Exemple #1
0
 public Note(Pitch pitch, Duration?duration, Scale?scale, bool dotted)
 {
     Pitch    = pitch;
     Duration = duration;
     Scale    = scale;
     Dotted   = dotted;
 }
Exemple #2
0
 public Entry(string password, uint?numberOfAccesses, Duration?validFor, IClock clock)
 {
     Password         = password;
     NumberOfAccesses = numberOfAccesses;
     CreatedAt        = clock.GetCurrentInstant();
     ValidUntil       = CreatedAt + validFor;
 }
 public ReservationQuery CollideWith(Instant from, Instant to, Duration?bufferTime = null)
 {
     From   = from;
     To     = to;
     Buffer = bufferTime.GetValueOrDefault(Duration.Zero);
     return(this);
 }
Exemple #4
0
        private bool ShouldNotify(Event evt)
        {
            if (evt.GetIsOccuring())
            {
                return(true);
            }

            Duration?timeTillEvent = evt.GetDurationTill();

            // Event in the past.
            if (timeTillEvent == null)
            {
                return(false);
            }

            Duration?notifyDuration = evt.GetNotifyDuration();

            // never notify
            if (notifyDuration == null)
            {
                return(false);
            }

            // instant notify
            if (notifyDuration.Value.TotalSeconds == 0)
            {
                return(true);
            }

            return(timeTillEvent.Value <= notifyDuration.Value);
        }
        /// <summary>
        /// This function
        /// </summary>
        /// <returns></returns>
        private TamperDetection detectTampering()
        {
            lock (lockObj)
            {
                Duration currentDifference = measureDifference();

                if (measuredDifference.HasValue)
                {
                    long totalMillisMeasured, totalMillisCurrent;
                    totalMillisMeasured = (long)measuredDifference.Value.TotalMilliseconds;
                    totalMillisCurrent  = (long)currentDifference.TotalMilliseconds;

                    long millisDifference = totalMillisMeasured - totalMillisCurrent;

                    // No normal clock should have a jitter over a thousand milliseconds. If the difference
                    if (Math.Abs(millisDifference) > 60000)
                    {
                        measuredDifference = currentDifference;
                        return(TamperDetection.TimeTampering);
                    }
                }

                var currentZone = tzProvider.GetSystemDefault();
                if (lastDetectedZone.Id != currentZone?.Id)
                {
                    lastDetectedZone = currentZone;
                    return(TamperDetection.ZoneTampering);
                }
                else
                {
                    return(TamperDetection.NoTampering);
                }
            }
        }
        public override async Task <VTQs> ReadVariablesSync(VariableRefs variables, Duration?timeout = null)
        {
            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }
            var request = MakeSessionRequest <ReadVariablesSyncReq>();

            request.Variables = variables;
            request.Timeout   = timeout;
            Task <VTQs> task = Post <VTQs>(request, binaryDeserializer: BinSeri.VTQ_Serializer.Deserialize);

            if (timeout.HasValue)
            {
                if (task == await Task.WhenAny(task, Task.Delay(timeout.Value.ToTimeSpan())))
                {
                    return(await task);
                }
                else
                {
                    throw new Exception("Timeout");
                }
            }
            else
            {
                return(await task);
            }
        }
        /// <summary>
        /// Update an existing user.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="username">The username of the user to update.</param>
        /// <param name="password">The password for the user.</param>
        /// <param name="policies">List of policies. If set to empty, only the default policy will be applicable to the user.</param>
        /// <param name="ttl">The lease duration which decides login expiration.</param>
        /// <param name="maxTtl">Maximum duration after which login should expire.</param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static async Task UpdateUserpassUserAsync(this VaultClient client,
                                                         string username,
                                                         string password             = null,
                                                         string[] policies           = null,
                                                         Duration?ttl                = null,
                                                         Duration?maxTtl             = null,
                                                         UserpassAuthOptions options = null)
        {
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException(nameof(username));
            }

            var payload = new UserData
            {
                Password = password,
                Ttl      = ttl,
                MaxTtl   = maxTtl,
            };

            if (policies?.Length > 0)
            {
                payload.Policies = string.Join(",", policies);
            }

            var mountName = options?.MountName ?? DefaultMountName;

            await((IProtocolSource)client).Protocol
            .SendPostAsync <NoContentResponse>(
                $"auth/{mountName}/users/{username}",
                payload,
                options: options);
        }
 public PasswordInput(string password, uint?numberOfAccesses, Duration?duration = null, Guid?sessionId = null)
 {
     Password         = password;
     NumberOfAccesses = numberOfAccesses;
     Duration         = duration;
     SessionId        = sessionId;
 }
        /// <summary>
        /// Create a new user. Honors the capabilities inside ACL policies.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="username">The username for the user.</param>
        /// <param name="password">The password for the user, required when creating the user.</param>
        /// <param name="policies">List of policies. If set to empty, only the default policy will be applicable to the user.</param>
        /// <param name="ttl">The lease duration which decides login expiration.</param>
        /// <param name="maxTtl">Maximum duration after which login should expire.</param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static async Task CreateUserpassUserAsync(this VaultClient client,
                                                         string username,
                                                         string password,
                                                         string[] policies           = null,
                                                         Duration?ttl                = null,
                                                         Duration?maxTtl             = null,
                                                         UserpassAuthOptions options = null)
        {
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException(nameof(username));
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException(nameof(password));
            }

            // Create is the same as Update, only the initial password is required
            await UpdateUserpassUserAsync(client, username,
                                          password : password,
                                          policies : policies,
                                          ttl : ttl,
                                          maxTtl : maxTtl,
                                          options : options);
        }
 public static void AddObjectAnimationUsingKeyFrames <T, TValue>(this VisualState state, T target, Expression <Func <T, TValue> > targetProperty,
                                                                 Duration?duration, params ObjectKeyFrame[] keyFrames
                                                                 )
     where T : DependencyObject
 {
     state.GetStoryboard().AddObjectAnimationUsingKeyFrames(target, targetProperty, duration, keyFrames);
 }
Exemple #11
0
 public Scheduling(SchedulingMode mode, Duration?interval = null, Duration?offset = null, bool useTimestampFromSource = false)
 {
     Mode     = mode;
     Interval = interval;
     Offset   = offset;
     UseTimestampFromSource = useTimestampFromSource;
 }
Exemple #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncTimer" /> class.
        /// </summary>
        /// <param name="callback">The asynchronous method to be executed.</param>
        /// <param name="period">The minimum gap between the start of the task invocation and the start of the previous task invocation (defautls to <see langword="null" /> which is equivalent to <see cref="TimeHelpers.InfiniteDuration" />).</param>
        /// <param name="dueTime">The due time between the last time the timeouts were changed and the start of the task invocation (defautls to <see langword="null" /> which is equivalent to <see cref="Duration.Zero" />).</param>
        /// <param name="minimumGap">The minimum gap between the start of the task invocation and the end of the previous task invocation (defautls to <see langword="null" /> which is equivalent to <see cref="Duration.Zero" />).</param>
        /// <param name="pauseToken">The pause token for pasuing the timer.</param>
        /// <param name="errorHandler">The optional error handler.</param>
        public AsyncTimer(
            [NotNull] AsyncTimerCallback callback,
            Duration?period                 = null,
            Duration?dueTime                = null,
            Duration?minimumGap             = null,
            PauseToken pauseToken           = default(PauseToken),
            Action <Exception> errorHandler = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            long timeStamp = HighPrecisionClock.Instance.NowTicks;

            _callback   = callback;
            _pauseToken = pauseToken;
            _timeOuts   = new TimeOuts(
                period ?? TimeHelpers.InfiniteDuration,
                dueTime ?? Duration.Zero,
                minimumGap ?? Duration.Zero,
                timeStamp);

            _cancellationTokenSource  = new CancellationTokenSource();
            _timeOutsChanged          = new CancellationTokenSource();
            _callbackCompletionSource = null;

            _errorHandler = errorHandler;

            Task.Run(() => TimerTask(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
        }
Exemple #13
0
            public IList <ReadTask> ReadItems(IList <ReadRequest> values, Duration?timeout)
            {
                Func <Task <VTQ[]>, DataItemValue[]> f = task => {
                    VTQ[] vtqs = task.Result;
                    if (vtqs.Length != values.Count)
                    {
                        throw new Exception("ReadDataItems returned wrong number of VTQs");
                    }
                    DataItemValue[] divalues = new DataItemValue[vtqs.Length];
                    for (int i = 0; i < vtqs.Length; ++i)
                    {
                        divalues[i] = new DataItemValue(values[i].ID, vtqs[i]);
                    }
                    return(divalues);
                };

                if (ItemGroups.Length == 1 || values.Count == 1)
                {
                    string                 group = ItemGroups.Length == 1 ? ItemGroups[0].ID : MapItem2GroupID[values[0].ID];
                    Task <VTQ[]>           t     = Instance.ReadDataItems(group, values, timeout);
                    Task <DataItemValue[]> tt    = t.ContinueWith(f);
                    return(new ReadTask[] { new ReadTask(tt, values.Select(x => x.ID).ToArray()) });
                }
                else
                {
                    return(values.GroupBy(x => MapItem2GroupID[x.ID]).Select(group => {
                        ReadRequest[] items = group.ToArray();
                        Task <VTQ[]> t = Instance.ReadDataItems(group.Key, items, timeout);
                        Task <DataItemValue[]> tt = t.ContinueWith(f);
                        return new ReadTask(tt, items.Select(x => x.ID).ToArray());
                    }).ToArray());
                }
            }
        private bool CanOptimizeAnimation(KeyFrameAnimationSceneNode nodeToTest)
        {
            TimelineSceneNode.PropertyNodePair elementAndProperty = nodeToTest.TargetElementAndProperty;
            if (elementAndProperty.PropertyReference == null || FromToAnimationSceneNode.GetFromToAnimationForType((ITypeId)elementAndProperty.PropertyReference.ValueTypeId, nodeToTest.ProjectContext) == null || (nodeToTest.KeyFrameCount != 1 || DesignTimeProperties.ExplicitAnimationProperty.Equals((object)elementAndProperty.PropertyReference[0])))
            {
                return(false);
            }
            KeyFrameSceneNode keyFrameAtIndex = nodeToTest.GetKeyFrameAtIndex(0);
            Duration?         nullable        = nodeToTest.GetLocalOrDefaultValueAsWpf(TimelineSceneNode.DurationProperty) as Duration?;
            bool flag = !nullable.HasValue || nullable.Value == Duration.Automatic || nullable.Value.HasTimeSpan && nullable.Value.TimeSpan.TotalSeconds == keyFrameAtIndex.Time;

            if (keyFrameAtIndex.InterpolationType != KeyFrameInterpolationType.Easing || !flag)
            {
                return(false);
            }
            foreach (IMemberId memberId in (IEnumerable <IProperty>)((DocumentCompositeNode)nodeToTest.DocumentNode).Properties.Keys)
            {
                switch (memberId.Name)
                {
                case "Duration":
                case "TargetName":
                case "TargetProperty":
                case "BeginTime":
                case "IsAnimationProxy":
                case "KeyFrames":
                case "ShouldSerialize":
                    continue;

                default:
                    return(false);
                }
            }
            return(true);
        }
Exemple #15
0
 /// <summary>
 ///     Match nullable <see cref="Duration" />
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 /// <exception cref="ArgumentNullException"></exception>
 public static DurationAssertions Should(this Duration?value)
 {
     if (value == null)
     {
         throw new ArgumentNullException(nameof(value));
     }
     return(new DurationAssertions(value));
 }
Exemple #16
0
        public async Task <T> WaitFor(Func <T, bool> predicate, Duration?timeout = null, CancellationToken ct = default)
        {
            var timeoutTask = Task.Delay(timeout?.ToTimeSpan() ?? TimeSpan.FromMilliseconds(-1), ct);
            var tcs         = new TaskCompletionSource <T>();

            ValueTask Handler(T e)
            {
                tcs.SetResult(e);
                return(default);
        /// <summary>
        /// Creates a <see cref="DurationGenerator"/> using the given max duration.
        /// </summary>
        /// <param name="max">A positive duration. If <c>null</c>, a max duration of two standard days is used.</param>
        /// <exception cref="ArgumentException"><paramref name="max"/> is negative.</exception>
        public DurationGenerator(Duration?max = null)
        {
            if (max < Duration.Zero)
            {
                throw new ArgumentException("The max duration must be non-negative.", nameof(max));
            }

            Max = max ?? Duration.FromDays(2);
        }
Exemple #18
0
        private void buttonDone_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;

            if (!checkBoxIndefinite.Checked)
            {
                Timeout = Duration.FromTimeSpan(new TimeSpan((int)numericUpDownHours.Value, (int)numericUpDownMinutes.Value, (int)numericUpDownSeconds.Value));
            }
        }
Exemple #19
0
 static public DoubleAnimation slideAnimacionF(double to, Duration?duration = null)
 {
     return(new DoubleAnimation()
     {
         Duration = duration != null ? (Duration)duration : slideDuracion,
         EasingFunction = EasingFunc,
         To = to
     });
 }
Exemple #20
0
        public static string?GetDurationString(Duration?timeNull)
        {
            if (timeNull == null)
            {
                return(null);
            }

            Duration      time    = (Duration)timeNull;
            StringBuilder builder = new StringBuilder();

            if (time.Days == 0 && time.Hours == 0 && time.Minutes == 0)
            {
                return(" now");
            }

            if (time.Days == 1)
            {
                builder.Append(" ");
                builder.Append(time.Days);
                builder.Append(" day");
            }
            else if (time.Days > 1)
            {
                builder.Append(" ");
                builder.Append(time.Days);
                builder.Append(" days");
            }

            if (time.Hours == 1)
            {
                builder.Append(" ");
                builder.Append(time.Hours);
                builder.Append(" hour");
            }
            else if (time.Hours > 1)
            {
                builder.Append(" ");
                builder.Append(time.Hours);
                builder.Append(" hours");
            }

            if (time.Minutes == 1)
            {
                builder.Append(" ");
                builder.Append(time.Minutes);
                builder.Append(" minute");
            }
            else if (time.Minutes > 1)
            {
                builder.Append(" ");
                builder.Append(time.Minutes);
                builder.Append(" minutes");
            }

            return(builder.ToString());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RegionTimer"/> class.
 /// </summary>
 /// <param name="onDisposed">The disposed delegate is called once on disposal.</param>
 /// <param name="warningDuration">Duration of the warning.</param>
 /// <param name="criticalDuration">Duration of the critical.</param>
 public RegionTimer(
     [CanBeNull] RegionTimerDisposedDelegate onDisposed = null,
     Duration?warningDuration  = null,
     Duration?criticalDuration = null)
 {
     Started          = HighPrecisionClock.Instance.Now;
     _onDisposed      = onDisposed;
     WarningDuration  = warningDuration ?? PerformanceConfiguration.DefaultWarningDuration;
     CriticalDuration = criticalDuration ?? PerformanceConfiguration.DefaultCriticalDuration;
 }
        public void OnlySingleNotesWithSpaces(string note, Pitch pitch, Duration?duration, Scale?scale, bool dotted)
        {
            var result = Rtttl.TryParse($"::{note}", out var rtttl);

            using var _ = new AssertionScope();
            result.Should().Be(true);
            rtttl !.Notes.Should().HaveCount(1)
            .And.BeEquivalentTo(
                new Note(pitch, duration, scale, dotted));
        }
Exemple #23
0
        public void SetNotifyDuration(Duration?value)
        {
            if (value == null)
            {
                this.NotifyDurationStr = null;
                return;
            }

            this.NotifyDurationStr = DurationPattern.Roundtrip.Format((Duration)value);
        }
Exemple #24
0
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Duration?d = (Duration?)value;

            if (d.HasValue == true)
            {
                writer.WriteValue(d.Value.ToString());
            }
            else
            {
                writer.WriteNull();
            }
        }
Exemple #25
0
        public void ReadXml(XmlReader reader)
        {
            string m = reader["mode"];

            switch (m)
            {
            case "None":
                Mode = HistoryMode.None;
                break;

            case "Complete":
                Mode = HistoryMode.Complete;
                break;

            case "ValueOrQualityChanged":
                Mode = HistoryMode.ValueOrQualityChanged;
                break;

            case "Interval":
                Mode = HistoryMode.Interval;
                break;

            case "IntervalExact":
                Mode = HistoryMode.IntervalExact;
                break;

            case "IntervalOrChanged":
                Mode = HistoryMode.IntervalOrChanged;
                break;

            case "IntervalExactOrChanged":
                Mode = HistoryMode.IntervalExactOrChanged;
                break;

            default:
                throw new Exception("Unknown HistoryMode: " + m);
            }
            string intv = reader["interval"];

            if (intv != null)
            {
                Interval = Duration.Parse(intv);
            }
            string off = reader["offset"];

            if (off != null)
            {
                Offset = Duration.Parse(off);
            }
            reader.Read();
        }
Exemple #26
0
        public static void AddObjectAnimationUsingKeyFrames <T, TValue>(this Storyboard storyboard, T target, Expression <Func <T, TValue> > targetProperty,
                                                                        Duration?duration, params ObjectKeyFrame[] keyFrames
                                                                        )
            where T : DependencyObject
        {
            var animation = new ObjectAnimationUsingKeyFrames();

            animation.Duration = duration ?? new Duration(TimeSpan.FromSeconds(0));
            foreach (var keyFrame in keyFrames)
            {
                animation.KeyFrames.Add(keyFrame);
            }
            storyboard.AddAnimation(animation, target, targetProperty);
        }
Exemple #27
0
        public static Duration GetDuration(string input, Duration?def = null)
        {
            int?val = GetNullableNonNegativeInt(input);

            if (val.HasValue)
            {
                return(Duration.FromSeconds(val.Value));
            }
            if (def.HasValue)
            {
                return(def.Value);
            }
            throw new ArgumentException($"{input} could not be parsed into a duration in seconds.");
        }
        private async Task Start0(bool startImmediately, CancellationToken ct)
        {
            bool     wait         = !startImmediately;
            Duration getOfs       = Duration.Zero;
            Duration?waitOverride = null;

            while (true)
            {
                if (wait)
                {
                    await _scheduler.ScheduleOne(waitOverride ?? Duration.FromMinutes(2), Duration.FromSeconds(4), ct).ConfigureAwait(_taskHelper);
                }
                wait = true;
                var count = (int)await _reader.CountAsync(ct).ConfigureAwait(_taskHelper);

                Instant now = _time.GetCurrentInstant();
                Instant from;
                if (count > 0)
                {
                    var last = await(await _reader.ReadAsync(count - 1).ConfigureAwait(_taskHelper)).Last().ConfigureAwait(_taskHelper);
                    from = last.Update + getOfs;
                }
                else
                {
                    from = now - Duration.FromHours(1);
                }
                Instant to = from + Duration.FromHours(1);
                if (to > now)
                {
                    to = now;
                }
                var data = await _freq.GetAsync(from + Duration.FromSeconds(1), to, ct).ConfigureAwait(_taskHelper);

                if (data.Count == 0 && to < now - Duration.FromDays(1))
                {
                    // If no data, and we're at least a day in the past, then skip forward an hour.
                    // This is probably because data is missing.
                    getOfs      += Duration.FromHours(1);
                    waitOverride = Duration.FromSeconds(20);
                }
                else
                {
                    getOfs       = Duration.Zero;
                    waitOverride = null;
                }
                await _writer.AppendAsync(data, ct).ConfigureAwait(_taskHelper);
            }
        }
        internal IterationCounterSnapshot([NotNull] IterationCounter counter)
        {
            if (counter == null)
            {
                throw new ArgumentNullException(nameof(counter));
            }

            IterationsPerSecond        = counter.IterationsPerSecond;
            MaxIterationsPerSecond     = counter.MaxIterationsPerSecond;
            MinIterationsPerSecond     = counter.MinIterationsPerSecond;
            AverageIterationsPerSecond = counter.AverageIterationsPerSecond;

            TotalIterationsDone = counter.TotalIterationsDone;

            mElapsed = counter.GetElapsedDuration();
        }
Exemple #30
0
        public static DoubleAnimation CreateDoubleAnimation(double from, double to, FillBehavior?fillBehavior = null,
                                                            Action completeAction = null,
                                                            Duration?duration     = null, IEasingFunction easingFunction = null)
        {
            var animation = new DoubleAnimation(from, to, duration ?? ViewConstants.DefaultAnimationDuration)
            {
                FillBehavior   = fillBehavior ?? FillBehavior.HoldEnd,
                EasingFunction = easingFunction ?? ViewConstants.DefaultEasingFunction
            };

            if (completeAction != null)
            {
                animation.Completed += (sender, e) => completeAction();
            }
            return(animation);
        }
Exemple #31
0
 public RepeatBehavior(float count)
 {
     myDuration = null;
     myCount = count;
 }
Exemple #32
0
 public void Finish()
 {
     for (int i = 0, j = Beats.Count; i < j; i++)
     {
         var beat = Beats[i];
         Chain(beat);
         beat.Finish();
         if (MinDuration == null || MinDuration.Value > beat.Duration)
         {
             MinDuration = beat.Duration;
         }
         if (MaxDuration == null || MaxDuration.Value < beat.Duration)
         {
             MaxDuration = beat.Duration;
         }
     }
 }
Exemple #33
0
 public RepeatBehavior(Duration duration)
 {
     myCount = null;
     myDuration = duration;
 }