I'm trying to understand gestures, but I'm having a hard time understanding how the they actually work.
I've put the following code in, but it's not returning what I would expect.
public void Rectangle_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("last positionX was {0}. Current positionX is {1}. Difference between the 2: {2}", _previousPositionX, e.Position.X, e.Position.X - _previousPositionX);
System.Diagnostics.Debug.WriteLine("delta x: {0}", e.Delta.Translation.X);
_previousPositionX = e.Position.X;
}
I would expect this code to print out something like
last positionX was 0. Current positionX is 23.
Difference between the 2: 23
delta x: 23
last positionX was 23. Current positionX is 33.
Difference between the 2: 10
delta x: 10
last positionX was 33. Current positionX is 53.
Difference between the 2: 20
delta x: 20
However what I'm getting is
last positionX was 298.787872314453. Current positionX is 314.760620117188.
Difference between the 2: 15.9727478027344
cumulative x: -181.818176269531
delta x: -44.5818138122559
last positionX was 314.760620117188. Current positionX is 326.009094238281.
Difference between the 2: 11.2484741210938
cumulative x: -210.036361694336
delta x: -28.2181797027588
last positionX was 326.009094238281. Current positionX is 350.893920898438.
Difference between the 2: 24.8848266601563
cumulative x: -212.509078979492
delta x: -2.47272729873657
Neither e.Delta.Translation.X or e.Cumulative.Translation.X seem to match the difference between what the e.Position.X was last time the eventhandler was called and the current time. This is all in one swipe gesture. How do I find out where the rectangle is at the start/end of the the ManipulationDelta and how far it has moved since the last one? I want to know where the current position of the rectangle is, because I don't want the user to be able to move it offscreen.
Thanks
Related
I am gathering data on a device, and after every second, I update a count and log it. I am now processing it, and am new to python, so I had a question as to whether it was possible to convert a numbered array [0,1,2,3,4,...1091,1092,1093,...] into a timestamp [00:00:01, 00:00:02, 00:00:03, 00:00:04, ... 00:18:11, 00:18:12, 00:18:13,...] for example.
If you could please lead me in the right direction, that would be very much appreciated!
p.s. In the future, I will be logging the data as a timestamp, but for now, I have 5 hours' worth of data that needs to be processed!
import datetime as dt
timestamp=[0,1,2,3,4,5,1092,1093]
print([dt.timedelta(seconds=ts) for ts in timestamp])
Happy Coding
If all you have is seconds, then you can just do simple arithmetic to convert them to minutes and hours:
inp = [0, 1, 2, 3, 4, 1091, 1092, 1093]
outp = [f'{secs // 3600:02}:{(secs // 60) % 60:02}:{secs % 60:02}' for secs in inp]
print(outp)
# ['00:00:00', '00:00:01', '00:00:02', '00:00:03', '00:00:04', '00:18:11', '00:18:12', '00:18:13']
Here, I use a list comprehension and, for each secs in the input, create a format string:
hours is secs // 3600 (that's integer floor division), because one hour is 3600 seconds
Minutes is (secs // 60) % 60 (this incorporates the modulo operator, which displays the remainder of secs // 60 after dividing it by 60 again). One minute is 60 seconds, but more than 60 minutes would be an hour, so we need to make sure to 'roll over' the counter every 60 minutes (which is what the mod is for).
Seconds is, of course, secs % 60, because a minute has 60 seconds and we want the counter to roll over.
The format string starts with f', and anything inside {} is an instruction to evaluate whatever's inside it, and insert that into the string. The syntax is {expression:format}, where display is an optional instruction for how to format the data (i.e. not just printing it out). And format can get complicated (look up a python f-string tutorial if you're curious about the specifics), but suffice it to say that in this case we use 02, which means that we want the output to be two characters in length, and padded with zeroes in case it's less than that.
I am making an overtime pay calculator in rust. I have the following code below:
let overhours = 40;
let overhoursFLOAT = overhours as f32;
if calcpay > overhours{
println!("You worked more than 40 hours!");
let overmath = floathours - overhoursFLOAT as f32;
println!("You worked {} extra hours.",overmath);
let overpay = overmath * 1.5;
floatpay = floatpay + overpay;
}
else{println!("You did not work more than 40 hours. Therefore, your overtime pay will not be calculated.");}
Everytime i run it, the hours i input (I do 10) is under 40, and the if statement code runs anyway. It ends up looking like this:
How much do you get paid per hour?: 9
Hourly pay: 9
How much did you work?: 10
Hourly pay: 9
Hours worked: 10
Your calculated pay is $90
You worked more than 40 hours!
You worked -30 extra hours.
Am i using the operators wrong? How can i fix this?
you are comparing calcpay with overhours and calcpay equals 90. I assume what you wanted is to compare overhours with hours worked instead.
I need more efficient code which does the same thing I already have, but better.
I made a dynamic lighting system for my game. The way I currently have it programmed, the lighting values update each hour.
The time is blitted onto a monitor in-game and 'self.custom' is used in screen.fill() before a background with transparent sky (which also changes colour) is placed in front of it.
But I only wrote it this way as a prototype to test other features faster. It looks messy as code and I would also rather have the sky fluidly changing after every 56 ticks (minimum possible), rather than in larger time blocks of 600 ticks.
I divided 14400 by 255 (RGB values range) to get 56 (as an int) but my brain's fried and I can't think what I need to do with those values.
Here's the way it currently looks -
if self.time in range(0, 599):
self.showTime = '12 AM'
self.custom = (0,0,0)
elif self.time in range(600, 1199):
self.custom = (24,24,24)
self.showTime = '1 AM'
...
etc...
I hope I explained well enough what the problem is and what I want?
You could define everything up front (either as a dict, as I've done here, or just as a tuple/list):
timeData = [
{'showTime': '12 AM', 'custom': (0,0,0)},
{'showTime': '1 AM', 'custom': (24,24,24)},
...
]
and then use integer division to check what index in that list the time should correspond to:
idx = (self.time // 56) % len(timeData) # 0 if time < 56
# 1 if 56 <= time < 112
# ...
self.showTime = timeData[idx]['showTime']
self.custom = timeData[idx]['custom']
That's assuming that you're setting custom manually, and not doing a solid gradient from black to white. If you are, then you could omit putting that in timeData, and just calculate it based on idx, which would be conceptually easier than doing it based directly on self.time:
self.custom = (20 * idx,) * 3 # make 3-tuple with 3 of the same value
If you want a gradient effect, you could calculate it every time you want the sky to update.
if self.time < (14400/2): #If the time is before midday
self.rgb_value = int(((14400/2)/255)*self.time) #Set the sky colour to a value between 0 and 255, where 0 is at midnight and 255 is at midday.
elif self.time == (14400/2): #If the time is midday
self.rgb_value = 255 #Midday is full brightness
elif self.time > (14400/2) and self.time < 14400: #If the time is after midday
self.rgb_value = int(((14400/2)/255)*-(self.time-14400)) #The code is similar to before midday, but subtract the full length from self.time, and invert the result, to get the time until midnight.
elif self.time == 14400: #If the time is midnight
self.rgb_value = 0 #It is dark at midnight
self.custom = (self.rgb_value,self.rgb_value,self.rgb_value) #Convert the value into a colour.
For the clock display, you can have a list like:
clockoptions = [ (0,599,"12 AM"),
(600,1199,"1 AM"),
...
]
and pull values from it every time the clock is updated using the code
for opt in clockoptions:
if self.time >= opt[0] and self.time <= opt[1]:
self.showTime = opt[2]
break #Stop the loop from continuing to iterate unnecessarily.
This code is untested but I hope this helps.
I have a homework assignment in which I have to write a program that outputs the change to be given by a vending machine using the lowest number of coins. E.g. £3.67 can be dispensed as 1x£2 + 1x£1 + 1x50p + 1x10p + 1x5p + 1x2p.
However, I'm not getting the right answers and suspect that this might be due to a rounding problem.
change=float(input("Input change"))
twocount=0
onecount=0
halfcount=0
pttwocount=0
ptonecount=0
while change!=0:
if change-2>=0:
change=change-2
twocount+=1
else:
if change-1>=0:
change=change-1
onecount+=1
else:
if change-0.5>=0:
change=change-0.5
halfcount+=1
else:
if change-0.2>=0:
change=change-0.2
pttwocount+=1
else:
if change-0.1>=0:
change=change-0.1
ptonecount+=1
else:
break
print(twocount,onecount,halfcount,pttwocount,ptonecount)
RESULTS:
Input: 2.3
Output: 10010
i.e. 2.2
Input: 3.4
Output: 11011
i.e. 3.3
Some actually work:
Input: 3.2
Output: 11010
i.e. 3.2
Input: 1.1
Output: 01001
i.e. 1.1
Floating point accuracy
Your approach is correct, but as you guessed, the rounding errors are causing trouble. This can be debugged by simply printing the change variable and information about which branch your code took on each iteration of the loop:
initial value: 3.4
taking a 2... new value: 1.4
taking a 1... new value: 0.3999999999999999 <-- uh oh
taking a 0.2... new value: 0.1999999999999999
taking a 0.1... new value: 0.0999999999999999
1 1 0 1 1
If you wish to keep floats for output and input, multiply by 100 on the way in (cast to integer with int(round(change))) and divide by 100 on the way out of your function, allowing you to operate on integers.
Additionally, without the 5p, 2p and 1p values, you'll be restricted in the precision you can handle, so don't forget to add those. Multiplying all of your code by 100 gives:
initial value: 340
taking a 200... new value: 140
taking a 100... new value: 40
taking a 20... new value: 20
taking a 20... new value: 0
1 1 0 2 0
Avoid deeply nested conditionals
Beyond the decimal issue, the nested conditionals make your logic very difficult to reason about. This is a common code smell; the more you can eliminate branching, the better. If you find yourself going beyond about 3 levels deep, stop and think about how to simplify.
Additionally, with a lot of branching and hand-typed code, it's very likely that a subtle bug or typo will go unnoticed or that a denomination will be left out.
Use data structures
Consider using dictionaries and lists in place of blocks like:
twocount=0
onecount=0
halfcount=0
pttwocount=0
ptonecount=0
which can be elegantly and extensibly represented as:
denominations = [200, 100, 50, 10, 5, 2, 1]
used = {x: 0 for x in denominations}
In terms of efficiency, you can use math to handle amounts for each denomination in one fell swoop. Divide the remaining amount by each available denomination in descending order to determine how many of each coin will be chosen and subtract accordingly. For each denomination, we can now write a simple loop and eliminate branching completely:
for val in denominations:
used[val] += amount // val
amount -= val * used[val]
and print or show a final result of used like:
278 => {200: 1, 100: 0, 50: 1, 10: 2, 5: 1, 2: 1, 1: 1}
The end result of this is that we've reduced 27 lines down to 5 while improving efficiency, maintainability and dynamism.
By the way, if the denominations were a different currency, it's not guaranteed that this greedy approach will work. For example, if our available denominations are 25, 20 and 1 cents and we want to make change for 63 cents, the optimal solution is 6 coins (3x 20 and 3x 1). But the greedy algorithm produces 15 (2x 25 and 13x 1). Once you're comfortable with the greedy approach, research and try solving the problem using a non-greedy approach.
I'm using chisquare test for my data. I'm appending them in a loop in that way:
My .txt file looks like below, it has 180 rows with strings like that. Now I want to find the minimum value from those 180 rows, which is contained in parentesis, like in example below (15.745037950673217,), but I don't want to lose information which is assigned to a string in that row, which is 201701241800 Chi for 75 degree model.
...
201701241800 Chi for 75 degree model (15.745037950673217,)
201701241800 Chi for 76 degree model (16.014744332924252,)
...
The code I use looks like this:
o = chisquare(f_obs=fin, f_exp=y)
rows = str(Date) + str(Start_time_hours_format) + str(Start_time_minutes_format) + " Chi for {} degree model ".format(r) + str(o[0:1])
table.append(rows)
The problem is that number of those calculations is enormously huge. My task is to find minimum value in each iteration, which is defined by a for loop. Example above came from one iteration (There are 180 degree models in each iteration). The problem is I cannot use min(table) because I've got there strings, but I cannot erase them, because that information is important. Do you have any ideas how to find min value here? I mean specificly min value in parentesis.
If you have a list lst, min(lst) returns the minimum value without modifying the list. If you don't have a list, but objects from which you want to consider a value, let's say obj[i].myvalue, then you can do something like
min = 1000 # a huge number much bigger than your expected values
for o in obj:
if o.myvalue < min:
min = o.myvalue
which assigns to min the minimum value (probably it is not the best way, but it works for sure).
[I would be more specific, but it is not clear what kind of object you have to find the minimum of. Please consider to update your question to be more explicative.]
Ok, so I've found a way to solve this problem. Code below:
o = chisquare(f_obs=fin, f_exp=y)
rows = str(Date) + str(Start_time_hours_format) + str(Start_time_minutes_format) + " Chi for {} degree model ".format(r) + str(o[0:1])
print(rows)
table.append(rows)
with open('measurements.txt', 'a') as j:
j.write(min(table))
j.write('\n')
j.close()