コード例 #1
0
        private void SwitchOnWatching(string[] validFileNames)
        {
            _triggerBasedUpdate = new Main.TriggerBasedUpdate(Current.TimerQueue)
            {
                MinimumWaitingTimeAfterUpdate       = TimeSpanExtensions.FromSecondsAccurate(_importOptions.MinimumWaitingTimeAfterUpdateInSeconds),
                MaximumWaitingTimeAfterUpdate       = TimeSpanExtensions.FromSecondsAccurate(Math.Max(_importOptions.MinimumWaitingTimeAfterUpdateInSeconds, _importOptions.MaximumWaitingTimeAfterUpdateInSeconds)),
                MinimumWaitingTimeAfterFirstTrigger = TimeSpanExtensions.FromSecondsAccurate(_importOptions.MinimumWaitingTimeAfterFirstTriggerInSeconds),
                MinimumWaitingTimeAfterLastTrigger  = TimeSpanExtensions.FromSecondsAccurate(_importOptions.MinimumWaitingTimeAfterLastTriggerInSeconds),
                MaximumWaitingTimeAfterFirstTrigger = TimeSpanExtensions.FromSecondsAccurate(Math.Max(_importOptions.MaximumWaitingTimeAfterFirstTriggerInSeconds, _importOptions.MinimumWaitingTimeAfterFirstTriggerInSeconds))
            };

            _triggerBasedUpdate.UpdateAction += EhUpdateByTimerQueue;

            var directories = new HashSet <string>(validFileNames.Select(x => System.IO.Path.GetDirectoryName(x)));
            var watchers    = new List <System.IO.FileSystemWatcher>();

            foreach (var directory in directories)
            {
                try
                {
                    var watcher = new System.IO.FileSystemWatcher(directory)
                    {
                        NotifyFilter = System.IO.NotifyFilters.LastWrite | System.IO.NotifyFilters.Size
                    };
                    watcher.Changed += EhTriggerByFileSystemWatcher;
                    watcher.IncludeSubdirectories = false;
                    watcher.EnableRaisingEvents   = true;
                    watchers.Add(watcher);
                }
                catch (Exception)
                {
                }
            }
            _fileSystemWatchers = watchers.ToArray();
        }
コード例 #2
0
        private void ValidateBounds()
        {
            if (Minimum < TimeSpan.Zero)
            {
                Minimum = TimeSpan.Zero;
            }

            if (Maximum > TimeSpan.MaxValue)
            {
                Maximum = TimeSpan.MaxValue;
            }

            if (Maximum < Minimum)
            {
                Maximum = Minimum;
            }

            if (Value.HasValue)
            {
                Value = TimeSpanExtensions.CheckBound(Value.Value, Minimum, Maximum);
            }
            else
            {
                Value = Minimum;
            }
        }
コード例 #3
0
        private TimeSpan?GetStartTimeFromUrl(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                return(null);
            }

            if (!Uri.TryCreate(url, UriKind.Absolute, out Uri validUrl))
            {
                return(null);
            }

            string query = validUrl.Query;

            if (!string.IsNullOrWhiteSpace(query))
            {
                var queryParams = HttpUtility.ParseQueryString(validUrl.Query);

                if (queryParams.ContainsKey("t"))
                {
                    string durationStr = queryParams["t"];

                    if (!string.IsNullOrWhiteSpace(durationStr) && TimeSpanExtensions.TryParseTwitchFormat(durationStr, out TimeSpan startTime))
                    {
                        return(startTime);
                    }
                }
            }

            return(null);
        }
コード例 #4
0
        private TimeSpan IncreaseDelay(TimeSpan delay)
        {
            var multiplier     = minDelayMultiplier + ThreadSafeRandom.NextDouble() * (maxDelayMultiplier - minDelayMultiplier);
            var increasedDelay = delay.Multiply(multiplier);

            return(TimeSpanExtensions.Min(TimeSpanExtensions.Max(minDelay, increasedDelay), maxDelay));
        }
コード例 #5
0
        private void PreloadStreams()
        {
            IDictionary <ChannelIdentifier, short[]> output = new Dictionary <ChannelIdentifier, short[]>();

            foreach (var s in ActiveOutputStreams.Cast <HekaDAQOutputStream>())
            {
                s.Reset();
                var outputSamples = new List <short>();
                while (TimeSpanExtensions.FromSamples((uint)outputSamples.Count(), s.SampleRate).TotalSeconds < PRELOAD_DURATION_SECONDS) // && s.HasMoreData
                {
                    var nextOutputDataForStream = NextOutputDataForStream(s);
                    var nextSamples             = nextOutputDataForStream.DataWithUnits(HekaDAQOutputStream.DAQCountUnits).Data.
                                                  Select(
                        (m) => (short)m.QuantityInBaseUnit);

                    outputSamples = outputSamples.Concat(nextSamples).ToList();
                }

                if (!outputSamples.Any())
                {
                    throw new HekaDAQException("Unable to pull data to preload stream " + s.Name);
                }


                output[new ChannelIdentifier {
                           ChannelNumber = s.ChannelNumber, ChannelType = (ushort)s.ChannelType
                       }] =
                    outputSamples.ToArray();
            }

            Device.Preload(output);
        }
コード例 #6
0
        public TimeSpan Next(int attempt)
        {
            TimeSpan currentDelay;

            try
            {
                long multiple = checked (1 << attempt);

                currentDelay = _step.Multiply(multiple);

                if (currentDelay <= TimeSpan.Zero)
                {
                    throw new OverflowException();
                }
            }
            catch (OverflowException)
            {
                currentDelay = _maxDelay;
            }

            currentDelay = TimeSpanExtensions.Min(currentDelay, _maxDelay);

            if (_minDelay >= currentDelay)
            {
                throw new ArgumentOutOfRangeException($"minDelay {_minDelay}, currentDelay = {currentDelay}");
            }

            return(_random.NextTimeSpan(_minDelay, currentDelay));
        }
コード例 #7
0
        public void ToFriendlyString_MinutesAndSecondsLessThanOneHour_ShowAsMinutesAndSeconds(int minutes, int seconds, string expected)
        {
            var ts = TimeSpan.FromMinutes(minutes) + TimeSpan.FromSeconds(seconds);

            var actual = TimeSpanExtensions.ToFriendlyString(ts);

            Assert.Equal(expected, actual);
        }
コード例 #8
0
        public void ToFriendlyString_WholeHours_ShowAsMinutesAndSeconds(int hours, string expected)
        {
            var ts = TimeSpan.FromHours(hours);

            var actual = TimeSpanExtensions.ToFriendlyString(ts);

            Assert.Equal(expected, actual);
        }
コード例 #9
0
        void Timer_Tick(object?sender, EventArgs e)
        {
            DateTime now = DateTime.Now;

            timeSpan = now - startTime;

            txtTime.Text = TimeSpanExtensions.FormatTimeSpan(timeSpan);
        }
コード例 #10
0
        public void ToFriendlyString_HoursAndMinutes_ShowAsMinutesAndSeconds(int hours, int minutes, string expected)
        {
            var ts = new TimeSpan(hours, minutes, 0);

            var actual = TimeSpanExtensions.ToFriendlyString(ts);

            Assert.Equal(expected, actual);
        }
コード例 #11
0
 private static bool EqualMaxResponseTime(TimeSpan value1, TimeSpan value2)
 {
     if (TimeSpanExtensions.Divide(value1, 2.0) <= value2)
     {
         return(TimeSpanExtensions.Multiply(value1, 2.0) >= value2);
     }
     return(false);
 }
コード例 #12
0
        public void null_double_to_time_span()
        {
            double?inputFloat = null;

            var actual = TimeSpanExtensions.FromSeconds(inputFloat);

            Assert.AreEqual(null, actual);
        }
コード例 #13
0
        public void ToFriendlyString_WhenLessThanOneMinute_ShowAsSeconds(int seconds, string expected)
        {
            var ts = TimeSpan.FromSeconds(seconds);

            var actual = TimeSpanExtensions.ToFriendlyString(ts);

            Assert.Equal(expected, actual);
        }
コード例 #14
0
 private void SwitchOnWatching()
 {
     _triggerBasedUpdate = new Main.TriggerBasedUpdate(Current.TimerQueue)
     {
         MinimumWaitingTimeAfterUpdate = TimeSpanExtensions.FromSecondsAccurate(_importOptions.MinimumWaitingTimeAfterUpdateInSeconds),
         MaximumWaitingTimeAfterUpdate = TimeSpanExtensions.FromSecondsAccurate(Math.Max(_importOptions.MinimumWaitingTimeAfterUpdateInSeconds, _importOptions.MaximumWaitingTimeAfterUpdateInSeconds))
     };
     _triggerBasedUpdate.UpdateAction += EhUpdateByTimerQueue;
 }
コード例 #15
0
        private void PopulateSummary(IEnumerable <Span> spans)
        {
            foreach (var span in spans)
            {
                if (span.Tags.TryGetValue(CouchbaseTags.OperationId, out var id))
                {
                    OperationId = id.ToString();
                }

                switch (span.OperationName)
                {
                case CouchbaseOperationNames.RequestEncoding:
                    EncodingDuration += span.Duration;
                    break;

                case CouchbaseOperationNames.DispatchToServer:
                    DispatchDuration += span.Duration;

                    if (span.Tags.TryGetValue(CouchbaseTags.LocalAddress, out var local))
                    {
                        LastLocalAddress = local.ToString();
                    }

                    if (span.Tags.TryGetValue(Tags.PeerAddress, out var remote))
                    {
                        LastRemoteAddress = remote.ToString();
                    }

                    if (span.Tags.TryGetValue(CouchbaseTags.LocalId, out var localId))
                    {
                        LastLocalId = localId.ToString();
                    }

                    if (span.Tags.TryGetValue(CouchbaseTags.PeerLatency, out var duration))
                    {
                        if (TimeSpanExtensions.TryConvertToMicros(duration, out var value))
                        {
                            if (ServerDuration.HasValue)
                            {
                                ServerDuration += value;
                            }
                            else
                            {
                                ServerDuration = value;
                            }
                        }
                    }
                    break;

                case CouchbaseOperationNames.ResponseDecoding:
                    DecodingDuration += span.Duration;
                    break;
                }

                PopulateSummary(span.Spans);
            }
        }
コード例 #16
0
    public void TestJiraTimeRangeToTimeSpan_RealWeek_FromWorkingTime()
    {
        var testTimeSpan = TimeSpanExtensions.FromWorkingTime("4w 1d 1h 10m");
        var testResult   = TimeSpan.FromDays(7);

        testResult = testResult.Add(TimeSpan.FromHours(1));
        testResult = testResult.Add(TimeSpan.FromMinutes(10));
        Assert.Equal(testResult, testTimeSpan);
    }
コード例 #17
0
        public void nullable_double_to_time_span()
        {
            var    expected   = TimeSpan.FromSeconds(3.5);
            double?inputFloat = 3.5;

            var actual = TimeSpanExtensions.FromSeconds(inputFloat);

            Assert.AreEqual(expected, actual);
        }
コード例 #18
0
        public static void Division(TimeSpan timeSpan, double factor, TimeSpan expected)
        {
            // This code is borrowed from the official .NET implementation:
            //   https://git.io/JYvjY#L1152-L1158
            // We can remove these copy-and-pasted lines in the future when Libplanet drops
            // .NET Standard 2.0 support and becomes to support .NET Standard 2.1 or higher.
            double divisor = 1.0 / factor;

            Assert.Equal(expected, TimeSpanExtensions.Divide(timeSpan, divisor));
        }
コード例 #19
0
        public void Initialize(IServiceRegistry services, string url, long startPosition, long length)
        {
            if (isInitialized)
            {
                return;
            }

            try
            {
                inputFile = new Java.IO.File(url);
                if (!inputFile.CanRead())
                {
                    throw new Exception(string.Format("Unable to read: {0} ", inputFile.AbsolutePath));
                }

                inputFileDescriptor = new Java.IO.FileInputStream(inputFile);

                // ===================================================================================================
                // Initialize the audio media extractor
                mediaExtractor = new MediaExtractor();
                mediaExtractor.SetDataSource(inputFileDescriptor.FD, startPosition, length);

                var videoTrackIndex = FindTrack(mediaExtractor, MediaType.Video);
                var audioTrackIndex = FindTrack(mediaExtractor, MediaType.Audio);
                HasAudioTrack = audioTrackIndex >= 0;

                mediaTrackIndex = MediaType == MediaType.Audio ? audioTrackIndex : videoTrackIndex;
                if (mediaTrackIndex < 0)
                {
                    throw new Exception(string.Format($"No {MediaType} track found in: {inputFile.AbsolutePath}"));
                }

                mediaExtractor.SelectTrack(mediaTrackIndex);

                var trackFormat = mediaExtractor.GetTrackFormat(mediaTrackIndex);
                MediaDuration = TimeSpanExtensions.FromMicroSeconds(trackFormat.GetLong(MediaFormat.KeyDuration));

                ExtractMediaMetadata(trackFormat);

                // Create a MediaCodec mediadecoder, and configure it with the MediaFormat from the mediaExtractor
                // It's very important to use the format from the mediaExtractor because it contains a copy of the CSD-0/CSD-1 codec-specific data chunks.
                var mime = trackFormat.GetString(MediaFormat.KeyMime);
                MediaDecoder = MediaCodec.CreateDecoderByType(mime);
                MediaDecoder.Configure(trackFormat, decoderOutputSurface, null, 0);

                isInitialized = true;

                StartWorker();
            }
            catch (Exception e)
            {
                Release();
                throw e;
            }
        }
コード例 #20
0
        public void When_Days_GreaterThan24_Ttl_Is_Postive()
        {
            var twentyFourDays = new TimeSpan(24, 0, 0, 0);
            var twentyFiveDays = new TimeSpan(25, 0, 0, 0);

            var result1 = TimeSpanExtensions.ToTtl((uint)twentyFourDays.TotalMilliseconds);
            var result2 = TimeSpanExtensions.ToTtl((uint)twentyFiveDays.TotalMilliseconds);

            Assert.Positive(result1);
            Assert.Positive(result2);
        }
コード例 #21
0
        public TimeSpan GetTimeout(Request request, IRequestTimeBudget budget, int currentReplicaIndex, int totalReplicas)
        {
            if (currentReplicaIndex >= providers.Length)
            {
                return(tailBehaviour == TailTimeoutBehaviour.UseRemainingBudget
                    ? budget.Remaining
                    : TimeSpanExtensions.Min(providers.Last()(), budget.Remaining));
            }

            return(TimeSpanExtensions.Min(providers[currentReplicaIndex](), budget.Remaining));
        }
コード例 #22
0
        public TimeSpan GetTimeout(Request request, IRequestTimeBudget budget, int currentReplicaIndex, int totalReplicas)
        {
            if (currentReplicaIndex >= divisionFactor)
            {
                return(budget.Remaining);
            }

            var effectiveDivisionFactor = Math.Min(divisionFactor, totalReplicas) - currentReplicaIndex;

            return(TimeSpanExtensions.Max(TimeSpan.Zero, budget.Remaining.Divide(effectiveDivisionFactor)));
        }
コード例 #23
0
 public void ParseTimeSpan()
 {
     Assert.AreEqual(TimeSpanExtensions.ParseTimeSpan("01.211"), new TimeSpan(0, 0, 0, 1, 211));
     Assert.AreEqual(TimeSpanExtensions.ParseTimeSpan("01.11"), new TimeSpan(0, 0, 0, 1, 110));
     Assert.AreEqual(TimeSpanExtensions.ParseTimeSpan("01.1"), new TimeSpan(0, 0, 0, 1, 100));
     Assert.AreEqual(TimeSpanExtensions.ParseTimeSpan("02,21"), new TimeSpan(0, 0, 0, 2, 210));
     Assert.AreEqual(TimeSpanExtensions.ParseTimeSpan("02,3"), new TimeSpan(0, 0, 0, 2, 300));
     Assert.AreEqual(TimeSpanExtensions.ParseTimeSpan("1:01,111"), new TimeSpan(0, 0, 1, 1, 111));
     Assert.AreEqual(TimeSpanExtensions.ParseTimeSpan("61.111"), new TimeSpan(0, 0, 1, 1, 111));
     Assert.AreEqual(TimeSpanExtensions.ParseTimeSpan("121,11"), new TimeSpan(0, 0, 2, 1, 110));
 }
コード例 #24
0
        public static void NaNDivision()
        {
            // This code is borrowed from the official .NET implementation:
            //   https://git.io/JYvhp#L1171-L1175
            // We can remove these copy-and-pasted lines in the future when Libplanet drops
            // .NET Standard 2.0 support and becomes to support .NET Standard 2.1 or higher.
            ArgumentException e = Assert.Throws <ArgumentException>(
                () => TimeSpanExtensions.Divide(TimeSpan.FromDays(1), double.NaN)
                );

            Assert.Equal("divisor", e.ParamName);
        }
コード例 #25
0
ファイル: StringTest.cs プロジェクト: fengrui358/NetLibCore
        public void TimeSpanFormatTest()
        {
            var seconds = 14;

            Assert.Equal("00:14", TimeSpanExtensions.TimeSpanFormat(seconds));

            seconds = 76;
            Assert.Equal("01:16", TimeSpanExtensions.TimeSpanFormat(seconds));

            seconds = 5698;
            Assert.Equal("01:34:58", TimeSpanExtensions.TimeSpanFormat(seconds));
        }
コード例 #26
0
        public TimeSpan GetRetryDelay(int attemptsUsed)
        {
            var delay = InitialRetryDelay.Multiply(Math.Pow(RetryDelayMultiplier, Math.Max(0, attemptsUsed - 1)));

            var jitterAmount = delay.Multiply(ThreadSafeRandom.NextDouble() * Jitter);

            if (ThreadSafeRandom.NextDouble() <= 0.5)
            {
                jitterAmount = jitterAmount.Negate();
            }

            return(TimeSpanExtensions.Min(MaximumRetryDelay, delay + jitterAmount));
        }
コード例 #27
0
        public void Test_TryConverToMicros(string duration, long?expected)
        {
            var result = TimeSpanExtensions.TryConvertToMicros(duration, out var value);

            if (expected.HasValue)
            {
                Assert.IsTrue(result);
                Assert.AreEqual(expected, value);
            }
            else
            {
                Assert.IsFalse(result);
            }
        }
コード例 #28
0
        private void OnTextTimeInput_TextChanged(object sender, EventArgs e)
        {
            TextBox  control = sender as TextBox;
            TimeSpan time;

            if (TimeSpanExtensions.TryParseTimeOfDay(control.Text, out time) == false)
            {
                control.ForeColor = Color.Red;
            }
            else
            {
                control.ForeColor = Color.Black;
            }
        }
コード例 #29
0
        /// <summary>
        /// Resets the device, updates PROM data and clears current measurements
        /// </summary>
        public virtual void Reset()
        {
            // Send reset command
            Hardware.WriteJoinByte((byte)Ms5611Command.Reset, 0);

            // Wait for completion
            Task.Delay(TimeSpanExtensions.FromMicroseconds(ResetTime)).Wait();

            // Update PROM values
            ReadProm();

            // Clear measurement
            Measurement = Ms5611Measurement.Zero;
        }
コード例 #30
0
    public void TestJiraTimeRangeToTimeSpan_RealWeek_7HalfHours_FromWorkingTime()
    {
        var timeTrackingConfiguration = new TimeTrackingConfiguration
        {
            WorkingHoursPerDay = 7.5f
        };
        var testTimeSpan = TimeSpanExtensions.FromWorkingTime("1w 1d 1h 10m", timeTrackingConfiguration);
        // in hours => (5 (Working days per week) + 1 )* 7,5 (working hours per day)
        var testResult = TimeSpan.FromHours(6 * timeTrackingConfiguration.WorkingHoursPerDay);

        testResult = testResult.Add(TimeSpan.FromHours(1));
        testResult = testResult.Add(TimeSpan.FromMinutes(10));
        Assert.Equal(testResult, testTimeSpan);
    }