protected bool ChunkIsStable(IEnumerable<Point> points)
 {
     const int maxVariance = 50;
     var xVariance = points.Max(p => p.X) - points.Min(p => p.Y);
     var yVariance = points.Max(p => p.X) - points.Min(p => p.Y);
     return xVariance < maxVariance && yVariance < maxVariance;
 }
Beispiel #2
0
 protected bool ChunkIsStable(IEnumerable<Zipping.Pair<int, int>> points)
 {
     const int maxVariance = 50;
     var xVariance = points.Max(p => p.First) - points.Min(p => p.First);
     var yVariance = points.Max(p => p.Second) - points.Min(p => p.Second);
     return xVariance < maxVariance && yVariance < maxVariance;
 }
Beispiel #3
0
        public static BoundingBox MinimumOf(IEnumerable<BoundingBox> boxes)
        {
            decimal northmost = boxes.Max(b => b.North);
            decimal southmost = boxes.Min(b => b.South);
            decimal eastmost  = boxes.Max(b => b.East);
            decimal westmost  = boxes.Min(b => b.West);

            return new BoundingBox { North = northmost, South = southmost, East = eastmost, West = westmost };
        }
        public void SetPlotModelAxes(
            IEnumerable<DataPoint> seriesPoints,
            string xAxisTitle, string yAxisTitle)
        {
            double minXVal = seriesPoints.Min<DataPoint>(dp => dp.X);
            double maxXVal = seriesPoints.Max<DataPoint>(dp => dp.X);
            double minYVal = seriesPoints.Min<DataPoint>(dp => dp.Y);
            double maxYVal = seriesPoints.Max<DataPoint>(dp => dp.Y);

            PlotType = PlotType.XY;
            SetXAxisForPlotModel(minXVal, maxXVal, xAxisTitle);
            SetYAxisForPlotModel(minYVal, maxYVal, yAxisTitle);
        }
Beispiel #5
0
 public OctreeLookup(IEnumerable<float[]> points)
 {
     tree = new Octree(
         points.Max(p => p[0]),
         points.Min(p => p[0]),
         points.Max(p => p[1]),
         points.Min(p => p[1]),
         points.Max(p => p[2]),
         points.Min(p => p[2]),
         points.Count());
     foreach (var p in points)
         tree.AddNode(p[0], p[1], p[2], p);
 }
Beispiel #6
0
        public static IEnumerable<double> Normalize(IEnumerable<double> collection)
        {
            double min = collection.Min();
            double max = collection.Max();

            return collection.Select(f => Normalize(f, min, max));
        }
        public static VehicleStatisticsModel Calculate(IEnumerable<Model.FillupEntry> fillUps, bool includeFirst = true)
        {
            if (!fillUps.Any()) return new VehicleStatisticsModel();

            var firstFillUp = fillUps.OrderBy(x => x.Date).FirstOrDefault();

            double totalFuelCost = 0.0;
            double totalUnits = 0.0;
            double totalCost = 0.0;
            int totalDistance = 0;

            foreach (var fillUp in fillUps)
            {
                if (includeFirst || fillUp != firstFillUp)
                {
                    totalFuelCost += fillUp.PricePerUnit*fillUp.TotalUnits;
                    totalUnits += fillUp.TotalUnits;
                    totalCost += fillUp.TotalCost;
                    totalDistance += fillUp.Distance ?? 0;
                }
            }

            var odometer = fillUps.Max(x => x.Odometer);

            var earliestEntryDate = fillUps.Min(x => x.Date).ToUniversalTime();
            var today = DateTime.UtcNow.Date;
            var totalMonths = CalculateDifferenceInMonths(earliestEntryDate.Date, today.Date);

            return new VehicleStatisticsModel(totalFuelCost, totalUnits, totalCost, totalDistance, odometer, totalMonths);
        }
Beispiel #8
0
        /// <summary>
        /// Gets area that's occupied by user selected points
        /// </summary>
        /// <param name="selector">Selected points container</param>
        /// <param name="maxWorkingArea">Minimum allowed area size</param>
        /// <returns></returns>
        public static System.Drawing.Rectangle GetArea(IEnumerable<PointSelector.SelectedPoint> selector, int workingAreaSize)
        {

            var minX = selector.Min(p => p.Location.X);
            var maxX = selector.Max(p => p.Location.X);
            var minY = selector.Min(p => p.Location.Y);
            var maxY = selector.Max(p => p.Location.Y);

            int areaWidth = maxX - minX;
            int areaHeight = maxY - minY;

            areaWidth = areaWidth > workingAreaSize ? workingAreaSize : areaWidth;
            areaWidth = areaHeight > workingAreaSize ? workingAreaSize : areaHeight;

            if (areaWidth < workingAreaSize)
            {
                minX = minX - (workingAreaSize - areaWidth) / 2;
                minX = minX < 0 ? 0 : minX;
                areaWidth = workingAreaSize;
            }

            if (areaHeight < workingAreaSize)
            {
                minY = minY - (workingAreaSize - areaHeight) / 2;
                minY = minY < 0 ? 0 : minY;
                areaHeight = workingAreaSize;
            }

            return new System.Drawing.Rectangle(minX, minY, areaWidth, areaHeight);
        }
        public static DateTime MinDate(this IEnumerable<DateTime> left, IEnumerable<DateTime> right)
        {
            var minLeft = left.Any() ? left.Min() : DateTime.MaxValue;
            var minRight = right.Any() ? right.Min() : DateTime.MaxValue;

            return minLeft.Ticks < minRight.Ticks ? minLeft : minRight;
        }
Beispiel #10
0
        public List<ILNode> ConvertToAst(List<Instruction> body, IEnumerable<ExceptionHandler> ehs)
        {
            List<ILNode> ast = new List<ILNode>();

            while (ehs.Any()) {
                ILTryCatchBlock tryCatchBlock = new ILTryCatchBlock();

                // Find the first and widest scope
                int tryStart = ehs.Min(eh => eh.TryStart.Offset);
                int tryEnd   = ehs.Where(eh => eh.TryStart.Offset == tryStart).Max(eh => eh.TryEnd.Offset);
                var handlers = ehs.Where(eh => eh.TryStart.Offset == tryStart && eh.TryEnd.Offset == tryEnd).ToList();

                // Cut all instructions up to the try block
                {
                    int tryStartIdx;
                    for (tryStartIdx = 0; body[tryStartIdx].Offset != tryStart; tryStartIdx++);
                    ast.AddRange(ConvertToAst(body.CutRange(0, tryStartIdx)));
                }

                // Cut the try block
                {
                    List<ExceptionHandler> nestedEHs = ehs.Where(eh => (tryStart <= eh.TryStart.Offset && eh.TryEnd.Offset < tryEnd) || (tryStart < eh.TryStart.Offset && eh.TryEnd.Offset <= tryEnd)).ToList();
                    int tryEndIdx;
                    for (tryEndIdx = 0; tryEndIdx < body.Count && body[tryEndIdx].Offset != tryEnd; tryEndIdx++);
                    tryCatchBlock.TryBlock = ConvertToAst(body.CutRange(0, tryEndIdx), nestedEHs);
                }

                // Cut all handlers
                tryCatchBlock.CatchBlocks = new List<ILTryCatchBlock.CatchBlock>();
                foreach(ExceptionHandler eh in handlers) {
                    int start;
                    for (start = 0; body[start] != eh.HandlerStart; start++);
                    int end;
                    for (end = 0; body[end] != eh.HandlerEnd; end++);
                    int count = end - start;
                    List<ExceptionHandler> nestedEHs = ehs.Where(e => (start <= e.TryStart.Offset && e.TryEnd.Offset < end) || (start < e.TryStart.Offset && e.TryEnd.Offset <= end)).ToList();
                    List<ILNode> handlerAst = ConvertToAst(body.CutRange(start, count), nestedEHs);
                    if (eh.HandlerType == ExceptionHandlerType.Catch) {
                        tryCatchBlock.CatchBlocks.Add(new ILTryCatchBlock.CatchBlock() {
                            ExceptionType = eh.CatchType,
                            Body = handlerAst
                        });
                    } else if (eh.HandlerType == ExceptionHandlerType.Finally) {
                        tryCatchBlock.FinallyBlock = handlerAst;
                    } else {
                        // TODO
                    }
                }

                ehs = ehs.Where(eh => eh.TryStart.Offset > tryEnd).ToList();

                ast.Add(tryCatchBlock);
            }

            // Add whatever is left
            ast.AddRange(ConvertToAst(body));

            return ast;
        }
Beispiel #11
0
    public IEnumerable<Card> Play(IEnumerable<Card> hand, IEnumerable<Card> table, int rank, Suit suit, Mode mode, bool revolution, History history)
    {
        if (revolution && rank != Card.RankOfJoker)
        {
            rank = 14 - rank;
        }

        if (hand == null || hand.Count() == 0)
            return null;

        int count = table.Count();

        // 初手はとりあえず一番弱いのを出しとく。
        if (mode.Match(Mode.First))
        {
            var min = hand.Min(x => Game.Rank(x, revolution));
            return hand.Where(x => Game.Rank(x, revolution) == min);
        }

        if (mode.Match(Mode.Normal))
        {
            if(mode.Match(Mode.SuitBound))
            {
                return hand.MinCard(x => Game.Rank(x, revolution) > rank && x.Suit == suit, revolution);
            }
            else
            {
                return hand.MinCard(x => Game.Rank(x, revolution) > rank, revolution);
            }
        }

        if(mode.Match(Mode.Multiple))
        {
            for (int i = rank + 1; i <= 13; i++)
            {
                // 出せる
                var c = hand.Where(x => Game.Rank(x, revolution) == i);
                if (c.Count() >= count)
                    return c.Take(count);

                // Joker含めれば出せる
                if (c.Count() + 1 == count && hand.FirstOrDefault(x => x.Suit == Suit.Joker) != null)
                    return c.Concat(hand.Where(x => x.Suit == Suit.Joker).Take(count));
            }
        }

        if (mode.Match(Mode.SequenceBound))
            return null; //todo また未対応

        if (mode.Match(Mode.Sequence))
        {
            if (mode.Match(Mode.SuitBound))
                return hand.Sequence(rank, revolution, count, suit);
            else
                return hand.Sequence(rank, revolution, count);
        }

        return null;
    }
        public override Character GetTarget(IEnumerable<Character> targetsList)
        {
            Character target = targetsList
                .Where(t => t.Team == this.Team && t.IsAlive == true && t.Id != this.Id)
                .FirstOrDefault(t => t.HealthPoints == targetsList.Min(h => h.HealthPoints));

            return target;
        }
Beispiel #13
0
 public PerfIteratorResult(IEnumerable<PerfRoundResult> resultsList)
 {
     this.ResultsList = resultsList;
     this.RepeatCount = resultsList.Count();
     this.OverallAverageTicks = resultsList.Average(r => r.AverageTicks);
     this.OverallMaxTicks = resultsList.Max(r => r.MaxTicks);
     this.OverallMinTicks = resultsList.Min(r => r.MinTicks);
 }
    protected void ConfigureParameters(IEnumerable<double> data) {
      double originalRangeStart = data.Min();
      double originalRangeEnd = data.Max();

      double originalRangeWidth = originalRangeEnd - originalRangeStart;
      double targetRangeWidth = Range.End - Range.Start;

      Multiplier = targetRangeWidth / originalRangeWidth;
      Addend = Range.Start - originalRangeStart * Multiplier;
    }
Beispiel #15
0
        /// <summary>
        /// Creates a Polyline from a list of points and calculates the lines and bounds of the result
        /// </summary>
        /// <param name="points">The list of points that define the polyline</param>
        /// <returns>a Polyline object</returns>
        public static Polyline FromPoints(IEnumerable<Point> points)
        {
            Polyline poly = new Polyline();

            poly.Points = points.ToArray();
            if (poly.Points.Length > 1) {
                poly.Lines = new Line[poly.Points.Length - 1];
                for (int i = 0; i < poly.Lines.Length; i++) {
                    poly.Lines[i] = Line.FromPoints(
                        new Vector2(poly.Points[i].X, poly.Points[i].Y),
                        new Vector2(poly.Points[i + 1].X, poly.Points[i + 1].Y));
                }
            }

            poly.Bounds.X = points.Min(x => x.X);
            poly.Bounds.Y = points.Min(x => x.Y);
            poly.Bounds.Width = points.Max(x => x.X) - points.Min(x => x.X);
            poly.Bounds.Height = points.Max(x => x.Y) - points.Min(x => x.Y);

            return poly;
        }
Beispiel #16
0
        private void ExecuteIndexingInternal(IEnumerable<IndexToWorkOn> indexesToWorkOn, Action<JsonDocument[]> indexingOp)
        {
            var lastIndexedGuidForAllIndexes = indexesToWorkOn.Min(x => new ComparableByteArray(x.LastIndexedEtag.ToByteArray())).ToGuid();

            JsonDocument[] jsonDocs = null;
            try
            {
                transactionalStorage.Batch(actions =>
                {
                    jsonDocs = actions.Documents.GetDocumentsAfter(lastIndexedGuidForAllIndexes)
                        .Where(x => x != null)
                        .Select(doc =>
                        {
                            DocumentRetriever.EnsureIdInMetadata(doc);
                            return doc;
                        })
                        .Take(context.Configuration.MaxNumberOfItemsToIndexInSingleBatch) // ensure that we won't go overboard with reading and blow up with OOM
                        .ToArray();
                });

                if (jsonDocs.Length > 0)
                    indexingOp(jsonDocs);
            }
            finally
            {
                if (jsonDocs != null && jsonDocs.Length > 0)
                {
                    var last = jsonDocs.Last();
                	
					Debug.Assert(last.Etag != null);
                	Debug.Assert(last.LastModified != null);

                	var lastEtag = last.Etag.Value;
                	var lastModified = last.LastModified.Value;

                    var lastIndexedEtag = new ComparableByteArray(lastEtag.ToByteArray());
                    // whatever we succeeded in indexing or not, we have to update this
                    // because otherwise we keep trying to re-index failed documents
                    transactionalStorage.Batch(actions =>
                    {
                        foreach (var indexToWorkOn in indexesToWorkOn)
                        {
                            if (new ComparableByteArray(indexToWorkOn.LastIndexedEtag.ToByteArray()).CompareTo(lastIndexedEtag) > 0)
                                continue;
                            actions.Indexing.UpdateLastIndexed(indexToWorkOn.IndexName, lastEtag, lastModified);
                        }
                    });
                }
            }
        }
        public static int GetHexShade(IEnumerable<KMLData> data, decimal current)
        {
            decimal min = data.Min(i => i.Amount);
            decimal value = (data.Max(i => i.Amount) - min) / 4;

            if (current <= min + value)
                return 0;
            else if (current <= min + (value * 2))
                return 1;
            else if (current <= min + (value * 3))
                return 2;
            else
                return 3;
        }
        public PersonApiResponse GetPeopleInfo(IEnumerable<Person> personList)
        {
            PersonApiResponse response = new PersonApiResponse();
            response.NumberOfPeople = personList.Count();
            response.MaxAge = personList.Max(c=>c.Age);
            response.MinAge = personList.Min(c=>c.Age);
            response.AverageOfAge = personList.Average(c=>c.Age);

            response.NumberOfAngles = personList.Where(c => c.Race == PersonRace.Angles).Count();
            response.NumberOfAsians = personList.Where(c => c.Race == PersonRace.Asians).Count();
            response.NumberOfJutes = personList.Where(c => c.Race == PersonRace.Jutes).Count();
            response.NumberOfSaxons = personList.Where(c => c.Race == PersonRace.Saxons).Count();

            return response;
        }
Beispiel #19
0
        //Naive calculation of Hausdorff distance between two sets of points
        public static double Distance(IEnumerable<Coordinate> a, IEnumerable<Coordinate> b)
        {
            var distance = 0D; //drive distance up
            var shortest = double.MaxValue; //drive shortest found down

            foreach(var d in a.Select(pa => b.Min(pb => pb.Distance(pa))))
            {
                if(d < shortest)
                    shortest = d;
                if(shortest > distance)
                    distance = shortest;
            }

            return distance;
            //return a.Max(pa => b.Min(pb => pb.Distance(pa)));
        }
        private async Task<IEnumerable<SnapshotSpan>> ExpandSelectionAsync(IEnumerable<SnapshotSpan> selectedSpans, CommandArgs args, CancellationToken cancellationToken)
        {
            var selectedSpansStart = selectedSpans.Min(span => span.Start);
            var selectedSpansEnd = selectedSpans.Max(span => span.End);
            ITextSnapshot snapshot = args.TextView.TextSnapshot;

            IEnumerable<SnapshotSpan> newSpans = await GetExecutableSyntaxTreeNodeSelectionAsync(
                TextSpan.FromBounds(selectedSpansStart, selectedSpansEnd),
                args,
                snapshot,
                cancellationToken).ConfigureAwait(true);

            return newSpans.Any()
                ? newSpans.Select(n => new SnapshotSpan(snapshot, n.Span.Start, n.Span.Length))
                : selectedSpans;
        }
Beispiel #21
0
        private static void PlaySong(IEnumerable<Note> notes)
        {
            var offset = (int)notes.Min(x => x.Pitch);

            foreach (var note in notes)
            {
                if (note.Pitch == Pitch.Rest)
                {
                    Thread.Sleep(note.Duration);
                }
                else
                {
                    Console.WriteLine("{0}#", new String('.', (int)note.Pitch - offset));
                    Console.Beep((int)Constants.Frequencies[note.Pitch], note.Duration);
                }
            }
        }
        public static CalendarioViewModel ContruirCalendario(IEnumerable<Evento> eventos)
        {
            List<EventoCalendarioViewModel> listaEventos = new List<EventoCalendarioViewModel>();

            //TODO RETIRAR
            listaEventos.Add(new EventoCalendarioViewModel()
            {
                Id = "1",
                Subject = "Teste",
                Description = "",
                StartTime = "11/5/2011 08:00",
                EndTime = "11/5/2011 10:00",
                Location = "",
                IsAllDayEvent = 0,
                Color = "0",
                RecurringRule = ""
            });

            foreach (Evento evento in eventos)
            {
                listaEventos.Add(new EventoCalendarioViewModel()
                {
                    Id = evento.Id,
                    Subject = evento.Nome,
                    Description = evento.Descricao,
                    StartTime = evento.DataInicio.ToString("M/d/yyyy HH:mm"),
                    EndTime = evento.DataFim.ToString("M/d/yyyy HH:mm"),
                    Location = ObterTextoLocais(evento),
                    IsAllDayEvent = 0,
                    Color = ObterCor(evento),
                    RecurringRule = ""
                });
            }

            var calendario = new CalendarioViewModel();
            foreach (EventoCalendarioViewModel item in listaEventos)
            {
                calendario.events.Add(item.GetValues());
            }

            calendario.start =  eventos.Count() > 0 ? eventos.Min(e => e.DataInicio).ToString("M/d/yyyy HH:mm") : "";
            calendario.end = eventos.Count() > 0 ? eventos.ToList().Max(e => e.DataFim).ToString("M/d/yyyy HH:mm") : "";
            calendario.issort = true;

            return calendario;
        }
Beispiel #23
0
        public void AddOrUpdate(IEnumerable<WeatherDataEntity> source)
        {
            var time = source.Min(t => t.DateTime);
            var same = new Func<WeatherDataEntity, WeatherDataEntity, bool>((x, y) => x.DateTime == y.DateTime && x.Provider == y.Provider && x.CityId == y.CityId);
            var destination = this.context.Database.SqlQuery<WeatherDataEntity>("SELECT * FROM WeatherData WHERE DateTime >= {0}", time).ToList();

            var insert = source.Where(x => !destination.Any(y => same(x, y))).ToList();
            var update = source.Except(insert).ToList();

            this.context.BulkInsert(insert);

            foreach (var item in update)
            {
                var margeItem = Mapper.Map(item, destination.First(x => same(item, x)));

                this.context.Database.ExecuteSqlCommandSmart("WeatherData_Update", margeItem);
            }
        }
        /// <summary>
        /// Calculates the midrange of the specified collection of numbers.
        /// </summary>
        /// <param name="numbers">The numbers whose midrange is to be calculated.</param>
        /// <returns>
        /// The midrange of the specified collection of numbers.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// The specified collection must not be null.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// The specified collection must not be empty.
        /// </exception>
        public static double Midrange(IEnumerable<double> numbers)
        {
            if (numbers == null)
            {
                throw ArgumentNullException;
            }

            if (!numbers.Any())
            {
                throw EmptyNumbersCollectionException;
            }

            double minValue = numbers.Min();
            double maxValue = numbers.Max();

            double midrange = ArithmeticMeanCalculator.ArithmeticMean(minValue, maxValue);

            return midrange;
        }
Beispiel #25
0
        public bool AreOrdersValid(IEnumerable<int> orders)
        {
            var itemCount = orders.Count();
            var maxOrder = orders.Max();
            var minOrder = orders.Min();

            var distinctOrders = orders.Distinct();
            var distinctCount = distinctOrders.Count();

            if (minOrder == 1 &&
                maxOrder == itemCount &&
                itemCount == distinctCount)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
Beispiel #26
0
 int FindPrimeSievecounts(IEnumerable<int> nums, int n)
 {
     int result = 0;
     if (n < nums.Min() || n > nums.Max())
     {
         return 0;
     }
     else
     {
         for (int i = 2 ; i < n; i++)
         {
             int currentN = nums.ElementAt(i);
             if (currentN % 2 != 0)
             {
                 result = result + 1;
             }
         }
         return result;
     }
 }
        public static string ToBitmask(this IEnumerable <DateTime> dates, bool defaultOnEmpty = false)
        {
            var result = default(string);

            if (dates?.Any() ?? false)
            {
                result = dates?.ToBitmask(
                    begin: dates?.Min() ?? DateTime.MinValue,
                    end: dates?.Max() ?? DateTime.MinValue,
                    defaultOnEmpty: defaultOnEmpty);
            }

            if (result == default)
            {
                result = defaultOnEmpty
                    ? default
                    : string.Empty;
            }

            return(result);
        }
Beispiel #28
0
        public static List<int> Bucketize(IEnumerable<decimal> source, int totalBuckets)
        {
            var min = source.Min();
            var max = source.Max();
            var buckets = new List<int>(new int[totalBuckets]);

            var bucketSize = (max - min) / totalBuckets;
            foreach (var value in source)
            {
                int bucketIndex = 0;
                if (bucketSize > (decimal)0.0)
                {
                    bucketIndex = (int)((value - min) / bucketSize);
                    if (bucketIndex == totalBuckets)
                    {
                        bucketIndex--;
                    }
                }
                buckets[bucketIndex]++;
            }

            return buckets;
        }
Beispiel #29
0
        private static IEnumerable <DataRow> GetFields(Page page)
        {
            DataTable table = page.GetMetadata().GetFieldsOnPageAsDataTable(page.Id);

            table.SetColumnDataType(ColumnNames.TAB_INDEX, typeof(double));
            IDictionary <string, DataRow> fields = table.Rows.Cast <DataRow>()
                                                   .ToDictionary(field => field.Field <string>(ColumnNames.NAME), StringComparer.OrdinalIgnoreCase);
            IEnumerable <DataRow> groups = fields.Values
                                           .Where(field => (MetaFieldType)field.Field <int>(ColumnNames.FIELD_TYPE_ID) == MetaFieldType.Group);

            foreach (DataRow group in groups)
            {
                IEnumerable <DataRow> members = group.Field <string>(ColumnNames.LIST)
                                                ?.Split(Constants.LIST_SEPARATOR)
                                                ?.Select(fieldName => fields.TryGetValue(fieldName, out DataRow field) ? field : null);
                double?tabIndexMin = members?.Min(member => member?.Field <double?>(ColumnNames.TAB_INDEX));
                if (tabIndexMin == null)
                {
                    continue;
                }
                group.SetField(ColumnNames.TAB_INDEX, tabIndexMin.Value - GroupTabIndexDifference);
            }
            return(fields.Values.OrderBy(field => field.Field <double?>(ColumnNames.TAB_INDEX)));
        }
Beispiel #30
0
        public static IEnumerable <T> FindMin <T>(this IEnumerable <T> values, Func <T, double> selector)
        {
            var min = values.Min(selector);

            return(values.Where(v => selector(v) == min));
        }
Beispiel #31
0
 private static string GetMinimumValue(IEnumerable <int> numbers) => numbers?.Min().ToString(CultureInfo.InvariantCulture);
Beispiel #32
0
 protected override decimal CalculateAggregate(IEnumerable <CalculatorValue> values)
 => values.Min(x => x.Value);
 private static int GetAssemblyWeight(IEnumerable <DeclaredSymbolInfo> resultsInAssembly)
 {
     return(resultsInAssembly.Min(d => d.Weight));
 }
 ///<summary></summary>
 public static T SingleWithMin <T, TResult>(this IEnumerable <T> local, Func <T, TResult> selector) => local.Min(selector)
 .Make(x => local.Single(y => selector(y).Equals(x)));
Beispiel #35
0
 protected static Vector2 UpdateBounds(IEnumerable <float> range)
 {
     return(new Vector2(range.Min() - 1, range.Max() + 1));
 }
Beispiel #36
0
        static void Main(string[] args)
        {
            Console.WindowHeight = 50;
            Console.WindowWidth  = 200;
            Console.Title        = "Lambda lambda lambda :>";
            Console.Clear();


            var consoleHelper = new ConsoleHelper();
            var consoleWriter = new RecieveAndWriteConsoleMessage();

            consoleHelper.WritingMessage += consoleWriter.OnMessageWriting;
            consoleHelper.WriteConsoleMessage("----------------------------------------------------------------------");
            //My Extension Methods
            consoleHelper.WriteConsoleMessage("Upper first letter of any name that starts with lower case");
            foreach (var employee in Employee.GetAllEmployees())
            {
                string newEmployeeName = employee.Name.ChangeFirstLetterCaseToUpper();
                consoleHelper.WriteConsoleMessage(newEmployeeName);
            }

            IEnumerable <Employee> employees = Employee.GetAllEmployees();
            double totalEmployeeRaiseCost    = 0;

            totalEmployeeRaiseCost = totalEmployeeRaiseCost.SumEmployeeSalariesWithAnnualPercentRaise(Employee.GetAllEmployees(), 2);
            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage(string.Format("Total cost for all raises: {0:C}", totalEmployeeRaiseCost));

            //LINQ Aggregate Operators
            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Max salary");
            consoleHelper.WriteConsoleMessage(employees.Max(e => e.Salary).ToString());

            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Min salary");
            consoleHelper.WriteConsoleMessage(employees.Min(e => e.Salary).ToString());

            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Average of all salaries");
            consoleHelper.WriteConsoleMessage(employees.Average(e => e.Salary).ToString());

            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Sum of all salaries");
            consoleHelper.WriteConsoleMessage(employees.Sum(e => e.Salary).ToString());

            //Aggregate Function

            //How Aggregate() function works ?
            //Step 1.First "India" is concatenated with "US" to produce result "India, US"
            //Step 2.Result in Step 1 is then concatenated with "UK" to produce result "India, US, UK"
            //Step 3: Result in Step 2 is then concatenated with "Canada" to produce result "India, US, UK, Canada"

            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Aggragate all employee names into a single comma seperated string");
            string nameList = employees.Select(e => e.Name)
                              .ToArray <string>()
                              .Aggregate((a, b) => a + ", " + b);

            consoleHelper.WriteConsoleMessage(nameList);

            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Using modula in Where restriction operator predicate to get only even numbers\nthen aggregate to comma seperated string");
            List <int> numbers = new List <int> {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10
            };
            IEnumerable <int> evenNumbers      = numbers.Where(num => num % 2 == 0);
            string            evenNumberString = evenNumbers.Select(n => n.ToString()).ToArray <string>().Aggregate((a, b) => a + ", " + b);

            consoleHelper.WriteConsoleMessage(evenNumberString);

            //Projection operator
            //Select Many--IEnumerable<string> sequences, which are then flattened to form a single sequence i.e a single IEnumerable<string> sequence.
            //Select many list<string> of AllStates a complany resides in and print a distinct list of the state codes
            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Select Many");
            IEnumerable <string> statesList = Company.GetAllCompanies().SelectMany(c => c.AllStates).Distinct();

            foreach (var states in statesList)
            {
                consoleHelper.WriteConsoleMessage(states);
            }

            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Select multiple columns from company list");
            var companies = Company.GetAllCompanies().Select(c => new { CompanyName = c.Name, CompanyId = c.ID, CompanyState = c.State }).Distinct();

            foreach (var company in companies)
            {
                consoleHelper.WriteConsoleMessage(string.Format("Company ID: {0} - Company Name {1} - Company State {2}", company.CompanyId, company.CompanyName, company.CompanyState));
            }

            //Ordering operators
            var esd = employees.OrderByDescending(e => e.Name);

            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Order name descending");
            foreach (var e in esd)
            {
                consoleHelper.WriteConsoleMessage(string.Format("Emp Name: {0}", e.Name));
            }

            var esa = employees.OrderBy(e => e.Name);

            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Order name ascending");
            foreach (var e in esa)
            {
                consoleHelper.WriteConsoleMessage(string.Format("Emp Name: {0}", e.Name));
            }

            var esb = employees.OrderBy(e => e.Name).ThenBy(e => e.ID);

            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("OrderBy name ThenBy ID");
            foreach (var e in esb)
            {
                consoleHelper.WriteConsoleMessage(string.Format("Name: {0} ID:{1}", e.Name, e.ID));
            }


            //Take,Skip,Take While,Skip While Partitioning Operators
            var est = employees.Take(4);

            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Take the first 4 employees");
            foreach (var e in est)
            {
                consoleHelper.WriteConsoleMessage(string.Format("Name: {0} ID:{1}", e.Name, e.ID));
            }

            var ess = employees.Skip(4);

            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Skip the first 4 employees");
            foreach (var e in ess)
            {
                consoleHelper.WriteConsoleMessage(string.Format("Name: {0} ID:{1}", e.Name, e.ID));
            }

            //SkipWhile must be sorted first
            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Skip while salary is > 55000 -- Don't forget to sort before skipping while");
            var esw = employees.OrderByDescending(e => e.Salary).SkipWhile(e => e.Salary > 55000);

            foreach (var e in esw)
            {
                consoleHelper.WriteConsoleMessage(string.Format("Name: {0} Salary is <= 55000: {1}", e.Name, e.Salary));
            }
            //TakeWhile must be sorted first
            consoleHelper.WriteConsoleMessage("-------------------------");
            consoleHelper.WriteConsoleMessage("Take while salary is > 55000 -- Don't forget to sort before taking while");
            var estake = employees.OrderByDescending(e => e.Salary).TakeWhile(e => e.Salary > 55000);

            foreach (var e in estake)
            {
                consoleHelper.WriteConsoleMessage(string.Format("Name: {0} Salary is > 55000: {1}", e.Name, e.Salary));
            }

            Console.ReadLine();
        }
Beispiel #37
0
 float CenteredMinimumAt(IEnumerable <TextLine> lineset)
 {
     return(lineset.Min(t => t.CenteredAt));
 }
Beispiel #38
0
 float BoundaryLeft(IEnumerable <TextLine> lineset)
 {
     return(lineset.Min(t => t.MarginLeft));
 }
 public static TResult MinOrDefault <T, TResult>(this IEnumerable <T> list, Func <T, TResult> selector)
 {
     return(!list.Any() ? default(TResult) : list.Min(selector));
 }
Beispiel #40
0
 public static int MinOrDefault <T>(
     this IEnumerable <T> source, Func <T, int> selector, int defaultValue = 0)
 {
     return(source.Any() ? source.Min(selector) : defaultValue);
 }
 public static TResult MinOrDefault <TSource, TResult>(this IEnumerable <TSource> source, Func <TSource, TResult> selector, TResult defaultValue)
 {
     return(source.Any() ? source.Min(selector) : defaultValue);
 }
Beispiel #42
0
 /// <summary>
 /// Processes a set of data.
 /// </summary>
 /// <param name="values">A set of data to consider into the limits.</param>
 public void ProcessData(IEnumerable <double> values)
 {
     AutoMax = Math.Max(AutoMax, values.Max());
     AutoMin = Math.Min(AutoMin, values.Min());
     Count  += values.Count();
 }
        protected void UpdateElementEditors(IList[] values, bool getValueOnNewEditors)
        {
            PropertyInfo        indexer       = typeof(IList).GetProperty("Item");
            IEnumerable <IList> valuesNotNull = values.Where(v => v != null);
            int  visibleElementCount          = valuesNotNull.Min(o => (int)o.Count);
            bool showOffset = false;

            if (visibleElementCount > 10)
            {
                this.offset = Math.Min(this.offset, visibleElementCount - 10);
                this.offsetEditor.Maximum         = visibleElementCount - 10;
                this.offsetEditor.ValueBarMaximum = this.offsetEditor.Maximum;
                visibleElementCount = 10;
                showOffset          = true;
            }
            else
            {
                this.offset = 0;
            }

            if (this.sizeEditor.ParentEditor == null)
            {
                this.AddPropertyEditor(this.sizeEditor, 0);
            }
            if (showOffset && this.offsetEditor.ParentEditor == null)
            {
                this.AddPropertyEditor(this.offsetEditor, 1);
            }
            else if (!showOffset && this.offsetEditor.ParentEditor != null)
            {
                this.RemovePropertyEditor(this.offsetEditor);
            }

            this.internalEditors = showOffset ? 2 : 1;

            this.BeginUpdate();


            // Add missing editors
            Type elementType        = GetIListElementType(this.EditedType);
            Type reflectedArrayType = PropertyEditor.ReflectDynamicType(elementType, valuesNotNull.Select(a => GetIListElementType(a.GetType())));

            for (int i = this.internalEditors; i < visibleElementCount + this.internalEditors; i++)
            {
                int  elementIndex         = i - this.internalEditors + this.offset;
                Type reflectedElementType = PropertyEditor.ReflectDynamicType(
                    reflectedArrayType,
                    valuesNotNull.Select(v => indexer.GetValue(v, new object[] { elementIndex })));
                bool           elementEditorIsNew = false;
                PropertyEditor elementEditor;

                // Retrieve and Update existing editor
                if (i < this.ChildEditors.Count())
                {
                    elementEditor = this.ChildEditors.ElementAt(i);
                    if (elementEditor.EditedType != reflectedElementType)
                    {
                        // If the editor has the wrong type, we'll need to create a new one
                        PropertyEditor oldEditor = elementEditor;
                        elementEditor      = this.ParentGrid.CreateEditor(reflectedElementType, this);
                        elementEditorIsNew = true;

                        this.AddPropertyEditor(elementEditor, oldEditor);
                        this.RemovePropertyEditor(oldEditor);
                        this.ParentGrid.ConfigureEditor(elementEditor);
                    }
                }
                // Create a new editor
                else
                {
                    elementEditor      = this.ParentGrid.CreateEditor(reflectedElementType, this);
                    elementEditorIsNew = true;

                    this.AddPropertyEditor(elementEditor);
                    this.ParentGrid.ConfigureEditor(elementEditor);
                }

                elementEditor.Getter       = this.CreateElementValueGetter(indexer, elementIndex);
                elementEditor.Setter       = this.CreateElementValueSetter(indexer, elementIndex);
                elementEditor.PropertyName = "[" + elementIndex + "]";

                // Immediately retrieve a valid value for the newly created editor when requested
                if (elementEditorIsNew && getValueOnNewEditors)
                {
                    elementEditor.PerformGetValue();
                }
            }

            // Remove overflowing editors
            for (int i = this.ChildEditors.Count() - (this.internalEditors + 1); i >= visibleElementCount; i--)
            {
                PropertyEditor child = this.ChildEditors.Last();
                this.RemovePropertyEditor(child);
            }

            this.EndUpdate();
        }
 public static void SkipWhile_SomeFalse(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip)
 {
     ParallelQuery<int> query = labeled.Item;
     int seen = skip.Min();
     Assert.All(query.SkipWhile(x => !skip.Contains(x)), x => Assert.Equal(seen++, x));
     Assert.Equal(count, seen);
 }
Beispiel #45
0
 private static int GetSmallestOffset(IEnumerable <string> lines)
 {
     return(lines.Min(line => String.IsNullOrEmpty(line) ? Int32.MaxValue : GetLineInfo(line)[1]));
 }
 private static void RenderDropDown(HtmlWriter writer, IEnumerable<GridCell> cells, GridCell selectedCell, IEnumerable<int> validOptions)
 {
     writer.RenderBeginTag(HtmlTextWriterTag.Select);
     writer.AddAttribute("value", "");
     if (selectedCell == null)
         writer.AddAttribute("selected","selected");
     writer.RenderFullTag(HtmlTextWriterTag.Option, "None");
     foreach (var cell in cells.Where(c => c.ColumnSpan >= validOptions.Min()))
     {
         writer.AddAttribute(HtmlTextWriterAttribute.Value, cell.Key);
         if (cell == selectedCell)
             writer.AddAttribute("selected", "selected");
         writer.RenderFullTag(HtmlTextWriterTag.Option, cell.Key);
     }
     writer.RenderEndTag();
 }
Beispiel #47
0
        private void SendResults(IEnumerable <ScanResult> results)
        {
            var msg = new MailMessage(_settings.EmailFrom, _settings.EmailTo)
            {
                // ReSharper disable PossibleMultipleEnumeration
                Subject = results.Any() ? string.Format(_settings.EmailSubjectResultsFormat, results.Sum(x => x.Items), results.Min(x => x.LastScan)) : _settings.EmailSubjectEmptyFormat,
                // ReSharper restore PossibleMultipleEnumeration
                SubjectEncoding = Encoding.UTF8,
                BodyEncoding    = Encoding.UTF8,
                IsBodyHtml      = true
            };

            var sb = new StringBuilder(@"<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
  <title>QTH search results</title>
  <style>
    * {box-sizing: border-box}
    html, body {margin:0; padding:0}

    .ext-link {text-align: right; width: 100%;}
    .ext-link a {color: #aaa;}
    .source {width: 100%; font-size: 2rem; font-weight: bold; text-align: center; color: cadetblue; }
    table {border: 1px solid #aaa; margin-bottom: 5px; width: 100%}
    tr, td {border: none; padding: 0; margin: 0}
    td.thumb {vertical-align: top; max-width: 300px}
    td.thumb img {width: 300px}
    td.thumb img.qth {max-width: 300px}
    td.thumb img.eham {max-width: 300px}
    td.title {height: 1.5rem; padding: 2px 5px; font: 1.2rem bold; font-family: helvetica; color: azure; background-color: cornflowerblue; width: 100%}
    td.title a.link {color: azure; text-decoration: none}
    td.title a.cat {float: right; font-size: 1rem; font-style: italic; color: oldlace}
    tr.content {height: 100%}
    tr.content td {padding: 10px 5px 0 5px; height: 100%; font-family: trebuchet ms; vertical-align: top}
    tr.content td .price {color: crimson}
    td.info {height: 1rem; padding: 10px 5px 0 5px; font-family: monospace; font-size: 0.8rem; vertical-align: bottom}
    td.info a.call {color: black;}
    td.info .modified {color: crimson}
</style>
</head>
<body>
");

            if (!string.IsNullOrEmpty(_settings.BodyFileName) && !string.IsNullOrEmpty(_settings.ResourceUrl))
            {
                sb.AppendLine($"<div class='ext-link'><a href='{_settings.ResourceUrl}/{_settings.BodyFileName}' target='_blank'>View this email in a separate browser window</a></div>");
            }

            // ReSharper disable once PossibleMultipleEnumeration
            foreach (var res in results)
            {
                sb.AppendLine($"<div class='source'>{res.Title}</div>\n<div>");
                sb.AppendLine(res.Html);
                sb.AppendLine("</div>");
            }

            sb.AppendLine("</body>\n</html>");

            msg.Body = sb.ToString();

            if (string.IsNullOrEmpty(_settings.BodyFileName))
            {
                return;
            }

            _logger.LogDebug("Saving file");
            File.WriteAllText($"{_settings.ResourceFolder}/{_settings.BodyFileName}", msg.Body);

#if !DEBUG
            _logger.LogDebug($"Sending email to {_settings.EmailTo}");
            var client = new SmtpClient(_settings.SmtpServer);

            if (!string.IsNullOrWhiteSpace(_settings.User))
            {
                client.Credentials = new NetworkCredential(_settings.User, _settings.Password);
            }

            if (_settings.AttachFile && !string.IsNullOrEmpty(_settings.BodyFileName))
            {
                msg.Attachments.Add(new Attachment(_settings.BodyFileName));
            }

            try
            {
                client.Send(msg);
            }
            catch (Exception e)
            {
                _logger.LogError(e.ToString());
            }
#endif
        }
Beispiel #48
0
 static public RectI2 CreatePoints(IEnumerable <VectorI2> points)
 {
     return(new RectI2(points.Min(), points.Max()));
 }
        public override void DesignateMultiCell(IEnumerable <IntVec3> cells)
        {
            var planDesignations = cells.Select(cell => MapUtility.GetPlanDesignationAt(cell, Map)).Where(designation => designation != null).ToList();

            cells = planDesignations.Select(plan => plan.target.Cell);

            if (planDesignations.Count == 0)
            {
                Messages.Message("MorePlanning.MissingPlanningDesignations".Translate(), MessageTypeDefOf.RejectInput);
                return;
            }

            int left   = cells.Min(cell => cell.x);
            int top    = cells.Max(cell => cell.z);
            int right  = cells.Max(cell => cell.x);
            int bottom = cells.Min(cell => cell.z);

            IntVec2 mousePos = new IntVec2((int)Math.Floor(UI.MouseMapPosition().x), (int)Math.Floor(UI.MouseMapPosition().z));

            // Adjust mouse position to nearest planning designation
            if (mousePos.x < left)
            {
                mousePos.x = left;
            }
            else if (mousePos.x > left)
            {
                mousePos.x = right;
            }

            if (mousePos.z > top)
            {
                mousePos.z = top;
            }
            else if (mousePos.z < bottom)
            {
                mousePos.z = bottom;
            }

            int sizeCompX = mousePos.x;
            int sizeCompZ = mousePos.z;

            List <PlanInfo> planDesignationInfo = new List <PlanInfo>();

            // Copy all data from designations
            foreach (var planDesignation in planDesignations)
            {
                var moddedPlanDesignation = planDesignation as PlanDesignation;

                var planInfo = new PlanInfo
                {
                    Color = moddedPlanDesignation != null ? moddedPlanDesignation.Color : 0,
                    Pos   = new IntVec3(planDesignation.target.Cell.x - sizeCompX, planDesignation.target.Cell.y, planDesignation.target.Cell.z - sizeCompZ)
                };
                planDesignationInfo.Add(planInfo);
            }

            var planCopy = new PlanInfoSet(planDesignationInfo);

            PasteDesignator.CurrentPlanCopy = planCopy;
            Finalize(true);

            var designatorPlanPaste = MenuUtility.GetPlanningDesignator <PasteDesignator>();

            Find.DesignatorManager.Select(designatorPlanPaste);
        }
Beispiel #50
0
 protected override MatchingScore selectScoreInternally(IEnumerable <MatchingScore> scores)
 {
     return(scores.Min());
 }
        public ActionResult History(int year = 0, bool displayMonth = false)
        {
            year = (year == 0) ? DateTime.Now.Year : year;

            DashboardViewModel viewModel = new DashboardViewModel();

            viewModel.CurrentYear  = year;
            viewModel.DisplayMonth = displayMonth;

            IEnumerable <BillPayment>   billPayments   = db.BillPayments.Where(x => x.User.Id == user.Id || x.SharedWith.Where(y => y.SharedWithUser.Id == user.Id).Any()).Include(x => x.Bill).Include(x => x.User).Include(x => x.SharedWith.Select(y => y.SharedWithUser)).OrderBy(x => x.DatePaid);
            IEnumerable <LoanPayment>   loanPayments   = db.LoanPayments.Where(x => x.User.Id == user.Id || x.SharedWith.Where(y => y.SharedWithUser.Id == user.Id).Any()).Include(x => x.Loan).Include(x => x.User).Include(x => x.SharedWith.Select(y => y.SharedWithUser)).OrderBy(x => x.DatePaid);
            IEnumerable <IncomePayment> incomePayments = db.IncomePayments.Where(x => x.User.Id == user.Id).Include(x => x.Income).Include(x => x.User).OrderBy(x => x.Date);

            int maxYear = 0;
            int minYear = DateTime.Now.Year;

            if (billPayments.Any())
            {
                int maxYearBill = billPayments.Max(x => x.DatePaid).Year;
                int minYearBill = billPayments.Min(x => x.DatePaid).Year;
                maxYear = (maxYearBill > maxYear) ? maxYearBill : maxYear;
                minYear = (minYearBill < minYear) ? minYearBill : minYear;
            }
            if (loanPayments.Any())
            {
                int maxYearLoan = loanPayments.Max(x => x.DatePaid).Year;
                int minYearLoan = loanPayments.Min(x => x.DatePaid).Year;
                maxYear = (maxYearLoan > maxYear) ? maxYearLoan : maxYear;
                minYear = (minYearLoan < minYear) ? minYearLoan : minYear;
            }
            if (incomePayments.Any())
            {
                int maxYearIncome = incomePayments.Max(x => x.Date).Year;
                int minYearIncome = incomePayments.Min(x => x.Date).Year;
                maxYear = (maxYearIncome > maxYear) ? maxYearIncome : maxYear;
                minYear = (minYearIncome < minYear) ? minYearIncome : minYear;
            }

            viewModel.StartYear = minYear;
            viewModel.EndYear   = maxYear;

            IEnumerable <BillPayment>   yearBillPayments   = billPayments.Where(x => x.DatePaid.Year == year);
            IEnumerable <LoanPayment>   yearLoanPayments   = loanPayments.Where(x => x.DatePaid.Year == year);
            IEnumerable <IncomePayment> yearIncomePayments = incomePayments.Where(x => x.Date.Year == year);

            if (yearBillPayments.Any() || yearLoanPayments.Any() || yearIncomePayments.Any())
            {
                DateTime startDate = DateTime.Now;
                if (yearBillPayments.Any())
                {
                    DateTime billStartDate = yearBillPayments.Min(x => x.DatePaid);
                    startDate = (billStartDate < startDate) ? billStartDate : startDate;
                }
                if (yearLoanPayments.Any())
                {
                    DateTime loanStartDate = yearLoanPayments.Min(x => x.DatePaid);
                    startDate = (loanStartDate < startDate) ? loanStartDate : startDate;
                }
                if (yearIncomePayments.Any())
                {
                    DateTime incomeStartDate = yearIncomePayments.Min(x => x.Date);
                    startDate = (incomeStartDate < startDate) ? incomeStartDate : startDate;
                }

                startDate            = GetUserStartDate(startDate, viewModel.DisplayMonth);
                viewModel.DateRanges = InitiateDateRanges(startDate, viewModel.DisplayMonth, true);
                viewModel.DateRanges = (user.PrimaryIncome.PaymentFrequency == PaymentFrequency.SemiMonthly) ? viewModel.DateRanges.OrderByDescending(x => x.StartDate.Month) : viewModel.DateRanges.OrderByDescending(x => x.StartDate);

                foreach (DashboardDateRange range in viewModel.DateRanges)
                {
                    List <DashboardItem> items = new List <DashboardItem>();
                    items.AddRange(yearBillPayments.Where(x => x.DatePaid >= range.StartDate && x.DatePaid <= range.EndDate).Select(x => new DashboardItem(x, user)));
                    items.AddRange(yearLoanPayments.Where(x => x.DatePaid >= range.StartDate && x.DatePaid <= range.EndDate).Select(x => new DashboardItem(x, user)));
                    range.Items = items.OrderBy(x => x.Date);

                    List <DashboardIncomeItem> incomeItems = new List <DashboardIncomeItem>();
                    incomeItems.AddRange(yearIncomePayments.Where(x => x.Date >= range.StartDate && x.Date <= range.EndDate).Select(x => new DashboardIncomeItem(x)));
                    range.IncomeItems = incomeItems.OrderBy(x => x.Date).ToList();
                }
                viewModel.DateRanges = viewModel.DateRanges.Where(x => x.Items.Any() || x.IncomeItems.Any());
            }

            return(View(viewModel));
        }
        public double MinimumAtRange(double leftX, double rightX)
        {
            IEnumerable <DataPoint> elements = curve.Points.Where((DataPoint x) => x.XValue >= leftX && x.XValue <= rightX);

            return(elements.Count() == 0 ? MaximumY : elements.Min((DataPoint p) => { return p.YValues.Min(); }));
        }
Beispiel #53
0
        private static string TrackTimeQueryMin(IEnumerable <ITrack> tracks)
        {
            var track = tracks.Min();

            return(track.Name + "\t\t" + track.Milliseconds + "/ 1000");
        }
Beispiel #54
0
 /// <summary>
 /// Returns the racer's best lap.
 /// </summary>
 /// <param name="race"></param>
 /// <returns></returns>
 public Lap GetBestLap(Race race)
 {
     Laps = race.Laps.Where(x => x.Racer.RacerId == RacerId);
     return(Laps.FirstOrDefault(x => x.LapTime == Laps.Min(y => y.LapTime)));
 }
Beispiel #55
0
 public static Date Start(this IEnumerable <DateRange> source)
 {
     return(source.Min(period => period.Start));
 }
Beispiel #56
0
 float BoundaryRight(IEnumerable <TextLine> lineset)
 {
     return(lineset.Min(t => t.MarginRight));
 }
Beispiel #57
0
 public static UInt16[] IEnumerableToIndexArray(IEnumerable<double> data, int width, int height, int nIndices)
 {
     double max = data.Max();
     double min = data.Min();
     double Scale = (nIndices - 1) / (max - min);
     int count = width * height;
     int index = 0;
     UInt16[] indices = new UInt16[count];
     foreach (double value in data)
     {
         indices[index] = (UInt16)((value - min) * Scale);
         index++;
     }
     return indices;
 }
Beispiel #58
0
        } // CreateBody()

        #endregion

        #region CalcSize
        private Vector2 _calcSize(IEnumerable <Vector2> vert)
        {
            return(new Vector2(vert.Max(v => v.X) - vert.Min(v => v.X),
                               vert.Max(v => v.Y) - vert.Min(v => v.Y)));
        } // _calcSize(vertices)
        private EngineSettings GetBaseSettings(IEnumerable <EngineSettings> settings)
        {
            var minPrice = settings.Min(cur => cur.Price);

            return(settings.FirstOrDefault(cur => cur.Price == minPrice));
        }
Beispiel #60
0
        private static long GetDuration(IEnumerable <Span> spans)
        {
            var timeSpan = spans.Max(x => x.FinishTimestamp) - spans.Min(x => x.StartTimestamp);

            return(timeSpan.GetMicroseconds());
        }