public async Task<IssuesCollectionStatistics> Calculate(IList<JiraIssue> issues) { if(issues == null || issues.Any() == false) return null; return await Task.Factory.StartNew(() => { return new IssuesCollectionStatistics { IssuesCount = issues.Count(), ResolvedIssuesCount = issues.Where(i => i.Resolved.HasValue).Count(), UnresolvedIssuesCount = issues.Where(i => i.Resolved.HasValue == false).Count(), AverageResolutionTimeHours = issues .Where(i => i.Resolved.HasValue) .Select(i => (i.Resolved.Value - i.Created).TotalHours).Average(), MaxResolutionTimeHours = issues .Where(i => i.Resolved.HasValue) .Select(i => (i.Resolved.Value - i.Created).TotalHours).Max(), TotalStorypoints = issues.Sum(i => i.StoryPoints), AverageStorypointsPerTask = issues.Average(i => i.StoryPoints), AverageSubtasksCount = issues.Average(i => i.Subtasks), EpicsInvolved = issues.Select(i => i.EpicLink).Distinct().Count(), DistinctReporters = issues.Select(i => i.Reporter).Distinct().Count() }; }); }
public RiskProfile Calculate(Bet bet, IList<Bet> settledBets) { if (settledBets.Count == 0) { return Constants.SAFE_PROFILE; } var avergaStake = settledBets.Average(bets => bets.Stake); if (bet.Stake > (avergaStake * Constants.EXCEPTIONALLY_RISKY_STAKE_FACTOR)) { return new RiskProfile { Risk = Risk.HighlyRisky, Reason = "Stake is exceptionally large based on betting history." }; } if (bet.Stake > (avergaStake * Constants.UNUSUAL_STAKE_FACTOR)) { return new RiskProfile { Risk = Risk.Unusual, Reason = "Stake is unusually large based on betting history." }; } return Constants.SAFE_PROFILE; }
static void DisplayStats(IList<Response> responses) { if (!responses.Any()) { return; } var average = responses.Average(x => (x.EndUtc - x.StartUtc).TotalMilliseconds); ClearLine(); Console.WriteLine("Average time: {0} ms", Convert.ToInt32(average)); var min = responses.Min(x => x.StartUtc); var max = responses.Max(x => x.EndUtc); var count = responses.Count; var timespan = Convert.ToInt32((max - min).TotalMilliseconds); timespan = timespan == 0 ? 0 : timespan / 1000; var rps = timespan == 0 ? 0 : count / timespan; ClearLine(); Console.WriteLine("Performance: {0} rps ({1} reqs in {2})", Convert.ToInt32(rps), responses.Count, timespan); ClearLine(); Console.WriteLine("Threads: {0}", responses.Select(x => x.TaskId).Distinct().Count()); ClearLine(); Console.WriteLine("Errors: {0}", responses.Count(x => !x.Success)); }
public AggregationOperationResult Do(IList<UniversalValue> input) { if (input == null) throw new ArgumentNullException("input"); AggregationOperationResult result = new AggregationOperationResult(); result.Add("avg", input.Average()); return result; }
public RatingResult Compute(IList<RestaurantReview> reviews) { var result = new RatingResult(); result.Rating = (int)reviews.Average(r => r.Rating); return result; }
public AggregationOperationResult Do(IList<double> input) { if (input == null) throw new ArgumentNullException("input"); if (!input.Any()) throw new InvalidOperationException("No elements to aggregate"); return new AggregationOperationResult(AggregationType.Avg,input.Average()); }
private static AggregatedWeatherResponse CalculateAverages(IList<WeatherServiceResponse> weatherServiceResponses) { AggregatedWeatherResponse aggregatedResponse = null; if (weatherServiceResponses.Count > 0) { aggregatedResponse = new AggregatedWeatherResponse { AverageTemperatureCelsius = Math.Round(weatherServiceResponses.Average(a => a.TemperatureCelsius), 1), AverageTemperatureFahrenheit = Math.Round(weatherServiceResponses.Average(a => a.TemperatureFahrenheit), 1), AverageWindSpeedKph = Math.Round(weatherServiceResponses.Average(a => a.WindSpeedKph), 1), AverageWindSpeedMph = Math.Round(weatherServiceResponses.Average(a => a.WindSpeedMph), 1) }; } return aggregatedResponse; }
public static ArrayVector GetAverage(IList<ArrayVector> vectors) { if (vectors == null) throw new ArgumentNullException("vectors"); if (vectors.Count == 0) throw new ArgumentException("The source must not be empty.", "vectors"); return Enumerable.Range(0, vectors[0].Dimension) .Select(i => vectors.Average(v => v.Value[i])) .ToArray(); }
private static void FindSumAndAverage(IList<int> numbers) { long numbersSum = 0; double numbersAverage = 0; numbersSum = numbers.Sum(); numbersAverage = numbers.Average(); Console.WriteLine("The sum of your sequence is: {0} and the avgerage is: {1}.", numbersSum, numbersAverage); }
public double Calculate(IList<Coder> participants) { var n = participants.Count; var ratAvg = participants.Average(x => x.R); var sqrRatStdev = participants.Sum(x => Math.Pow(x.R - ratAvg, 2)) / (n - 1); var sqrVolAvg = participants.Sum(x => x.V * x.V) / n; return Math.Sqrt(sqrVolAvg + sqrRatStdev); }
public static Movement Analyze(IList<Movement> movements) { Movement movement; if (movements.Any(x => x > Movement.Higher)) movement = Movement.Highest; else if (movements.Any(x => x > Movement.High)) movement = Movement.High; else if (movements.Any(x => x > Movement.Med)) movement = Movement.Med; else if (movements.Average(x => (double)x) > (double)Movement.Lowest) movement = Movement.Low; else movement = Movement.Lowest; return movement; }
public RelatorioJogosDisponiveisModel(IList<Jogo> jogosDisponiveis) { this.Jogos = new List<JogoDisponivelModel>(); if(jogosDisponiveis != null && jogosDisponiveis.Count > 0) { foreach (Jogo jogo in jogosDisponiveis) { var jogoModel = new JogoDisponivelModel(jogo); this.Jogos.Add(jogoModel); } this.QuantidadeTotalDeJogos = jogosDisponiveis.Count; this.ValorMedio = jogosDisponiveis.Average(j => j.Preco); decimal maiorPreco = jogosDisponiveis.Max(j => j.Preco); decimal menorPreco = jogosDisponiveis.Min(j => j.Preco); this.JogoMaisCaro = this.Jogos.First(j => j.Preco == maiorPreco); this.JogoMaisBarato = this.Jogos.First(j => j.Preco == menorPreco); } }
public static StatSummary CalculateSummaries(IList<decimal> vals) { var res = new StatSummary(); res.Count = vals.Count; res.Average = vals.Average(); var sorted = new List<decimal>(vals); sorted.Sort(); res.Median = CalculateQuantile(sorted, 0.5M); res.LowerQuartile = CalculateQuantile(sorted, 0.25M); res.UpperQuartile = CalculateQuantile(sorted, 0.75M); res.Min = sorted.First(); res.Max = sorted.Last(); res.Percentile2 = CalculateQuantile(sorted, 0.02M); res.Percentile98 = CalculateQuantile(sorted, 0.98M); Validate(sorted, res); return res; }
public static double AverageIList(IList<double> numbers) { return numbers.Average(); }
public static double StandardDeviation(IList<double> doubleList, out double average, out double max, out double min) { average = doubleList.Average(); double sumOfDerivation = 0; max = -1e9; min = 1e9; foreach (double value in doubleList) { max = Math.Max(max, value); min = Math.Min(min, value); sumOfDerivation += (value) * (value); } double sumOfDerivationAverage = sumOfDerivation / doubleList.Count; return Math.Sqrt(sumOfDerivationAverage - (average * average)); }
/// <summary> /// Calculates the standard deviation assuming the whole population is provided (not sample st. dev.). /// </summary> /// <param name="A">An vector of doubles, A.</param> /// <returns>System.Double.</returns> public static double standardDeviation(this IList <double> A) { var mean = A.Average(); var variance = A.Sum(a => (a - mean) * (a - mean)); return(Math.Sqrt(variance / A.Count)); }
public RatingResult Compute(IList <RestrauntReview> reviews) { var result = new RatingResult(); result.Rating = (int)reviews.Average(r => r.Rating); return(result); }
/// <summary> /// Variance normalization (divide by unbiased estimate of stdev) /// </summary> /// <param name="vectors">Sequence of feature vectors</param> public static void NormalizeVariance(IList <FeatureVector> vectors, int bias = 1) { var n = vectors.Count; if (n < 2) { return; } var featureCount = vectors[0].Features.Length; for (var i = 0; i < featureCount; i++) { var mean = vectors.Average(t => t.Features[i]); var std = vectors.Sum(t => (t.Features[i] - mean) * (t.Features[i] - mean) / (n - bias)); if (std < Math.Abs(1e-10)) // avoid dividing by zero { std = 1; } foreach (var vector in vectors) { vector.Features[i] /= (float)Math.Sqrt(std); } } }
static void DisplayStats(IList <Response> responses) { if (!responses.Any()) { return; } var average = responses.Average(x => (x.EndUtc - x.StartUtc).TotalMilliseconds); ClearLine(); Console.WriteLine("Average time: {0} ms", Convert.ToInt32(average)); var min = responses.Min(x => x.StartUtc); var max = responses.Max(x => x.EndUtc); var count = responses.Count; var timespan = Convert.ToInt32((max - min).TotalMilliseconds); timespan = timespan == 0 ? 0 : timespan / 1000; var rps = timespan == 0 ? 0 : count / timespan; ClearLine(); Console.WriteLine("Performance: {0} rps ({1} reqs in {2})", Convert.ToInt32(rps), responses.Count, timespan); ClearLine(); Console.WriteLine("Threads: {0}", responses.Select(x => x.TaskId).Distinct().Count()); ClearLine(); Console.WriteLine("Errors: {0}", responses.Count(x => !x.Success)); }
private void GatherData(IList <GeneticAlgorithmAgent> agents) { DataCollector.AddDataPoint(DataCollector.SetsNames.MinFitness, agents.Min(agent => agent.Fitness)); DataCollector.AddDataPoint(DataCollector.SetsNames.MaxFitness, agents.Max(agent => agent.Fitness)); DataCollector.AddDataPoint(DataCollector.SetsNames.AvgFitness, agents.Average(agent => agent.Fitness)); IDictionary <string, int> topologyTrends = new Dictionary <string, int>(); foreach (var network in agents.Select(agent => agent.Network)) { string topologyIdentifier = network.GetTopologyIdentifier(); if (!topologyTrends.ContainsKey(topologyIdentifier)) { topologyTrends.Add(topologyIdentifier, 1); } else { topologyTrends[topologyIdentifier]++; } } var topologyTrendsStringBuilder = new StringBuilder(); foreach (var kvp in topologyTrends) { topologyTrendsStringBuilder.Append($"{kvp.Key}:{kvp.Value},"); } DataCollector.AddDataPoint(DataCollector.SetsNames.TopologyTrends, topologyTrendsStringBuilder.ToString()); }
public double GetAverageStudentGrade() { Debug.Assert(studentGrades != null && studentGrades.Count > 0, "Student grades are not initialized!"); return(studentGrades.Average()); }
public void AverageTest_LongSelector(IList <long> source) { var expected = source.Average(v => - v); var actual = source.AverageF(v => - v); Assert.Equal(expected, actual); }
public void AverageTest_Int(IList <int> source) { var expected = source.Average(); var actual = source.AverageF(); Assert.Equal(expected, actual); }
public void AverageTest_DoubleSelector(IList <double> source) { var expected = source.Average(v => - v); var actual = source.AverageF(v => - v); Assert.Equal(expected, actual, 3); }
private async Task FillDetails(string currency) { await Task.Run(() => { LendingOffer highLoanRate = null; LendingOffer lowLoanRate = null; IList <LendingOffer> periodOffers = null; try { DateTime horaInicio = DateTime.Now; DateTime horaFim = DateTime.Now; txtMinutos.Dispatcher.Invoke(DispatcherPriority.Render, (ThreadStart) delegate { int tempoMinutoPeriodo = 20; if (!int.TryParse(txtMinutos.Text, out tempoMinutoPeriodo)) { tempoMinutoPeriodo = 20; } horaInicio = DateTime.Now.AddMinutes(-tempoMinutoPeriodo); }); using (var context = new LoanContext()) periodOffers = context.LendingOffers.Where(o => (o.currency.Equals(currency) && (o.dataRegistro >= horaInicio && o.dataRegistro <= horaFim))).ToList(); ResetLabels(); if (periodOffers.Any()) { highLoanRate = periodOffers.OrderByDescending(o => o.rate).First(); lowLoanRate = periodOffers.OrderBy(o => o.rate).First(); var averageLoanRate = periodOffers.Average(x => x.rate); this.Dispatcher.Invoke(DispatcherPriority.Render, (ThreadStart) delegate { txtMaiorLoanRate.Text = highLoanRate.rate.ToString("0.0000%"); txtMenorLoanRate.Text = string.Concat(lowLoanRate.rate.ToString("0.0000%"), " ", "(", lowLoanRate.dataRegistro.ToShortTimeString(), ")"); txtRateAverage.Text = averageLoanRate.ToString("0.0000%"); txtDataRegistro.Text = highLoanRate.dataRegistro.ToString(); txtCountLoanOffers.Text = periodOffers.Count() + " in " + txtMinutos.Text + " mins."; }); } } catch { ResetLabels(); } finally { highLoanRate = null; lowLoanRate = null; periodOffers = null; } }); }
private int AverageYears(IList <Profile> list) { var f = DateTime.Now - DateTime.Now; long averageticks = (long)list.Average(x => (DateTime.Now - x.DateBirth).Ticks); int year = new DateTime(averageticks).Year; return(year); }
public double GetStutteringTimePercentage(IList <double> sequence, double stutteringFactor) { var average = sequence.Average(); var stutteringTime = sequence.Where(element => element > stutteringFactor * average).Sum(); return(100 * stutteringTime / sequence.Sum()); }
private string computeEstimatedTime() { double avg = taskTime.Average(); long estimatedMillis = (long)(avg * userIdsToProcess.Count); TimeSpan estimatedTimeSpan = TimeSpan.FromMilliseconds(estimatedMillis); return(estimatedTimeSpan.Days > 0 ? estimatedTimeSpan.ToString("%d' d. '%h' godz. '%m' min.'") : estimatedTimeSpan.ToString("%h' godz. '%m' min.'")); }
public static List <float> ToStdNorm(this IList <float> values) { var avg = values.Average(); var cnt = values.Count; var std = (float)Math.Sqrt(values.Sum(d => (d - avg) * (d - avg))); return(values.Select(x => (x - avg) / std).ToList()); }
/// <summary> /// Gets the average elevation (z) from a collection of points. /// </summary> /// <param name="existingPoints">The points.</param> /// <returns>The average elevation.</returns> public static double GetAverageElevation(IList <XYZ> existingPoints) { if (existingPoints.Count == 0) { return(0); } return(existingPoints.Average <XYZ>(xyz => xyz.Z)); }
public void average() { var averageItemsInStock = Session.CreateCriteria <Product>() .SetProjection(Projections.Avg("UnitsInStock")) .UniqueResult <double>(); Assert.AreEqual(_products.Average(p => p.UnitsInStock), averageItemsInStock); }
private static double CalculateStandardDeviation(IList <double> values) { var average = values.Average(); var sumOfSquaresOfDifferences = values.Select(val => (val - average) * (val - average)).Sum(); var standardDeviation = Math.Sqrt(sumOfSquaresOfDifferences / (values.Count() - 1)); return(standardDeviation); }
public void average() { var averageItemsInStock = Session.QueryOver <Product>() .Select(Projections.Avg <Product>(p => p.UnitsInStock)) .SingleOrDefault <double>(); Assert.AreEqual(_products.Average(p => p.UnitsInStock), averageItemsInStock); }
private decimal GetAverageRating(IList <Rating> ratings) { if (ratings.Any()) { return(Math.Round(ratings.Average(r => r.Score) * 2, MidpointRounding.AwayFromZero) / 2); } return(0M); }
private static void FindSumAndAverage(IList <int> numbers) { long numbersSum = 0; double numbersAverage = 0; numbersSum = numbers.Sum(); numbersAverage = numbers.Average(); Console.WriteLine("The sum of your sequence is: {0} and the avgerage is: {1}.", numbersSum, numbersAverage); }
private static float StandardDeviation(IList <float> values, out float average) { average = values.Average(); var a = average; var sumOfSquaresOfDiffs = values.Select(v => (v - a) * (v - a)).Sum(); var sd = Math.Sqrt(sumOfSquaresOfDiffs / values.Count); return((float)sd); }
/// <summary> /// ピアソンの積率相関係数を計算します。 /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public static double SampleCorrelationCoefficient(IList <double> x, IList <double> y) { var averageX = x.Average(); var averageY = y.Average(); var numerator = Enumerable.Range(0, x.Count).Sum(i => (x[i] - averageX) * (y[i] - averageY)); var denominator = Math.Pow(x.Sum(i => Math.Pow(i - averageX, 2)) * y.Sum(i => Math.Pow(i - averageY, 2)), 0.5); return(numerator / denominator); }
public void Init(IList <double> inputReturns) { Mean = inputReturns.Average(); var count = inputReturns.Count; var deMeanedReturns = inputReturns.Select(rett => rett - Mean).ToArray(); Stdev = CalculateStdev(deMeanedReturns, count); Skew = CalculateSkew(deMeanedReturns, count); Kurt = CalculateKurt(deMeanedReturns, count); }
public static float AverageNoOutliers(this IList <float> data) { data = data.OrderBy(x => x).ToList(); float average = data.Average(); float lowerQuartile = new float[] { data[(int)Math.Ceiling(data.Count / 4.0)], data[(int)Math.Floor(data.Count / 4.0)] }.Average(); float higherQuartile = new float[] { data[(int)Math.Ceiling(data.Count * 3.0 / 4.0)], data[(int)Math.Floor(data.Count * 3.0 / 4.0)] }.Average(); float IQR = higherQuartile - lowerQuartile; return(data.Where(x => x > lowerQuartile - 1.5 * IQR || x < higherQuartile + 1.5 * IQR).Average()); }
public async Task ShouldCalculateAverageTemperatureFromListOfResults(IList <double> fakeData) { _fakeBomService.GetTemperatureDataAsync().Returns(fakeData); var actual = await _sut.CalculateAverageTempAsync(); var expected = fakeData.Average(); actual.Should().Be(expected); }
public SigmaDistributor(IList <double> source, float sampling) { if (source == null) { throw new ArgumentNullException("source"); } this.source = source; this.sampling = sampling; median = source.Average(); sigma = Sigma.Get(source); }
public AggregationOperationResult Do(IList <UniversalValue> input) { if (input == null) { throw new ArgumentNullException("input"); } AggregationOperationResult result = new AggregationOperationResult(); result.Add("avg", input.Average()); return(result); }
internal Double CalculateZScore(IList <Double> listValues, Double value) { Double result = 0; Double stdDev = CalculateStandardDeviation(listValues); Double avg = listValues.Average(); result = (value - avg) / stdDev; return(result); }
public override string BuildMessage(IList <TimeSpan> context, TimeSpan alertPeriod) { var times = context.Count == 1 ? "time" : "times"; var maxTimeSpan = context.Max(x => x); var minTimeSpan = context.Min(x => x); var avg = context.Average(x => x.TotalMilliseconds); var median = context.Median(x => x.TotalMilliseconds); return($"{_serviceName} took >{_slowResponseThreshold.TotalSeconds}s to respond *{context.Count}* {times} in the past {alertPeriod.TotalSeconds}s.\n" + $"Min: {minTimeSpan.TotalMilliseconds:N0} ms Max: {maxTimeSpan.TotalMilliseconds:N0} ms Avg: {avg:N0} ms Median: {median:N0} ms"); }
private double GenerateValue(IList <double> data) { IList <double> initialLine = IdleRpmValueExtractor.ExtractInitialIdleLine(data); if (initialLine.Count > 0) { return(initialLine.Average()); } return(0); }
public double Merge(IList<double> values) { return values.Average(); }
private string CreateSimulationResultText(IList<IBattle> battleList) { double attackerWins = (double) battleList.Count(b => b.SurvivingAttackers.Count > 0 && b.SurvivingDefenders.Count == 0) / battleList.Count * 100; double defenderWins = (double)battleList.Count(b => b.SurvivingDefenders.Count > 0 && b.SurvivingAttackers.Count == 0) / battleList.Count * 100; double allDead = (double)battleList.Count(b => b.SurvivingAttackers.Count == 0 && b.SurvivingDefenders.Count == 0) / battleList.Count * 100; double avgRounds = battleList.Average(b => b.RoundCount); return String.Format("Attacker wins: {1:0.##}%{0}Defender wins: {2:0.##}%{0}All dead: {3:0.##}%{0}Rounds avg.: {4:0.##}{0}Simulation runs: {5}", Environment.NewLine, attackerWins, defenderWins, allDead, avgRounds, _simulationRuns); }
/// <summary> /// Averages a list of numbers. /// </summary> /// <param name="numbers">List of numbers to be averaged.</param> /// <returns name="average">Average of the list of numbers.</returns> /// <search>avg,mean</search> public static double Average(IList<double> numbers) { //DS will do proper marshalling, even if integer is sent. return numbers.Average(); }
public static DummyPoint Centroid(IList<DummyPoint> points) { return ByCoordinates(points.Average(p => p.X), points.Average(p => p.Y), points.Average(p => p.Z)); }
private float OneSigmaFromAverage(IList<float> data) { float average = data.Average(); float sumSquares = 0; foreach (float val in data) { sumSquares += (average - val)*(average - val); } return data.Count > 1 ? (float) (Math.Sqrt(sumSquares)/(data.Count - 1)) : float.NaN; }
private static double CalculateDeviation(IList<double> source, int count) { double avg = source.Average(); double deviation = 0; for (int index = 0; index < count; index++) { deviation += (source[index] - avg) * (source[index] - avg); } return deviation; }
private static double WeightedAverage(IList<double> input, int spread = 40) { if (input.Count == 1) { return input.Average(); } var weightdifference = spread / (input.Count() - 1); var averageWeight = 50; var startWeight = averageWeight - spread / 2; return input.Select((x, i) => x * (startWeight + (i * weightdifference))) .Sum() / (averageWeight * input.Count()); }
public void Update(IList<Genome> genomes) { Total = genomes.Sum(x => x.Fitness); Best = genomes.Max(x => x.Fitness); Worst = genomes.Min(x => x.Fitness); Average = genomes.Average(x => x.Fitness); TotalChange = Total - PreviousGenerationsTotal.LastOrDefault(); BestChange = Best - PreviousGenerationsBest.LastOrDefault(); WorstChange = Worst - PreviousGenerationsWorst.LastOrDefault(); AverageChange = Average - PreviousGenerationsAverage.LastOrDefault(); }
// Something for Applicable private CLLocationCoordinate2D FindCentre(IList<BusStop> busStops) { double latitude = busStops.Average(bs => bs.Latitude); double longitude = busStops.Average(bs => bs.Longtitude); return new CLLocationCoordinate2D(latitude, longitude); }
/// <summary> /// Compute and save statistics /// </summary> /// <param name="grid">The grid</param> /// <param name="nei">The neighborhoods</param> public void GridStats(Grid grid, IList<Neighborhood> nei) { var stats = new GridStats { MoveCount = grid.Players.Count(p => p.RequestMove), TypeChangeCount = grid.Players.Count(p => p.RequestTypeChange), TimeoutCount = grid.Players.Count(p => p.HasTimeout), SegregAvg = nei.Average(x => x.OwnShare), SegregStd = nei.StdDev(x => x.OwnShare) }; grid.GridStats = stats; db.Save(); }
public void GroupItem(HotItem item, IList<HotItem> result) { int quantity = result.Sum(x => x.Quantity); double avg = result.Average(x => x.UnitPrice); this.UnitPrice = (int)Math.Round(avg); this.Quantity = quantity; this.DisplayName = String.Format("Transactions {0}", result.Count()); this.DateTimeStamp = item.DateTimeStamp; this.TransactionTime = result.OrderByDescending(t => t.TransactionTime).First().TransactionTime; if (TransactionTime == DateTime.MinValue) { var tempDateTime = ParseTimeStamp(DateTimeStamp); if (tempDateTime.HasValue) { this.TransactionTime = tempDateTime.Value; } } this.Name = item.Name; this.ItemBuildDone = item.ItemBuildDone; this.Image = item.Image; this.ListingId = item.ListingId; this.DataId = item.DataId; this.BuyPrice = item.BuyPrice; this.SellPrice = item.SellPrice; }