How do I test if two dates are within a certain tolerance in NUnit? - nunit

How do I test if two dates are within a certain tolerance in NUnit?

You may want to look at the "Within" method that lives off of the Constraint object.
For example:
Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now.AddMilliseconds(1000)).Within(101));
It's usually used to give a tolerance to doubles and floats, but since in the end a DateTime is a double, it might suit your needs.

TimeSpan tolerance = new TimeSpan(0,1,0); // e.g. 1 minute
Assert.IsTrue((firstDateTime-SecondDateTime).Duration() > tolerance);

Convert your tolerance to Ticks and then use an And constraint. Something like;
long ticks = mydate.Ticks;
long tolerance = 1000;
Assert.That( ticks, Is.LessThan( ticks + tolerance ) & Is.GreaterThan( ticks - tolerance ) );
I would create an extension method or your own Assert to do this though.

Subtract one from the other, which gives you a TimeSpan value, use the TotalXYZ properties (like TotalMilliseconds) to get a value, use Math.Abs on it to convert it to a always-positive value, and check against your tolerance value.
For instance, if they need to be within 10 milliseconds of each other:
if (Math.Abs((dt1 - dt2).TotalMilliseconds) <= 10)
{
CloseEnough();
}

Related

PL/PGSQL function set upper and lower bound to an integer value

I am working on a pgsql function that calculates a score based on some logic. But one of the requirements is that a parameter after calculation should be in the range [100000, 9900000].
I can't figure out how to do this with existing functions, obviously possible with if conditions, any help?
v_running_sum += (30 - v_calcuated_value)* 100000;
I want v_running_sum to be in the range mentioned above. Is there any way to bound the value of the variable if lower than the lower bound (100,000) to 100,000 and vice versa for the upper bound?
This is how you can easily do this check, using a range:
SELECT 1 <# int4range(100000, 9900000,'[]');
There are many options how to implement this in your logic.
----edit----
When the outcome of a calculation should always be something between 100000 and 9900000, you can use this:
SELECT LEAST(GREATEST(var, 100000), 9900000);
Whatever you stick into "var", the result will always be between these boundaries
If you want a verbose solution use a CASE statement
case when val <= 100000 then 100000
when val >= 9900000 then 9900000
else val end as val

Seeking advice on how to stop a Timer used in a LinearProgressIndicator

I am using a LinearProgressIndicator to visually display a countdown of time and trigger a function at certain intervals. I am doing this by updating the LinearProgressIndicator's value prop using a state variable _progress that gets decremented by 0.01 each 100 milliseconds.
When I set conditions that were based on two decimal points, or even 0 if (_progress == 0.75), I discovered that the conditions were being skipped because the value of _progress was quickly becoming a much larger fraction that would not match my condition (e.g. 0.7502987777777). I assume this is an inherent issue of working with doubles, but my question then becomes, what is the best way to deal with this if you want to trigger actions based on the value of _progress? My approach is to broaden the conditions - for example if (_progress > 0.75 && _progress < 0.76).
Any tips/advice would be appreciated.
Thanks.
When dealing with floating-point values, you often cannot depend on strict equality. Instead you should check if the floating-point value you have is within a certain tolerance of the desired value. One approach:
bool closeTo(double value1, double value2, [double epsilon = 0.001]) =>
(value1 - value2).abs() <= epsilon;
if (closeTo(_progress, 0.75)) {
// Do something.
}
(package:matcher has a similar closeTo function for matching values in tests.)
Arguably, since floating-point values are floating, your tolerance should depend on the magnitude of the values.
In your case, you alternatively should strongly consider avoiding floating-point values for internal state: use fixed-point values by multiplying everything by 100 and using ints instead. That is, let _progress be an int, decrement it by 1 every 100 ms, and then you can compare against 75 or other values directly and exactly. This additionally would have the advantage of not accumulating floating-point error when you repeatedly decrement _progress. If you need to present _progress to the user or pass it to LinearProgressIndicator, use _progress / 100 instead.

How are min and max of cumulative variables assigned?

I created a routing problem and added some dimension to it. A solution assignment is found and I want to know the cumulative value at each index. I noticed that the CumulVar of an assignment does not only have a Value method but also Min and Max methods. Apparently the cumulative variables are implemented in such a way that they can represent intervals. I can see how setting
slack_max>0
fix_start_cumul_to_zero=False
introduces an ambiguity for the cumulative variables as their is a choice in how to start and how much slack to add at each stop. But
Question: How are the Min and Max at each index computed?
You can get the Min and Max range of a given node index from solution.Min(dimension.Cumulvar(index))
Note you'll get Min and Max exactly the same when slack_max=0 unless you know something I don't ;)
Assuming you are using an output solution object solution and a time dimension time_dimension, this will store em as a dict with min-max tuples, you may wish to adapt the output format however you wish:
time_dict = {}
for vehicle_id in range(num_vehicles):
vehicle_time_dict={}
index = routing.Start(vehicle_id)
start_time = solution.Min(time_dimension.CumulVar(index))
vehicle_time_dict[index]=(index_min,index_max)
while not routing.isEnd(index):
previous_index = index
index = solution.Value(routing.NextVar(index))
index_min = solution.Min(time_dimension.CumulVar(index))
index_max = solution.Max(time_dimension.CumulVar(index))
vehicle_time_dict[index]=(index_min,index_max)
time_dict[vehicle_id]=vehicle_time_dict
routing.IsEnd(index) returns True if it's the last index of that vehicle's route (or anywhere after the last index, so if it's 10 nodes long:
routing.IsEnd(8) will return False,
routing.IsEnd(9) will return True,
routing.IsEnd(10) will also return True, etc)

How to display datetime() value up to milliseconds

I have two questions:
In the following MATLAB code x is a date time value of the format "datetime(Y,M,D,H,MI,S,MS)". The display(x) command displays '00:00:00'. However the 'if condition' displays 'Well received!' which means the real value of x is greater than 0 as opposed to '00:00:00' displayed by the display(x) command. Please suggest how I could display the full value of x up to milliseconds or microseconds.
How can I save '0000,00,00,00,00,00,200' as a date time value?
send = datetime(2016,08,31,06,01,00,00);
receive=datetime(2016,08,31,06,01,00,100);
x=receive-send;
display(x);
if (x>0)
disp('Well received!')
else
disp('Late!')
end
The solution of your first question is, that you might convert your datetime-variable to a formatted string:
disp(datestr(x,'HH:MM:SS:FFF'));
This gives you the output 00:00:00:100, because F is the symbolic identifier for milliseconds.
Furthermore it seems, datetime doesn't support milliseconds. In this case you should use the MATLAB serial date number:
http://de.mathworks.com/help/matlab/ref/datenum.html
The variable x created in your example is a duration object. You can specify the display of milliseconds (as well as smaller decimal fractions of seconds) by setting the Format property.
>> x.Format = 'hh:mm:ss.SSS';
>> display(x);
x = 00:00:00.100
This is presumably also what you want when you ask about saving '0000,00,00,00,00,00,200' as a date time value. It's not really a date and time but a duration, and can be created using the duration constructor.
>> duration(00,00,00,200,'Format','hh:mm:ss.SSS')
ans =
00:00:00.200
Most operations acting on these duration objects will work as expected, such as comparison with the > operator:
>> x > duration(00,00,00,200)
ans =
0

Is there a range data structure in Scala?

I'm looking for a way to handle ranges in Scala.
What I need to do is:
given a set of ranges and a range(A) return the range(B) where range(A) intersect range (B) is not empty
given a set of ranges and a range(A) remove/add range(A) from/to the set of ranges.
given range(A) and range(B) create a range(C) = [min(A,B), max(A,B)]
I saw something similar in java - http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/RangeSet.html
Though subRangeSet returns only the intersect values and not the range in the set (or list of ranges) that it intersects with.
RangeSet rangeSet = TreeRangeSet.create();
rangeSet.add(Range.closed(0, 10));
rangeSet.add(Range.closed(30, 40));
Range range = Range.closed(12, 32);
System.out.println(rangeSet.subRangeSet(range)); //[30,32] (I need [30,40])
System.out.println(range.span(Range.closed(30, 40))); //[12,40]
There is an Interval[A] type in the spire math library. This allows working with ranges of arbitrary types that define an Order. Boundaries can be inclusive, exclusive or omitted. So e.g. (-∞, 0.0] or [0.0, 1.0) would be possible intervals of doubles.
Here is a library intervalset for working with sets of non-overlapping intervals (IntervalSeq or IntervalTrie) as well as maps of intervals to arbitrary values (IntervalMap).
Here is a related question that describes how to use IntervalSeq with DateTime.
Note that if the type you want to use is 64bit or less (basically any primitive), IntervalTrie is extremely fast. See the Benchmarks.
As Tzach Zohar has mentioned in the comment, if all you need is range of Int - go for scala.collection.immutable.Range:
val rangeSet = Set(0 to 10, 30 to 40)
val r = 12 to 32
rangeSet.filter(range => range.contains(r.start) || range.contains(r.end))
If you need it for another underlying type - implement it by yourself, it's easy for your usecase.