Example #1
1
        public void SetMinMax(IList<Point> points)
        {
            if (_isMaxMinSet)
            {
                var minX = points.Min(point => point.X);
                MinX = minX < MinX ? minX : MinX;

                var maxX = points.Max(point => point.X);
                MaxX = maxX > MaxX ? maxX : MaxX;

                var minY = points.Min(point => point.Y);
                MinY = minY < MinY ? minY : MinY;

                var maxY = points.Max(point => point.Y);
                MaxY = maxY > MaxY ? maxY : MaxY;
            }
            else
            {
                MinX = points.Min(point => point.X);
                MaxX = points.Max(point => point.X);
                MinY = points.Min(point => point.Y);
                MaxY = points.Max(point => point.Y);
                _isMaxMinSet = true;
            }
            SetOriginPoint(GetDelta());
        }
        /// <summary>
        /// I feel like this way is a little bit more optimized since it saves space
        /// there is still the possibility of empty space beetwen min,max 
        /// but atleast it gets rid of the space from 0 to min
        /// 
        /// This will also work with negative numbers.
        /// </summary>
        public static int[] Sort(IList<int> data, int min, int max)
        {
            Contract.Ensures(data != null, "data cannot be a null pointer");
            Contract.Ensures(min == data.Min(), "wrong min submitted");
            Contract.Ensures(max == data.Max(), "wrong max submitted");

            int[] count = new int[(max - min) + 1];
            int[] sorted = new int[data.Count];

            // Add the elements in reverse order big --> small
            // NOTE: Could do key - min instead for order small --> big
            foreach (int key in data)
            {
                count[max - key] += 1;
            }

            // Transfer the temp array to the sorted array from small --> big
            int sortedIndex = data.Count - 1;
            for (int i = 0; i < count.Length; i++)
            {
                // How often did we have this number in the input?
                int number = max - i;
                for (int j = 0; j < count[i]; j++)
                {
                    sorted[sortedIndex--] = number;
                }
            }

            return sorted;
        }
Example #3
1
        private static int ResolveNormal(IList<int> pancakes)
        {
            int maxvalue = pancakes.Max();
            int minvalue = pancakes.Min();

            if (minvalue == maxvalue)
                return maxvalue;

            int secondmaxvalue = pancakes.Where(n => n != maxvalue).Max();

            IList<int> newpancakes = new List<int>();
            int steps = maxvalue - secondmaxvalue;

            foreach (int value in pancakes)
            {
                if (value == maxvalue)
                    newpancakes.Add(secondmaxvalue);
                else if (value > steps)
                    newpancakes.Add(value - steps);
            }

            if (newpancakes.Count == 0)
                return 1;

            return Resolve(newpancakes) + steps;
        }
Example #4
1
        /// <summary>
        /// Convert numbers to spark chart strings.
        /// </summary>
        /// <param name="data">List or Array of numbers</param>
        /// <returns>empty string if <paramref name="data"/>is <code>null</code> or empty.</returns>
        public static String Render(IList<double> data)
        {
            var ticks = TickProvider.Ticks;

            if (data == null || data.Count == 0)
                return string.Empty;

            char[] res = new char[data.Count()];

            double min = data.Min();
            double max = data.Max();
            double step = (max - min) / (ticks.Length - 1);
            if (step.Equals(0d)) step = 1;

            for (var i = 0; i < data.Count(); i++)
            {
                var val = data[i];
                double d = (val - min)/step;

                // if it's 10^-10 close to its rounded, round; floor otherwise
                int tick = (int) ((Math.Abs(Math.Round(d) - d) < 1e-10) ? Math.Round(d) : Math.Floor((val - min) / step));
                res[i] = ticks[tick];
            }
            return new string(res);
        }
Example #5
1
        /// <summary>
        /// Generates intervals based on type, numberOfClasses and values.
        /// </summary>
        /// <param name="values"></param>
        /// <param name="type"></param>
        /// <param name="numberOfClasses"></param>
        /// <returns></returns>
        public static IList<Interval> GetIntervalsForNumberOfClasses(IList<Single> values, QuantityThemeIntervalType type, int numberOfClasses)
        {
            int index = 0;
            var intervals = new List<Interval>();
            var lowValue = values.Min();
            var highValue = values.Max();
            if (type == QuantityThemeIntervalType.NaturalBreaks)
            {
                ArrayList.Adapter((IList)values).Sort(); // performance, works 20% faster than layerAttribute.AttributeValues.Sort();
            }

            for (int i = 0; i < numberOfClasses; i++)
            {
                float intervalMin;
                float intervalMax;

                if (type == QuantityThemeIntervalType.EqualIntervals)
                {

                    intervalMin = lowValue + i * ((highValue - lowValue) / numberOfClasses);
                    intervalMax = lowValue + (i + 1) * ((highValue - lowValue) / numberOfClasses);
                }
                else
                {
                    intervalMin = Convert.ToSingle(values[index]);
                    index = (int)Math.Ceiling((double)(i + 1) / numberOfClasses * (values.Count - 1));
                    intervalMax = Convert.ToSingle(values[index]);
                }

                var interval = new Interval(intervalMin, intervalMax);
                intervals.Add(interval);
            }

            return intervals;
        }
Example #6
1
        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 List<Point> ConvexHull(IList<Point> points)
        {
            if (points.Count < 3)
            {
                throw new ArgumentException("At least 3 points reqired", "points");
            }

            List<Point> hull = new List<Point>();

            // get leftmost point
            Point vPointOnHull = points.Where(p => p.X == points.Min(min => min.X)).First();

            Point vEndpoint;
            do
            {
                hull.Add(vPointOnHull);
                vEndpoint = points[0];

                for (int i = 1; i < points.Count; i++)
                {
                    if ((vPointOnHull.IsTheSame(vEndpoint)) || (Orientation(vPointOnHull, vEndpoint, points[i]) == -1))
                    {
                        vEndpoint = points[i];
                    }
                }

                vPointOnHull = vEndpoint;

            }
            while (!vEndpoint.IsTheSame(hull[0]));

            return hull;
        }
Example #8
1
        public int CalculateDeceitfulWar(IList<double> first, IList<double> second)
        {
            if (first.Count == 0)
                return 0;

            double min1 = first.Min();
            double min2 = second.Min();
            bool win = false;

            double play1;
            double play2;

            if (min1 < min2)
            {
                play1 = min1;
                play2 = second.Max();
            }
            else
            {
                play1 = min1;
                play2 = min2;
                win = true;
            }

            var newfirst = first.Where(n => n != play1).ToList();
            var newsecond = second.Where(n => n != play2).ToList();

            return CalculateDeceitfulWar(newfirst, newsecond) + (win ? 1 : 0);
        }
Example #9
1
        public SeasonWeek AddWeekToSeason(int seasonId, IList<RealWorldFixture> fixtures)
        {
            var season = LoadSeason(seasonId);

            var currentFinalWeek = season.Weeks.Any() ? season.Weeks.Max(w => w.WeekNumber) : 0;

            if (currentFinalWeek == season.NumberOfWeeks)
                throw new InvalidOperationException("Season has full complement of weeks already");

            var predsCutoffDate = fixtures.Min(f => f.KickOff).AddHours(-1);

            var addedWeek = new SeasonWeek
            {
                WeekNumber = currentFinalWeek + 1,
                RealWorldFixtures = fixtures,
                PredsCutOffDate = predsCutoffDate,
                Season = season,
            };

            foreach (var fixture in fixtures)
            {
                fixture.SeasonWeek = addedWeek;
            }

            season.Weeks.Add(addedWeek);
            _seasonRepository.Save(season);

            return addedWeek;
        }
        public override void Draw(
			IList<Point> points,
			double thickness,
			int miterLimit,
			ILogicalToScreenMapper logicalToScreenMapper)
        {
            var pointsCount = points.Count;
            var firstPoint = points[0];
            var lastPoint = points[pointsCount - 1];
            var highestValue = _useHighest ? points.Max(it => it.Y) : 0;
            var lowestValue = _useLowest ? points.Min(it => it.Y) : 0;
            double baselineValue;

            // Auf gleiche Höhe bringen
            if (_useBaseline)
                baselineValue = logicalToScreenMapper.MapY(_baselineValue);
            else if (_useHighest)
                baselineValue = highestValue;
            else if (_useLowest)
                baselineValue = lowestValue;
            else
            {
                baselineValue = firstPoint.Y > lastPoint.Y
                    ? lastPoint.Y
                    : firstPoint.Y;
            }

            using (var dc = RenderOpen())
            {
                for (var i = 1; i < points.Count; i++)
                {
                    var previousPoint = points[i - 1];
                    var currentPoint = points[i];
                    var previousY = previousPoint.Y;
                    // -1 weil: 1 Pixel nach links verschieben bewirkt, dass die Löcher zwischen den Rechtecken nicht mehr auftauchen
                    // nicht mehr nach 1 verschieben, weil der Fall bei Kriko (kleine Löcher in den Kurven) sowieso nicht vorkommt
                    // var previousX = previousPoint.X - 1;
                    var previousX = previousPoint.X;
                    // Rect kann mit negativen Höhen nicht umgehen, deshalb die komischen Expressions
                    var height = previousY > baselineValue ? previousY - baselineValue : baselineValue - previousY;
                    var y = previousY > baselineValue ? baselineValue : previousY;
                    var rectangle = new Rect(
                        previousX,
                        height == 0 ? y - 1 : y, // Linie um 1 nach oben verschieben, damit die Linien nicht optisch nach unten versetzt sind
                        currentPoint.X - previousX,
                        height == 0d ? 1 : height);
                    dc.DrawRectangle(
                        Brushes.White,
                        new Pen(
                            Brushes.White,
                            0)
                        // brauchen wir nicht mehr (siehe oben - height == 0): thickness == 1 ? 0.25 : thickness)
                        {
                            MiterLimit = miterLimit
                        },
                        rectangle);
                }
            }
        }
 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.Min,input.Min());
 }
Example #12
1
        private static Department FindDepartmentWithMinSortOrder(IList<Department> departments)
        {
            int firstSortOrder = departments.Min(d => d.SortOrder);

            return (from d in departments
                    where d.SortOrder == firstSortOrder
                    select d).First();
        }
 public AggregationOperationResult Do(IList<UniversalValue> input)
 {
     if (input == null)
         throw new ArgumentNullException("input");
     AggregationOperationResult result = new AggregationOperationResult();
     result.Add("min", input.Min());
     return result;
 }
Example #14
1
 private int GetTheta(int current, IList<int> sortedCardinalities)
 {
     var result = sortedCardinalities.Count(i => i >= current);
     if (current != sortedCardinalities.Min())
     {
         result = result + 1;
     }
     return result;
 }
Example #15
1
 public IList<WordIntPair> GetFontSizes(IList<WordIntPair> wordsAndFreqs, InputOptions options)
 {
     int minCount = wordsAndFreqs.Min(t => t.Number);
     int maxCount = wordsAndFreqs.Max(t => t.Number);
     return wordsAndFreqs.Select(tuple => new WordIntPair(
         tuple.Word,
         CountFont(tuple.Number, options.MaxFont, options.MinFont, minCount, maxCount)))
         .ToList();
 }
        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);
            }
        }
Example #17
0
        public CarCalculatorSummary(IList<FuelEntryModel> fuelEntries)
        {
            HasData = fuelEntries != null && fuelEntries.Any();
            if (!HasData) return;

            MinAmountOf100Km = fuelEntries.Min(i => i.AmountOfFuelPer100Km);
            MaxAmountOf100Km = fuelEntries.Max(i => i.AmountOfFuelPer100Km);

            MinCost1Km = fuelEntries.Min(i => i.CostOf1Km);
            MaxCost1Km = fuelEntries.Max(i => i.CostOf1Km);

            SumDistance = fuelEntries.Sum(i => i.CurrentDistance);
            SumAmountOfFuel = fuelEntries.Sum(i => i.AmountOfFuel);
            SumTotalCost = fuelEntries.Sum(i => i.GasPrice * i.AmountOfFuel);

            var minDate = fuelEntries.Min(i => i.Date);
            var maxDate = fuelEntries.Max(i => i.Date);
            AverageFuel = (decimal)((maxDate - minDate).TotalDays/fuelEntries.Count);
        }
Example #18
0
        private static void CalculatePickList(IList<Product> allProducts,
            int columnSize, bool[,] pickList)
        {
            var valueList = new int[columnSize];
            var minVolumeIdx = allProducts.Min(x => x.Dimension.Volume) - 1;

            for (var idx = 0; idx < allProducts.Count; idx++)
            {
                var product = allProducts[idx];
                var tempValueList = new int[columnSize];

                for (var volIdx = minVolumeIdx; volIdx < columnSize; volIdx++)
                {
                    var chosenVal = 0;
                    var keep = false;

                    var isWithin = product.Dimension.Volume <= volIdx;

                    var valueOfCellAbove = valueList[volIdx];

                    if (isWithin)
                    {
                        var remainingSpace = volIdx - product.Dimension.Volume;
                        var otherPossibleVal = valueList[remainingSpace];

                        var finalPossibleVal = product.Price + otherPossibleVal;

                        if (valueOfCellAbove <= finalPossibleVal)
                        {
                            chosenVal = finalPossibleVal;
                            keep = true;
                        }
                        else
                        {
                            chosenVal = valueOfCellAbove;
                            keep = false;
                        }
                    }
                    else
                    {
                        chosenVal = valueOfCellAbove;
                        keep = false;
                    }

                    pickList[idx, volIdx] = keep;
                    tempValueList[volIdx] = chosenVal;
                }

                for (var i = 0; i < columnSize; i++)
                {
                    valueList[i] = tempValueList[i];
                }
            }
        }
Example #19
0
		private void ExecuteIndexingInternal(IList<IndexToWorkOn> indexesToWorkOn, Action<IEnumerable<Tuple<IndexToWorkOn, IEnumerable<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)
				{
					var result = FilterIndexes(indexesToWorkOn, jsonDocs).ToList();
					indexesToWorkOn = result.Select(x => x.Item1).ToList();
					indexingOp(result);
				}
			}
			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)
						{
							MarkIndexes(indexToWorkOn, lastIndexedEtag, actions, lastEtag, lastModified);
						}
					});
				}
			}
		}
 public LineData(IList<double> x, IList<double> y)
 {
     m_x = x;
     m_y = y;
     Count = x.Count;
     if (x.Count > 0)
     {
         MaxValueX = x.Max();
         MinValueX = x.Min();
     }
     if (y.Count > 0)
     {
         MaxValueY = y.Max();
         MinValueY = y.Min();
     }
 }
 public static IList<Team> CalcSmallestDiff(IList<Team> teams)
 {
     // use LinQ to find the minimum difference
     var smallest = teams.Min(team => team.Diff);
     // Need to cater for multiple teams having the minimum diff
     var smallestTeams = new List<Team>();
     foreach (var team in teams)
     {
         if (team.Diff == smallest)
         {
             smallestTeams.Add(team);
             team.SmallestDiff = true;
         }
     }
     return smallestTeams;
 }
Example #22
0
        private int MinimalMoves(IList<Group> groups)
        {
            int result = Int32.MaxValue;

            int minlength = groups.Min(gr => gr.Count);
            int maxlength = groups.Max(gr => gr.Count);

            for (int k = minlength; k <= maxlength; k++)
            {
                int moves = DistanceTo(groups, k);
                if (moves < result)
                    result = moves;
            }

            return result;
        }
Example #23
0
		protected override void ExecuteIndexingWork(IList<IndexToWorkOn> indexesToWorkOn)
		{
			indexesToWorkOn = context.Configuration.IndexingScheduler.FilterMapIndexes(indexesToWorkOn);

			var lastIndexedGuidForAllIndexes = indexesToWorkOn.Min(x => new ComparableByteArray(x.LastIndexedEtag.ToByteArray())).ToGuid();

			context.CancellationToken.ThrowIfCancellationRequested();

			var operationCancelled = false;
			TimeSpan indexingDuration = TimeSpan.Zero;
			List<JsonDocument> jsonDocs = null;
			var lastEtag = Guid.Empty;
			try
			{
				jsonDocs = prefetchingBehavior.GetDocumentsBatchFrom(lastIndexedGuidForAllIndexes);

				if (Log.IsDebugEnabled)
				{
					Log.Debug("Found a total of {0} documents that requires indexing since etag: {1}: ({2})",
							  jsonDocs.Count, lastIndexedGuidForAllIndexes, string.Join(", ", jsonDocs.Select(x => x.Key)));
				}

				context.ReportIndexingActualBatchSize(jsonDocs.Count);
				context.CancellationToken.ThrowIfCancellationRequested();

				if (jsonDocs.Count <= 0)
					return;

				var sw = Stopwatch.StartNew();
				lastEtag = DoActualIndexing(indexesToWorkOn, jsonDocs);
				indexingDuration = sw.Elapsed;
			}
			catch (OperationCanceledException)
			{
				operationCancelled = true;
			}
			finally
			{
				if (operationCancelled == false && jsonDocs != null && jsonDocs.Count > 0)
				{
					prefetchingBehavior.CleanupDocumentsToRemove(lastEtag);
					UpdateAutoThrottler(jsonDocs, indexingDuration);
				}

				prefetchingBehavior.BatchProcessingComplete();
			}
		}
 private ReportsViewModel BuildReportsModel(IList<UserReport> reports, int pageSize = int.MaxValue)
 {
     var model = new ReportsViewModel
     {
         Reports = reports
     };
     if (reports.Any())
     {
         model.FirstDate = (DateTime?)reports.Max(r => r.CreationDate);
         model.LastDate = (DateTime?)reports.Min(r => r.CreationDate);
     }
     foreach (var report in reports)
     {
         InitUserReport(report);
     }
     return model;
 }
Example #25
0
        //public static void CleanTitles(this Chart chart)
        //{
        //    foreach (var series in chart.Data.Series)
        //    {
        //        series.Name = RemovePrefixes(series.Name);
        //        foreach (var value in series.Values)
        //        {
        //            value.Label = RemovePrefixes(value.Label);
        //        }
        //    }
        //}
        public static IList<int> ParseYears(string yearsConfig, IList<int> yearsFromDb)
        {
            var result = new List<int>();
            var max = yearsFromDb.Max();
            var min = yearsFromDb.Min();
            var periods = yearsConfig.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
            foreach (var period in periods)
            {
                int val;
                // if value
                if (Int32.TryParse(period, out val) && yearsFromDb.Contains(val))
                {
                    result.Add(val);
                }
                else
                {
                    // if actual period
                    if (period.Contains("-"))
                    {
                        var bounds = period.Split(new[] {'-'}, StringSplitOptions.RemoveEmptyEntries);
                        if (bounds.Length != 2)
                        {
                            throw new ApplicationException("Incorrect period " + period);
                        }
                        var start = ParseYearConstant(bounds[0], min, max, yearsFromDb);
                        var end = ParseYearConstant(bounds[1], min, max, yearsFromDb);

                        for (var i = start; i <= end; i++)
                        {
                            result.Add(i);
                        }
                    }
                    // if year constant
                    else
                    {
                        result.Add(ParseYearConstant(period, min, max, yearsFromDb));
                    }
                }
            }

            return result;
        }
        private void ReadWellPoints()
        {
            _points = DataReader.ReadWells(@"Draw\B2-HO.txt");
            _xMin = _points.Min(p => p.X);
            _xMax = _points.Max(p => p.X);
            _yMin = _points.Min(p => p.Y);
            _yMax = _points.Max(p => p.Y);

            foreach (var point in _points)
            {
                var ellipse = new Ellipse();
                ellipse.Width = 10;
                ellipse.Height = 10;
                ellipse.Stroke = new SolidColorBrush(Colors.Black);
                drawCanvas.Children.Add(ellipse);

                _drawObjects.Add(point, new DrawObject()
                    {
                        Shape = ellipse
                    });
            }
        }
Example #27
0
        public int CalculateWar(IList<double> first, IList<double> second)
        {
            if (first.Count == 0)
                return 0;

            double play1 = first.Max();
            double play2;
            bool win = false;

            var greater = second.Where(n => n > play1).ToList();

            if (greater.Count > 0)
                play2 = greater.Min();
            else
            {
                play2 = second.Min();
                win = true;
            }

            var newfirst = first.Where(n => n != play1).ToList();
            var newsecond = second.Where(n => n != play2).ToList();

            return CalculateWar(newfirst, newsecond) + (win ? 1 : 0);
        }
Example #28
0
        private BinaryGeneration CreateNextGeneration(BinaryGeneration generation, IList<BinaryEntity> children)
        {
            if (children.Any())
            {
                var bestChild = children.First(x => Math.Abs(x.Value - children.Min(c => c.Value)) < 0.01);
                bestChild.Function = EntityFunction.BestChild;
                var nextGeneration = new List<Entity<BinaryGenom>>(generation.Winners());
                nextGeneration.Add(bestChild);
                return new BinaryGeneration(nextGeneration
                    .OfType<BinaryEntity>()
                    .Select(x => new BinaryEntity(x))
                    .OfType<Entity<BinaryGenom>>()
                    .ToList())
                    .MarkUpGenereation();
            }

            return generation;
        }
 private bool StraightInHand(IList<Card> cards)
 {
     // theres probably a better way to do this whole thing with linq... but I can't figure it out.
     int maxSequenceLength = 1;
     CardFigure minCard = cards.Min<Card, CardFigure>(key => key.Figure);
     CardFigure maxCard = cards.Max<Card, CardFigure>(key => key.Figure);
     CardFigure lastCard = minCard;
     int totalCardFigures = 0;
     // go through the cards except the lowest card - we've already handled it in variable assignment
     foreach (Card card in cards.OrderBy<Card, CardFigure>(key => key.Figure).Skip<Card>(1))
     {
         // if this card is one higher than the last one was
         maxSequenceLength += ((lastCard + 1) == card.Figure) ? 1 : 0;
         lastCard = card.Figure;
         // theres got to be a better way then summing all cards A,2,3,4,5 == 22
         totalCardFigures += (int)card.Figure;
     }
     // Either you have to have 5 cards in a row
     // or it is also valid to have 4 cards in a row, if your min card is a two and your max card is an ace
     // this handles the problematic ace wraparound where an ace can be at either end of a straight
     return (maxSequenceLength >= 5) ||
           ((maxSequenceLength == 4) && (maxCard == CardFigure.Ace) && (totalCardFigures == 22)); // A,2,3,4,5 == 22
 }
Example #30
0
    private void ListTable(IList<ProductionPlanDet> productionPlanDetList)
    {
        if (productionPlanDetList == null || productionPlanDetList.Count == 0)
        {
            this.list.InnerHtml = "没有查到符合条件的记录";
            return;
        }

        var minStartTime = productionPlanDetList.Min(s => s.StartTime).AddDays(13);
        productionPlanDetList = productionPlanDetList.Where(s => s.StartTime <= minStartTime).ToList();

        #region   trace
        List<ProductionPlanDetTrace> traceList = new List<ProductionPlanDetTrace>();
        int len = 0;
        int j = productionPlanDetList.Count % 2000 == 0 ? productionPlanDetList.Count / 2000 : productionPlanDetList.Count / 2000 + 1;
        while (true)
        {
            var cList = this.TheGenericMgr.FindAllWithCustomQuery<ProductionPlanDetTrace>(string.Format(" select l from ProductionPlanDetTrace as l where l.Type='{0}' and  l.UUID in ('{1}') ", this.rbType.SelectedValue, string.Join("','", productionPlanDetList.Skip(len * 2000).Take((len + 1) * 2000).Select(d => d.UUID).Distinct().ToArray())));
            if (cList != null && cList.Count > 0) { traceList.AddRange(cList); }
            len++;
            if (len == j) break;
        }
        traceList = traceList == null ? new List<ProductionPlanDetTrace>() : traceList;
        if (traceList != null && traceList.Count > 0)
        {
            foreach (var sd in productionPlanDetList)
            {
                var currentLogs = traceList.Where(d => d.UUID == sd.UUID).OrderBy(d => d.ReqDate).ToList();
                var showText = string.Empty;
                if (currentLogs != null && currentLogs.Count > 0)
                {
                    showText = "<table><thead><tr><th>发运路线</th><th>物料</th><th>Bom</th><th>需求日期</th><th>需求数</th></tr></thead><tbody><tr>";
                    foreach (var c in currentLogs)
                    {
                        showText += "<td>" + c.Flow + "</td><td>" + c.Item + "</td><td>" + c.Bom + "</td><td>" + c.ReqDate.ToShortDateString() + "</td><td>" + c.ReqQty.ToString("0.##") + "</td></tr><tr>";
                    }
                    showText += " </tr></tbody></table> ";
                }
                sd.Logs = showText;
            }
        }
        #endregion

        #region  orderQty
        List<ProductionPlanOpenOrder> productionPlanOpenOrderList = new List<ProductionPlanOpenOrder>();
        len = 0;
        while (true)
        {
            var cList = this.TheGenericMgr.FindAllWithCustomQuery<ProductionPlanOpenOrder>(string.Format(" select l from ProductionPlanOpenOrder as l where l.Type='{0}' and  l.UUID in ('{1}') ", this.rbType.SelectedValue, string.Join("','", productionPlanDetList.Skip(len * 2000).Take((len + 1) * 2000).Select(d => d.UUID).Distinct().ToArray())));
            if (cList != null && cList.Count > 0) { productionPlanOpenOrderList.AddRange(cList); }
            len++;
            if (len == j) break;
        }
        // productionPlanOpenOrderList = this.TheGenericMgr.FindAllWithCustomQuery<ProductionPlanOpenOrder>(string.Format(" select l from ProductionPlanOpenOrder as l where l.Type='{0}' and l.UUID in ('{1}') ", this.rbType.SelectedValue, string.Join("','", productionPlanDetList.Select(d => d.UUID).Distinct().ToArray())));
        productionPlanOpenOrderList = productionPlanOpenOrderList == null ? new List<ProductionPlanOpenOrder>() : productionPlanOpenOrderList;
        if (productionPlanOpenOrderList != null && productionPlanOpenOrderList.Count > 0)
        {
            foreach (var sd in productionPlanDetList)
            {
                var currentOrders = productionPlanOpenOrderList.Where(d => d.UUID == sd.UUID).OrderBy(d=>d.WindowTime).ToList();
                var showText = string.Empty;
                if (currentOrders != null && currentOrders.Count > 0)
                {
                    showText = "<table><thead><tr><th>路线</th><th>订单号</th><th>物料</th><th>订单数</th><th>收货数</th><th>开始时间</th><th>窗口时间</th></tr></thead><tbody><tr>";
                    foreach (var c in currentOrders)
                    {
                        showText += "<td>" + c.Flow + "</td><td>" + c.OrderNo + "</td><td>" + c.Item + "</td><td>" + c.OrderQty.ToString("0.##") + "</td><td>" + c.RecQty.ToString("0.##") + "</td><td>" + c.StartTime.ToShortDateString() + "</td><td>" + c.WindowTime.ToShortDateString() + "</td></tr><tr>";
                    }
                    showText += " </tr></tbody></table> ";
                }
                sd.OrderDets = showText;
            }
        }
        #endregion

        var planByDateIndexs = productionPlanDetList.GroupBy(p => p.StartTime).OrderBy(p => p.Key);
        var planByItems = productionPlanDetList.GroupBy(p => p.Item);

        StringBuilder str = new StringBuilder();
        //str.Append(CopyString());
        //head
        string headStr = string.Empty;
        str.Append("<thead><tr class='GVHeader'><th rowspan='2'>序号</th><th rowspan='2'>物料号</th><th rowspan='2'>物料描述</th><th rowspan='2'>客户零件号</th><th rowspan='2'>包装量</th><th rowspan='2'>经济批量</th><th rowspan='2'>安全库存</th><th rowspan='2'>最大库存</th><th rowspan='2'>期初库存</th><th rowspan='2'>报验</th><th rowspan='2'>库存倒数</th>");
        int ii = 0;
        foreach (var planByDateIndex in planByDateIndexs)
        {
            ii++;
            str.Append("<th colspan='4'>");
            //if (productionPlanDetList.First().Status == BusinessConstants.CODE_MASTER_STATUS_VALUE_SUBMIT && planByDateIndex.Key.Date == System.DateTime.Now.Date)
            //{
            //    str.Append("<input type='checkbox' id='CheckAll' name='CheckAll'  onclick='doCheckAllClick()' />");
            //}
            str.Append(planByDateIndex.Key.ToString("yyyy-MM-dd"));
            str.Append("</th>");
        }
        str.Append("</tr><tr class='GVHeader'>");
        foreach (var planByDateIndex in planByDateIndexs)
        {
            str.Append("<th >需求</th><th >订单数</th><th >计划数</th><th >期末</th>");
        }
        str.Append("</tr></thead>");
        str.Append("<tbody>");

        #region  通过长度控制table的宽度
        string widths = "100%";
        if (ii > 14)
        {
            widths = "260%";
        }
        else if (ii > 10)
        {
            widths = "210%";
        }
        else if (ii > 6)
        {
            widths = "160%";
        }
        else if (ii > 4)
        {
            widths = "120%";
        }

        headStr += string.Format("<table id='tt' runat='server' border='1' class='GV' style='width:{0};border-collapse:collapse;'>", widths);
        #endregion
        int l = 0;
        int seq = 0;
        foreach (var planByItem in planByItems)
        {
            var firstPlan = planByItem.First();
            var planDic = planByItem.GroupBy(d => d.StartTime).ToDictionary(d => d.Key, d => d.Sum(q => q.Qty));
            l++;
            if (l % 2 == 0)
            {
                str.Append("<tr class='GVAlternatingRow'>");
            }
            else
            {
                str.Append("<tr class='GVRow'>");
            }
            str.Append("<td>");
            str.Append(l);
            str.Append("</td>");
            str.Append("<td>");
            str.Append(planByItem.Key);
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.ItemDesc);
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.RefItemCode);
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.UnitCount.ToString("0.##"));
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.MinLotSize.ToString("0.##"));
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.SafeStock.ToString("0.##"));
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.MaxStock.ToString("0.##"));
            str.Append("</td>");
            var InitStockQty = firstPlan.InitStock + firstPlan.InspectQty;
            if (InitStockQty < firstPlan.SafeStock)
            {
                str.Append("<td style='background:red;color:white'>");
            }
            else if (InitStockQty >= firstPlan.SafeStock && InitStockQty <= firstPlan.MaxStock)
            {
                str.Append("<td style='background:green;color:white'>");
            }
            else if (InitStockQty > firstPlan.MaxStock)
            {
                str.Append("<td style='background:orange'>");
            }
            str.Append((firstPlan.InitStock).ToString("0.##"));
            str.Append("</td>");
            //str.Append("<td>");
            //str.Append((firstPlan.InTransitQty).ToString("0.##"));
            //str.Append("</td>");
            if (InitStockQty < firstPlan.SafeStock)
            {
                str.Append("<td style='background:red;color:white'>");
            }
            else if (InitStockQty >= firstPlan.SafeStock && InitStockQty <= firstPlan.MaxStock)
            {
                str.Append("<td style='background:green;color:white'>");
            }
            else if (InitStockQty > firstPlan.MaxStock)
            {
                str.Append("<td style='background:orange'>");
            }
            str.Append((firstPlan.InspectQty).ToString("0.##"));
            str.Append("</td>");
            str.Append("<td>");
            str.Append(firstPlan.InventoryCountDown.HasValue?firstPlan.InventoryCountDown.Value.ToString("0.##"):"");
            str.Append("</td>");
            foreach (var planByDateIndex in planByDateIndexs)
            {
                var curenPlan = planByItem.Where(p => p.StartTime == planByDateIndex.Key);
                var pdPlan = curenPlan.Count() > 0 ? curenPlan.First() : new ProductionPlanDet();
                str.Append(string.Format("<td tital='{0}'  onclick='doTdClick(this)'>", pdPlan.Logs));
                str.Append(pdPlan.ReqQty.ToString("0.##"));
                str.Append("</td>");
                str.Append(string.Format("<td tital='{0}'  onclick='doShowDetsClick(this)'>", pdPlan.OrderDets));
                str.Append(pdPlan.OrderQty.ToString("0.##"));
                str.Append("</td>");

                //str.Append("<td>");
                //str.Append(pdPlan.Qty.ToString("0.##"));
                //str.Append("</td>");

                if (firstPlan.Status == BusinessConstants.CODE_MASTER_STATUS_VALUE_CREATE)
                {
                    seq++;
                    str.Append("<td width='30px'>");
                    str.Append("<input  type='text'  item='" + firstPlan.Item + "'  name='UpQty' id='" + pdPlan.Id + "'value='" + pdPlan.Qty.ToString("0.##") + "' releaseNo='" + firstPlan.ReleaseNo + "'  dateFrom='" + planByDateIndex.Key + "' style='width:70px' onblur='doFocusClick(this)' seq='" + seq + "' />");
                    str.Append("</td>");
                }
                else
                {
                    str.Append("<td>");
                    //if (planByDateIndex.Key.Date == System.DateTime.Now.Date)
                    //{
                    //    str.Append("<input type='checkbox' id='CheckBoxGroup' name='CheckBoxGroup' value='" + pdPlan.Id + "' runat='' onclick='doCheckClick()' />");
                    //}
                    str.Append(pdPlan.Qty.ToString("0.##"));
                    str.Append("</td>");
                }

                InitStockQty = InitStockQty + pdPlan.Qty-pdPlan.ReqQty+pdPlan.OrderQty;
                if (InitStockQty < firstPlan.SafeStock)
                {
                    str.Append("<td style='background:red;color:white'>");
                }
                else if (InitStockQty >= firstPlan.SafeStock && InitStockQty <= firstPlan.MaxStock)
                {
                    str.Append("<td style='background:green;color:white'>");
                }
                else if (InitStockQty > firstPlan.MaxStock)
                {
                    str.Append("<td style='background:orange'>");
                }
                str.Append(InitStockQty.ToString("0.##"));
                str.Append("</td>");
            }
            str.Append("</tr>");
        }
        str.Append("</tbody></table>");
        this.list.InnerHtml = headStr + str.ToString();
    }