Esempio n. 1
0
 public static string GetMemoryAndCPUInfo()
 {
     return
         (((int)(memoryQueue.Average() / (1024 * 1024))).ToString().PadLeft(4) + " MB" +
          "".PadLeft(20) +
          "CPU:" + ((int)cpuCounter.NextValue()).ToString().PadLeft(3) + "%");
 }
Esempio n. 2
0
        private void OnApplicationOnIdle(object sender, EventArgs e)
        {
            int    numOfElem = eyeRatios.GetLength();
            double avrg      = 0;

            if (numOfElem >= 2)
            {
                avrg        = cExtMethods.CalcEarStatistics(eyeRatios);
                label3.Text = avrg.ToString("F2");
            }

            else if (numOfElem == 0)
            {
                label3.Text = "N/A";
            }

            if (FPSque.Count >= 2)
            {
                while (FPSque.Count > 20)
                {
                    FPSque.TryDequeue(out _);
                }

                label1.Text = FPSque.Average().ToString("F2");
            }

            label5.Text = MethodNames[iFilterMethod];
        }
Esempio n. 3
0
 private float getAverageLatency(ConcurrentQueue <float> queue)
 {
     if (queue.Count < 1) //InvalidOperationException
     {
         return(0);
     }
     else
     {
         return(queue.Average());
     }
 }
Esempio n. 4
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            Stopwatch timer = Stopwatch.StartNew();

            await next();

            timer.Stop();
            actionTimes.Enqueue(timer.Elapsed.TotalMilliseconds);
            diagnostics.AddMessage($@"Action time: 
                {timer.Elapsed.TotalMilliseconds} 
                Average: {actionTimes.Average():F2}");
        }
        public async Task OnResultExecutionAsync(
            ResultExecutingContext context, ResultExecutionDelegate next)
        {
            var timer = Stopwatch.StartNew();

            await next();

            timer.Stop();
            _resultTimes.Enqueue(timer.Elapsed.TotalMilliseconds);
            _diagnostics.AddMessage($@"Result time:{timer.Elapsed.TotalMilliseconds}" +
                                    $"\nAverage: {_resultTimes.Average():F2}");
        }
Esempio n. 6
0
 public void ServerProcessingTimeCalculator(float requestLatency)
 {
     if (ServerProcessingTimeRollingAvgQueue.Count < 10)
     {
         ServerProcessingTimeRollingAvgQueue.Enqueue(requestLatency);
     }
     else
     {
         float t;
         ServerProcessingTimeRollingAvgQueue.TryDequeue(out t);
         ServerProcessingTimeRollingAvgQueue.Enqueue(requestLatency);
     }
     avgServerProcessingTime = ServerProcessingTimeRollingAvgQueue.Average();
 }
Esempio n. 7
0
 void LatencyCalculator(float requestLatency)
 {
     if (LatencyRollingAvgQueue.Count < 10)
     {
         LatencyRollingAvgQueue.Enqueue(requestLatency);
     }
     else
     {
         float t;
         LatencyRollingAvgQueue.TryDequeue(out t);
         LatencyRollingAvgQueue.Enqueue(requestLatency);
     }
     avgLatency = LatencyRollingAvgQueue.Average();
 }
Esempio n. 8
0
    void SignalManager_TransformableUpdated(string fullName, System.Numerics.Vector3 localPositionIn, System.Numerics.Vector3 localRotationIn, System.Numerics.Vector3 localScaleIn, long remoteTime)
    {
        if (fullName != signalObjectFullName)
        {
            return;
        }

        Vector3    localPosition = new Vector3(localPositionIn.X, localPositionIn.Y, localPositionIn.Z);
        Quaternion localRotation = Quaternion.Euler(localRotationIn.X, localRotationIn.Y, localRotationIn.Z);
        Vector3    localScale    = new Vector3(localScaleIn.X, localScaleIn.Y, localScaleIn.Z);

        lastReceivedTime = DateTime.UtcNow;
        var newRemoteTime = DateTime.FromFileTime(remoteTime);

        lastRemoteTimeDelta = newRemoteTime - lastRemoteTime;

        remoteTimeDeltas.Enqueue(lastRemoteTimeDelta);
        while (remoteTimeDeltas.Count > remoteTimeDeltaQueueSampleLimit)
        {
            TimeSpan dummy = TimeSpan.Zero;
            remoteTimeDeltas.TryDequeue(out dummy);
        }

        averageRemoteTimeDelta = TimeSpan.FromTicks((long)remoteTimeDeltas.Average(ts => ts.Ticks));

        lastRemoteTime = newRemoteTime;

        float delta = (float)lastRemoteTimeDelta.TotalMilliseconds;

        var posDelta = localPosition - position;

        velocityPosition = new Vector3(posDelta.x / delta, posDelta.y / delta, posDelta.z / delta);

        var scDelta = localScale - scale;

        velocityScale = new Vector3(scDelta.x / delta, scDelta.y / delta, scDelta.z / delta);

        var rotDelta = localRotation.eulerAngles - rotation.eulerAngles;

        velocityRotation = new Vector3(rotDelta.x / delta, rotDelta.y / delta, rotDelta.z / delta);

        UpdateTransform(localPosition, localRotation, localScale);
    }
        protected override Task <IObservable <SpeedData> > InitializeCore()
        {
            if (this.DistanceDataSource == null)
            {
                this.DistanceDataSource            = new SubjectSlim <DistanceData>();
                this.IsDistanceOperationalCallback = () => false;
            }
            else
            {
                // we must be able to keep sending data even if distanceDataSource completes
                // so we merge it with a subject that never completes
                this.DistanceDataSource = this.DistanceDataSource.Merge(new SubjectSlim <DistanceData>());
            }

            if (this.LocalisationDataSource == null)
            {
                this.LocalisationDataSource            = new SubjectSlim <LocalisationData>();
                this.IsLocalisationOperationalCallback = () => false;
            }

            return(Task.Run(
                       () =>
            {
                var speedBuffer = new ConcurrentQueue <double>();

                DistanceData lastDistance = null;
                SpeedData lastSpeed = null;
                double?lastDistanceSpeed = null;
                double?lastGpsSpeed = null;

                var distanceDataSource = this.DistanceDataSource
                                         // filter invalid data
                                         .Where(
                    data =>
                {
                    if (lastDistance == null)
                    {
                        // no previous data
                        // so save first data point
                        // but speed cannot be calculated yet

                        lastDistance = data;
                        return false;
                    }

                    var deltaDistance = data.AbsoluteDistance - lastDistance.AbsoluteDistance;
                    var deltaTime = data.Timestamp - lastDistance.Timestamp;

                    // case when distance was reset on acquisition start
                    if (deltaDistance < 0)
                    {
                        lastDistance = data;
                    }

                    return deltaTime.TotalMilliseconds > 0 && deltaDistance >= 0;
                })
                                         // odometric speed calculation
                                         .Select(
                    data =>
                {
                    Debug.Assert(lastDistance != null);

                    var deltaDistance = data.AbsoluteDistance - lastDistance.AbsoluteDistance;
                    var deltaTime = data.Timestamp - lastDistance.Timestamp;

                    speedBuffer.Enqueue(deltaDistance * (3600 / deltaTime.TotalMilliseconds));

                    double tmpSpeed;
                    if (speedBuffer.Count > this.DistanceSpeedCountForAverage)
                    {
                        speedBuffer.TryDequeue(out tmpSpeed);
                    }

                    lastDistance = data;
                    return new SpeedData {
                        CurrentSpeed = speedBuffer.Average(), CurrentDistance = lastDistance.AbsoluteDistance, SpeedSource = SpeedActiveMode.Distance
                    };
                })
                                         // return odometric speed immediately or wait until timeout is reached
                                         .Buffer(this.DistanceDataTimeout, 1)
                                         // if timeout has been reached and odometer is operational, assume that speed is equal to 0
                                         .Select(
                    buffer =>
                {
                    if (buffer.Count > 0)
                    {
                        return buffer[0];
                    }
                    else if (this.IsDistanceOperationalCallback())
                    {
                        speedBuffer.Enqueue(0);

                        double tmpSpeed;
                        if (speedBuffer.Count > this.DistanceSpeedCountForAverage)
                        {
                            speedBuffer.TryDequeue(out tmpSpeed);
                        }

                        return new SpeedData {
                            CurrentSpeed = speedBuffer.Average(), SpeedSource = SpeedActiveMode.Distance
                        };
                    }
                    else
                    {
                        return null;
                    }
                })
                                         // filter null values in case odometer is not operational
                                         .Where(data => data != null)
                                         // save last odometric speed
                                         .Select(
                    data =>
                {
                    lastDistanceSpeed = data.CurrentSpeed;
                    return data;
                })
                                         .Publish().RefCount();

                var gpsDataSource = this.LocalisationDataSource
                                    // filter invalid GPS data and data received while GPS is not operational
                                    .Where(data => data.GpsStatus != GpsStatus.SignalLost && data.CorrectedData.VelocityData.SpeedKmh >= 0 && this.IsLocalisationOperationalCallback())
                                    // save last GPS speed
                                    .Select(
                    data =>
                {
                    var gpsSpeed = new SpeedData {
                        CurrentSpeed = data.CorrectedData.VelocityData.SpeedKmh, SpeedSource = SpeedActiveMode.Gps
                    };
                    lastGpsSpeed = gpsSpeed.CurrentSpeed;
                    return gpsSpeed;
                })
                                    .Publish().RefCount();

                return distanceDataSource.Merge(gpsDataSource)
                // return current speed based on data sources state and hysteresis
                .Select(
                    data =>
                {
                    SpeedActiveMode source;
                    if (data.CurrentSpeed < 0)
                    {
                        source = SpeedActiveMode.None;
                    }
                    else if (data.CurrentSpeed < (this.Threshold - this.Hysteresis))
                    {
                        source = SpeedActiveMode.Distance;
                    }
                    else if (data.CurrentSpeed > (this.Threshold + this.Hysteresis))
                    {
                        source = SpeedActiveMode.Gps;
                    }
                    else
                    {
                        source = lastSpeed == null ? SpeedActiveMode.Gps : lastSpeed.SpeedSource;
                    }

                    data.DistanceSpeed = data.SpeedSource == SpeedActiveMode.Distance ? data.CurrentSpeed : this.IsDistanceOperationalCallback() ? lastDistanceSpeed : null;
                    data.GpsSpeed = data.SpeedSource == SpeedActiveMode.Gps ? data.CurrentSpeed : this.IsLocalisationOperationalCallback() ? lastGpsSpeed : null;
                    Debug.Assert(data.DistanceSpeed != null || data.GpsSpeed != null);

                    if (source == SpeedActiveMode.None)
                    {
                        data.CurrentSpeed = -1;
                        data.SpeedSource = SpeedActiveMode.None;
                    }
                    else if (source == SpeedActiveMode.Distance && data.DistanceSpeed != null)
                    {
                        data.CurrentSpeed = data.DistanceSpeed.Value;
                        data.SpeedSource = SpeedActiveMode.Distance;
                    }
                    else if (source == SpeedActiveMode.Gps && data.GpsSpeed != null)
                    {
                        data.CurrentSpeed = data.GpsSpeed.Value;
                        data.SpeedSource = SpeedActiveMode.Gps;
                    }

                    data.IsInRange = this.SpeedRanges.Any(ranges => Math.Floor(data.CurrentSpeed).Between(ranges.MinSpeed, ranges.MaxSpeed, inclusive: true));

                    lastSpeed = data;

                    return data;
                })
                .Publish().RefCount();
            }));
        }
Esempio n. 10
0
        /// <summary>
        /// Keep track of processor steps efficiency for benchmarking purposes
        /// </summary>
        void LogProcessorStats(TimeSpan elapsed)
        {
            if (ProcessingTimesQueue.Count > 0)
            {
                IBFSample first;
                lock (UnfilteredData)
                {
                    first = UnfilteredData.First();
                }

                var processor = "Not processing !";
                if (ProcessingTimesQueue.Count > 0)
                {
                    processor = $"Queue {(ProcessingTimesQueue.Count / elapsed.TotalSeconds).ToString("F0")} times per second: Av {ProcessingTimesQueue.Average().ToString("F4")} s | Max {ProcessingTimesQueue.Max().ToString("F4")} s.";
                }


                Log?.Invoke(this, new LogEventArgs(Name, this, "LogProcessorStats", $"{Name} processing: Age {(DateTimeOffset.UtcNow.ToUnixTimeInDoubleSeconds() - first.TimeStamp).ToString("F6")}.  {processor}", LogLevel.TRACE));

                if (CountMissingIndex > 0)
                {
                    Log?.Invoke(this, new LogEventArgs(Name, this, "LogProcessorStats", $"Missed {CountMissingIndex} samples in the past {(int)(PeriodMsUpdateProcessorStats / 1000)} seconds.", LogLevel.WARN));
                    CountMissingIndex = 0;
                }
                ProcessingTimesQueue.RemoveAll();
            }
        }
Esempio n. 11
0
        private double TempWithOffset()
        {
            double temp = RtdTempFahrenheitFromResistance(_probeResistances.Average());

            return(Math.Round(temp + _offset));
        }
Esempio n. 12
0
 public decimal Calculate()
 {
     return(Count == 0 ? 0 : _queue.Average());
 }
        public double CalculateScore(IMLMethod network)
        {
            if (IsStopped)
            {
                return(0);
            }

            SessionNumber++;

            DateTime startSession = DateTime.Now;

            PlanogramSimulation pilot = new PlanogramSimulation((BasicNetwork)network, Items, SimSettings);
            var result = LastResult = pilot.ScorePilot();

            result.CurrentSession = SessionNumber;
            metricScoreHistory.Add(result.Score);
            metricAvgLastTen.Enqueue(result.Score);
            if (metricAvgLastTen.Count > 10)
            {
                double outVal = 0;
                metricAvgLastTen.TryDequeue(out outVal);
            }
            result.MaxScore   = metricScoreHistory.Max();
            result.MinScore   = metricScoreHistory.Min();
            result.AvgScore   = metricScoreHistory.Average();
            result.AvgLastTen = metricAvgLastTen.Average();

            if (SimSettings.Score.HasValue)
            {
                if (result.Score >= SimSettings.Score.Value)
                {
                    NumScoreHits++;
                }
                else
                {
                    NumScoreHits = 0;
                }
            }

            if (NumScoreHits >= RPOCSimulationSettings.NUM_SCORE_HITS)
            {
                StopEncogTraningEvent?.Invoke();
                IsStopped = true;
            }

            result.NumScoreHits = NumScoreHits;

            if (Logger != null)
            {
                SimulationData logdata = new SimulationData();

                logdata.Session = result.CurrentSession;
                logdata.Score   = result.Score;
                logdata.Elapse  = DateTime.Now - startSession;

                Logger.Add(logdata, false);
            }

            UpdateUI?.Invoke(result, SimSettings.EnableSimDisplay);

            return(result.Score);
        }
Esempio n. 14
0
        public void SetSession(AudioSessionControl2 session)
        {
            this.session = session;

            Process p = Process.GetProcessById((int)session.GetProcessID);

            LabelName.Text = session.IsSystemSoundsSession ? "System Sounds" : session.DisplayName;
            if (LabelName.Text == "")
            {
                LabelName.Text = p.ProcessName;
            }

            Bitmap bmp  = null;
            Icon   icon = NativeMethods.GetIconFromFile(session.IconPath);

            if (icon == null)
            {
                string tmpFileName = "";
                try {
                    tmpFileName = Path.Combine((new FileInfo(p.MainModule.FileName)).DirectoryName, @"Assets\AppList.scale-200.png");
                    if (File.Exists(tmpFileName))
                    {
                        bmp = (Bitmap)Image.FromFile(tmpFileName);
                    }
                    else
                    {
                        bmp = NativeMethods.GetIconFromFile(p.MainModule.FileName).ToBitmap();
                    }
                } catch { }
            }
            else
            {
                bmp = icon.ToBitmap();
            }
            if (bmp != null)
            {
                PictureBoxIcon.Image = bmp;
            }

            session.OnSimpleVolumeChanged += new SimpleVolumeChangedDelegate(UpdateUI);
            TrackBarVol.Scroll            += (_, __) => UpdateVolume();
            HandleCreated += (_, __) => {
                int newValue  = 0;
                int lastValue = -1;

                Task.Run(() => {
                    while (!this.IsDisposed)
                    {
                        Thread.Sleep(5);

                        volPeakHistory.Enqueue(session.AudioMeterInformation.MasterPeakValue);
                        if (volPeakHistory.Count > historySize)
                        {
                            volPeakHistory.TryDequeue(out float _);
                        }
                    }
                });

                Task.Run(() => {
                    try {
                        while (!this.IsDisposed)
                        {
                            Thread.Sleep(30);

                            newValue = (int)(volPeakHistory.Average() * 100);

                            if (newValue != lastValue)
                            {
                                this.Invoke((MethodInvoker) delegate {
                                    ProgressBarVU.Value = newValue;
                                    lastValue           = newValue;
                                });
                            }
                        }
                        ;
                    } catch { }
                });
            };

            UpdateUI(null, session.SimpleAudioVolume.MasterVolume, session.SimpleAudioVolume.Mute);
        }
Esempio n. 15
0
        public void SetSession(AudioSessionControl2 session)
        {
            this.session            = session;
            session.OnStateChanged += SessionStateChanged;
            Process p = Process.GetProcessById((int)session.GetProcessID);

            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(() => {
                    sessionLabel.Content = session.IsSystemSoundsSession ? "System sounds" : session.DisplayName;
                    if (sessionLabel.Content.ToString() == "")
                    {
                        sessionLabel.Content = p.ProcessName;
                    }
                });
            }
            else
            {
                sessionLabel.Content = session.IsSystemSoundsSession ? "System sounds" : session.DisplayName;
                if (sessionLabel.Content.ToString() == "")
                {
                    sessionLabel.Content = p.ProcessName;
                }
            }

            sessionLabel.Content = ParseLabel(sessionLabel.Content.ToString());

            session.OnSimpleVolumeChanged += new SimpleVolumeChangedDelegate(UpdateUI);
            sessionSlider.ValueChanged    += (_, __) => UpdateVolume();
            sessionCheckBox.Checked       += (_, __) => UpdateMuted();
            sessionCheckBox.Unchecked     += (_, __) => UpdateMuted();

            Loaded += (_, __) => {
                float newValue  = 0;
                float lastValue = -1;

                getPeaksTask = Task.Run(() => {
                    while (!isClosing)
                    {
                        volPeakHistory.Enqueue(session.AudioMeterInformation.MasterPeakValue);
                        if (volPeakHistory.Count > historySize)
                        {
                            volPeakHistory.TryDequeue(out float _);
                        }

                        Thread.Sleep(5);
                    }
                });

                setMeterTask = Task.Run(() => {
                    while (!isClosing)
                    {
                        newValue = volPeakHistory.Average();

                        if (newValue != lastValue)
                        {
                            Dispatcher.Invoke(() => {
                                sessionProgressBar.Value = newValue;
                                lastValue = newValue;
                            });
                        }
                        Thread.Sleep(16);
                    }
                });
            };

            UpdateUI(null, session.SimpleAudioVolume.MasterVolume, session.SimpleAudioVolume.Mute);
        }
Esempio n. 16
0
        public void SetSession(AudioSessionControl2 session)
        {
            this.session            = session;
            session.OnStateChanged += SessionStateChanged;
            Process p = Process.GetProcessById((int)session.GetProcessID);

            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(() => {
                    sessionLabel.Content = session.IsSystemSoundsSession ? "System sounds" : session.DisplayName;
                    if (sessionLabel.Content.ToString() == "")
                    {
                        sessionLabel.Content = p.ProcessName;
                    }
                });
            }
            else
            {
                sessionLabel.Content = session.IsSystemSoundsSession ? "System sounds" : session.DisplayName;
                if (sessionLabel.Content.ToString() == "")
                {
                    sessionLabel.Content = p.ProcessName;
                }
            }

            sessionLabel.Content = ParseLabel(sessionLabel.Content.ToString());

            session.OnSimpleVolumeChanged += SessionVolumeChanged;
            sessionSlider.ValueChanged    += SessionSlider_ValueChanged;
            sessionCheckBox.Checked       += (_, __) => {
                session.SimpleAudioVolume.Mute = true;
                UpdateMuted();
            };
            sessionCheckBox.Unchecked += (_, __) => {
                session.SimpleAudioVolume.Mute = false;
                UpdateMuted();
            };

            Loaded += (_, __) => {
                float newValue  = 0;
                float lastValue = -1;

                getPeaksTask = Task.Run(() => {
                    while (!isClosing)
                    {
                        volPeakHistory.Enqueue(session.AudioMeterInformation.MasterPeakValue);
                        if (volPeakHistory.Count > historySize)
                        {
                            volPeakHistory.TryDequeue(out float _);
                        }

                        Thread.Sleep(5);
                    }
                });

                setMeterTask = Task.Run(() => {
                    while (!isClosing)
                    {
                        newValue = volPeakHistory.Average();

                        if (newValue != lastValue)
                        {
                            try {
                                Dispatcher.Invoke(() => {
                                    sessionProgressBar.Value     = newValue;
                                    sessionProgressBarGrey.Value = newValue;
                                    lastValue = newValue;
                                });
                            } catch (TaskCanceledException) {
                                // Eh, who cares?
                            }
                        }
                        Thread.Sleep(16);
                    }
                });
            };

            UpdateUI(session, session.SimpleAudioVolume.MasterVolume, session.SimpleAudioVolume.Mute);
            Dispatcher.Invoke(() => {
                var margin   = sessionProgressBar.Margin;
                margin.Right = (1 - session.SimpleAudioVolume.MasterVolume) * sessionProgressBar.ActualWidth;
                Console.WriteLine($"Master volume: {session.SimpleAudioVolume.MasterVolume}, margin (right): {margin.Right}");
                sessionProgressBar.Margin = margin;
            });
        }
Esempio n. 17
0
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            var stopwatch = Stopwatch.StartNew();

            await next();

            stopwatch.Stop();
            resultTimes.Enqueue(stopwatch.Elapsed.TotalMilliseconds);
            _filterDiagnostics.AddMessage($"Result Time: {stopwatch.Elapsed.TotalMilliseconds} Average: {resultTimes.Average():F2}");
        }