How to write an openHAB rule which increments a number? - openhab

I want to write a Rule in openHAB2, which increments a counter of all group items.
The items:
Group counters
Number cnt1 (counters)
Number cnt2 (counters)
My try of a rule:
rule "Increase value .1 per minute"
when
Time cron "0 * * * * ?" or
System started
then
// Initialize. Necessary?
counters?.members.forEach(counter|
postUpdate(counter, 0.0)
)
counters?.members.forEach(counter|
postUpdate(counter, 0.1 + counter.state)
}
end
But that does not work. Exception:
Error during the execution of startup rule 'Increase value .1 per minute': Could not invoke method: org.eclipse.xtext.xbase.lib.DoubleExtensions.operator_plus(double,byte) on instance: null
I tried to explore the type of counter.state, and with logInfo(counter.state.class) it correctly logs ...DecimalType.

it seems the implicit type casting doesn't seem to work. If you'd change the rule to something like:
rule "Increase value .1 per minute"
when
Time cron "0 * * * * ?" or
System started
then
// Initialize. Necessary?
counters?.members.forEach(counter|
if (counter.state == null) {
postUpdate(counter, 0.0)
}
)
counters?.members.forEach(counter|
postUpdate(counter, 0.1 + (counter.state as DecimalType))
}
end
it should work. Hope this helps,
Thomas E.-E.

Related

Godot jump animation starting after a slight delay from the input

this is one of my first projects and i'm writing this code following a tutorial on YT. This tutorial does not include stuff about animation as far as i've seen, so i tried getting it done myself and the idle and run animations work. The jump also works but it starts after a slight delay and doesn't complete its cycle because the character lands too soon (for this last problem i'll try adjusting the speed of the animation)
extends Actor
func _physics_process(delta):
var direction = get_direction()
velocity = calculate_move_velocity(velocity, direction, maxSpeed)
velocity = move_and_slide(velocity, FLOOR_NORMAL) #Funzione che permette il movimento del personaggio
func get_direction() -> Vector2:
return Vector2(
Input.get_action_strength("right") - Input.get_action_strength("left"),
-1.0 if Input.is_action_just_pressed("jump") and is_on_floor() else 0.0
)
func calculate_move_velocity( #Movimento e Animazioni
linear_velocity: Vector2,
direction: Vector2,
maxSpeed: Vector2
) -> Vector2:
var new_velocity = linear_velocity #la new_velocity sarà il movimento lineare del personaggio
new_velocity.x = maxSpeed.x * direction.x
new_velocity.x = lerp(new_velocity.x, 0, 0.1)
if is_on_floor() and direction.x == 1.0: #muoversi verso destra
$AnimationPlayer.play("run")
$Sprite.scale.x = 1
elif is_on_floor() and direction.x == -1.0: #muoversi verso sinistra
$AnimationPlayer.play("run")
$Sprite.scale.x = -1
if is_on_floor() and direction.x == 0.0: #stare fermi
$AnimationPlayer.play("idle")
new_velocity.y += gravity * get_physics_process_delta_time()
if direction.y == -1.0: #saltare
new_velocity.y = maxSpeed.y * direction.y
if !is_on_floor() == false and Input.is_action_just_pressed("jump"):
$AnimationPlayer.play("jump")
return new_velocity
I see a lot of little things, will go over them one by one.
Is on floor?
The value is_on_floor() is updated when you call move_and_slide(...). But you are calling is_on_floor() before calling move_and_slide(...), which means it is operating the value of the prior physics frame. In fact, you want move_and_slide(...) to hit the ground (and thus, you probably want to apply gravity first).
This by it self is not a big deal. It is mostly noticeable for frame perfect jump, but still.
Lerp?
I'm looking at this line:
new_velocity.x = lerp(new_velocity.x, 0, 0.1)
Let us see the official documentation for lerp. It says the signature of lerp is:
Variant lerp ( Variant from, Variant to, float weight )
So we are interpolating from new_velocity.x to 0 with a weight of 0.1. I believe that is the same as:
new_velocity.x *= 0.9
Considering that other line also:
new_velocity.x = maxSpeed.x * direction.x
new_velocity.x = lerp(new_velocity.x, 0, 0.1)
We have:
new_velocity.x = maxSpeed.x * direction.x * 0.9
And considering that direction.x goes from -1 to 1, we have that new_velocity.x never reaches maxSpeed.x.
Why you want to do that? What do you think you are accomplishing?
Scale sprite?
You use $Sprite.scale.x = 1 and $Sprite.scale.x = -1. Sprites have a flip_h property strongly encouraged for this use.
Double negative?
You have this little nugget of code: !is_on_floor() == false.
Let us make a truth table:
is_on_floor() │ !is_on_floor() │ !is_on_floor() == false
──────────────┼────────────────┼──────────────────────────
false │ true │ false
true │ false │ true
As you can see, !is_on_floor() == false is the same as is_on_floor(). By the way, it returns bool, not Variant, in case that is your concern.
Playing animation multiple times
As you must be aware, calling AnimationPlayer.play multiple times with the same animation, is no problem at all. Which also means you don't need to check if the jump action was just pressed.
Separation of concerns
On one hand we have the concern of moving the kinematic body. On the other we have the concern of playing the animations. The first concern is a physics concern. It make sense to do it in _physics_process. The second concern is a visual concern. It makes sense to do it in _process instead.
Bringing it all together.
func _physics_process(delta:float) -> void:
velocity.y += gravity * delta
velocity = move_and_slide(velocity, Vector2.UP)
var h_direction = Input.get_action_strength("right") - Input.get_action_strength("left")
velocity.x = maxSpeed.x * h_direction
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = -maxSpeed.y
func _process(_delta:float) -> void:
if is_on_floor():
if velocity.x == 0.0:
$AnimationPlayer.play("idle")
$Sprite.flip_h = false
else:
$AnimationPlayer.play("run")
$Sprite.flip_h = velocity.x < 0.0
else:
$AnimationPlayer.play("jump")
Short and sweet.
Note: I replaced FLOOR_NORMAL with Vector2.UP. Also I removed the 0.9 introduced by lerp. Otherwise this should be the same, minus is_on_floor and animation play timing issues (I think this also differs on walls, there is is_on_wall() if that is an issue). However, we are talking of issues that at most expand one physics frame.
One more thing
Given that you are working with sprites in 2D. Consider using AnimatedSprite for the sprite animations instead of AnimationPlayer.
By the way, the timing of the animation may be the causing an apparent delay. For example if the first sprite of the jump animation matches - say - a frame of the idle animation. That is one whole frame that has to pass before we see a jump sprite. Double check that.

Update firebase database value every 5 seconds using Pub/sub OR Cloud Tasks?

I am new to Firebase and I am totally confused about what should I use. Here is my flow.
I have a collection score on firebase and it has values
- start_time
- count
- max_count
Now when start_time matches with the current time, I need to increment the count every five seconds till it matches max_count to the database. This should be in the backend. Now here I got confused. What can be suitable for this?
There are so many documents about Cloud Tasks and Pub/Sub.
If I Call the firebase function from Pub/Sub to update the count every 5 seconds then I will be paying for un-used compute time for calling a function.
I am not aware more about Cloud Tasks that is it matches my requirement? Can anyone please guide me?
Neither Cloud Tasks nor Pub/Sub would be the right solution for this and I wouldn't recommend using a cron-type service for such a menial task.
Instead consider moving the incremental logic to your client and just storing start_time and max_count in your database. Here's an example:
// Let's set a start_time 10 seconds in the future and pretend this was in the database
const start_time = Math.floor((new Date()).getTime() / 1000) + 10;
// Pretend this came from the database, we only want to iterate 10 times
const max_count = 10;
let prev_count = 0;
document.write("Waiting 10 seconds before starting<br />");
// Let's iterate once a second until we reach the start_time
let interval = setInterval(() => {
const now = Math.floor((new Date()).getTime() / 1000);
// If it's not start time, exit
if (now < start_time) return;
// Determine the count by dividing by 5 seconds
let count = Math.floor((now - start_time) / 5);
if (count > prev_count) {
document.write(`Tick: ${count}<br />`);
}
prev_count = count;
if (count >= max_count) {
clearInterval(interval);
}
}, 1000);
If you need the count stored in the database, have it update the count value in your database each time it increments.

i want to add increment of 6% to the return result from the query

<td>
<strong>
Rs #(Model.lstItem.Sum(c => c._product.option != null
? (c._product.option.Price * c.Quantity)
: (c._product.product.Price * c.Quantity))
- (Model.coupon != null ? (int)Model.coupon.Discount : 0))
</strong>
</td>
first of all let me tell you i am totally new in asp.net mvc..
Now my question is i have the above query which is returning total after multiplying price and quantity. now what i want is i want to increment 6% of pricequantity to the pricequanity..
The final result will be like (price * quantity) + 6% of price * quanity..
i hope you guys understand my question
You can just do this:
(price * quantity) + (((price * quantity)/100) * 6))
You shouldn't keep these constants in the View. If you have these calculations in multiple places and you wanted to change the percentage to 7% in the future, you'd have to change everywhere. So, it should either come from your database, or a config file or a constants class.
So, the easiest way to do this is to create a static class called ApplicationConstants in a Common folder or Utility folder.
public static class ApplicationConstants
{
public const int ProfitPercentage = 6;
}
Then in your View,
#using YourAppName.Common
<td>
<strong>
Rs #(
(1 + ApplicationConstants.ProfitPercentage / 100) *
(Model.lstItem.Sum(c => c._product.option != null
? (c._product.option.Price * c.Quantity)
: (c._product.product.Price * c.Quantity)))
- (Model.coupon != null ? (int)Model.coupon.Discount : 0))
</strong>
</td>

Difference between startDate and endDate-Symfony

Can someone assist me with this, I have a student table and I want to ensure that the user enters a date range from now to 3 months. I tried this but it didn't give me the results I wanted. Thinking about using datediff but not sure where I would put it. Is there another way like using a custom validation to validate the date.
* #Assert\Range
* (
* min= "today", max="+3 months"
* )
Error message:
This value should be a valid number.
#Assert\Callback(methods={"validatePayrollPeriod"})
public function validatePayrollPeriod(ExecutionContextInterface $context) {
$days = $this->startdate->diff($this->enddate)->days;
if ($days <= 7 || $days > 14) {
$context->buildViolation('Not a valid payroll period.')
->atPath('enddate')
->addViolation();
}
}
You could try to make a validation in your setter.
Something like
public function setEndDate($endDate)
{
if(your end date - your start date < 3){
$this->endDate= $endDate;
}else{
Throw whatever exepection you cant
}
return $this;
}

Asp.Net MVC timespan

I have a application in which users need to fill out a timesheet for the amount of work that they have completed against a client. I currently use Timespan which works well up to a certain point.
The issue that I am currently having is that if a user has to put 4 hours or more a day against a customer it fails. The current message i am getting is SqlDbType.Time overflow. Value '1.04:00:00' is out of range. Must be between 00:00:00.0000000 and 23:59:59.9999999.
This will only be for my total which adds up all the days.
What I have is this
Model:
public TimeSpan Total
{
get
{
TimeSpan result = new TimeSpan(Monday.Ticks
+ Tuesday.Ticks
+ Wednesday.Ticks
+ Thursday.Ticks
+ Friday.Ticks
+ Saturday.Ticks
+ Sunday.Ticks);
return (result);
}
set
{
TimeSpan result = new TimeSpan(Monday.Ticks
+ Tuesday.Ticks
+ Wednesday.Ticks
+ Thursday.Ticks
+ Friday.Ticks
+ Saturday.Ticks
+ Sunday.Ticks);
}
}
I have tried removing .ticks to .Hours which partially works but gives me an excessive amount of 0s http://prntscr.com/anaigx
Please can someone advise.
The problem you have having is due to your definition of SqlDbType.Time.
This type can only be used for a "normal" time, like 15:36, or whatever, it cannot store number of hours.
If you want to store amount of hours you should either use float type to store hours or int (or bigint) to store ticks.

Resources