示例#1
1
        private static void LargestStock(IList<double> cuts, IList<Board> stockList)
        {
            var longest = stockList.OrderByDescending(x => x.Length).First();
            var longestBoard = longest.Length;
            var boardCost = longest.Price;

            var scraps = new List<double>();
            var stockUsed = new List<Board>();

            while (cuts.Any())
            {
                var longestCut = cuts.OrderByDescending(x => x).First();
                cuts.Remove(longestCut);
                if (scraps.Any(x => x > longestCut))
                {
                    scraps = scraps.CutFromScrap(longestCut);
                }
                else
                {
                    stockUsed.Add(longest);
                    scraps.Add(longestBoard - longestCut - kerf);
                }
            }

            Console.WriteLine("Total number of boards used: {0}", stockUsed.Count());
            Console.WriteLine("Total Cost: {0}", stockUsed.Count() * boardCost);
            OutputWaste(scraps, stockUsed.Count() * longestBoard);
        }
        public void VisaData(IList<AktivPeriod> perioder)
        {
            panel1.Controls.Clear();
            double pixlarPerDygn = 1000;// (double)panel1.Width;

            var förstaTimme = perioder.OrderBy(o => o.Starttid.Hour).FirstOrDefault().Starttid.Hour;
            var sistaTimme = perioder.OrderBy(o => o.Starttid.Hour).LastOrDefault().Starttid.Hour;

            var daghöjd = 30;
            var marginal = 10;
            var vänsterMarginal = 120;
            var minutlängd = (pixlarPerDygn - vänsterMarginal) / (sistaTimme - förstaTimme) / 60; // pixlarPerDygn / 24 / 60;
            var position = 0;
            for (int timme = förstaTimme; timme <= sistaTimme; timme++)
            {
                var timstreck = new TimMarkering(timme);
                timstreck.Top = 0;
                timstreck.Left = (int)(position * minutlängd * 60) + vänsterMarginal;
                panel1.Controls.Add(timstreck);
                position++;

            }

            var y = marginal + daghöjd;

            foreach (var period in perioder.OrderByDescending(o => o.Starttid).GroupBy(o => o.Starttid.Date).Select(o =>
                new
                {
                    Datum = o.Key,
                    Perioder = o
                }))
            {
                var daglabel = new Label();
                daglabel.Top = y;
                daglabel.Left = marginal;
                daglabel.Text = period.Datum.ToString("dddd, d MMM");
                panel1.Controls.Add(daglabel);

                foreach (var item in period.Perioder)
                {
                    var aktivitet = new Aktivitetsmarkering(item);
                    aktivitet.BackColor = System.Drawing.Color.Blue;
                    aktivitet.Top = y;
                    aktivitet.Height = daghöjd;
                    aktivitet.Width = (int)(minutlängd * item.Tidsmängd.TotalMinutes);
                    if (aktivitet.Width == 0) aktivitet.Width = 1;
                    aktivitet.Left = (int)(item.Starttid.Subtract(period.Datum).TotalMinutes * minutlängd) + vänsterMarginal - (int)(förstaTimme * 60 * minutlängd);
                    panel1.Controls.Add(aktivitet);

                }
                y += daghöjd + marginal;
            }
        }
示例#3
1
        public static List<int[]> ChooseSets(IList<int[]> sets, IList<int> universe)
        {
            var selectedSets = new List<int[]>();

            while (universe.Count > 0)
            {
                var currentSet = sets.OrderByDescending(s => s.Count(universe.Contains)).First();

                selectedSets.Add(currentSet);
                sets.Remove(currentSet);
                universe = universe.Except(currentSet).ToList();
            }

            return selectedSets;
        }
        public void Update(IList<ICreature> creatures, IList<Tuple<ObjectType, IList<double>>> objects, MineSweeperSettings settings)
        {
            Image = new Bitmap(Width, Height);
            using (var graphics = Graphics.FromImage(Image))
            {
                var eliteSweeperPen = new Pen(_bestColor);
                var sweeperPen = new Pen(_neutralColor);
                var minePen = new Pen(Color.DarkGray);
                var blackPen = new Pen(Color.Black);
                var redPen = new Pen(Color.Maroon);

                // Elite Sweepers
                foreach (var sweeper in creatures.OrderByDescending(x => x.Fitness).Take(settings.EliteCount))
                {
                    drawSweeper(graphics, eliteSweeperPen, eliteSweeperPen.Brush, sweeper, settings.SweeperSize);
                }

                // Normal Sweepers
                foreach (var sweeper in creatures.OrderByDescending(x => x.Fitness).Skip(settings.EliteCount))
                {
                    drawSweeper(graphics, sweeperPen, sweeperPen.Brush, sweeper, settings.SweeperSize);
                }

                // Mines
                var mines = objects.Where(x => x.Item1 == ObjectType.Mine).Select(x => x.Item2);
                foreach (var mine in mines)
                {
                    drawMine(graphics, redPen, minePen.Brush, mine, settings.MineSize);
                }

                // ClusterMines
                var clusterMines = objects.Where(x => x.Item1 == ObjectType.ClusterMine).Select(x => x.Item2);
                foreach (var mine in clusterMines)
                {
                    drawMine(graphics, blackPen, sweeperPen.Brush, mine, settings.MineSize + 1);
                }

                // Holes
                var holes = objects.Where(x => x.Item1 == ObjectType.Hole).Select(x => x.Item2);
                foreach (var hole in holes)
                {
                    drawMine(graphics, redPen, redPen.Brush, hole, settings.MineSize + 1);
                }

                eliteSweeperPen.Dispose();
                sweeperPen.Dispose();
                minePen.Dispose();
                blackPen.Dispose();
                redPen.Dispose();
            }
        }
        public RuleResolver(IList<Rule> rules )
        {
            if(rules == null || rules.Count == 0)
                throw new ArgumentException("wrong format","rules");

            _rules = rules.OrderByDescending(x=>x.PriceTemplate.CountFixedDigits).ToList();
        }
示例#6
0
        public static Dictionary<int, int> ChooseCoins(IList<int> coins, int targetSum)
        {
            var sortedCoins = coins.OrderByDescending(c => c).ToList();
            var chosenCoins = new Dictionary<int, int>();
            var currentSum = 0;
            int coinIndex = 0;

            while (currentSum != targetSum && coinIndex < sortedCoins.Count)
            {
                var currentCoinValue = sortedCoins[coinIndex];
                var remainingSum = targetSum - currentSum;
                var numberOfCoinsToTake = remainingSum / currentCoinValue;
                if (numberOfCoinsToTake > 0)
                {
                    if (!chosenCoins.ContainsKey(currentCoinValue))
                    {
                        chosenCoins[currentCoinValue] = 0;
                    }

                    chosenCoins[currentCoinValue] += numberOfCoinsToTake;
                    currentSum += currentCoinValue * numberOfCoinsToTake;
                }

                coinIndex++;
            }

            if (currentSum != targetSum)
            {
                throw new InvalidOperationException("Greedy algorithm cannot produce desired sum with specified coins.");
            }

            return chosenCoins;
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 public SubmissionCandidatesViewModel(
     User user,
     IList<Commit> commits,
     Func<Commit, string> commitUrlBuilder,
     Checkpoint checkpoint,
     Model.Projects.Submission latestSubmission,
     ITimeZoneProvider timeZoneProvider)
 {
     User = user;
     Checkpoint = checkpoint;
     Candidates = commits
         .OrderByDescending(commit => commit.PushDate)
         .ThenByDescending(commit => commit.CommitDate)
         .Select
         (
             commit => new SubmissionCandidateViewModel
             (
                 commit,
                 commitUrlBuilder(commit),
                 latestSubmission?.CommitId == commit.Id,
                 commit == commits.First(),
                 timeZoneProvider
             )
         ).ToList();
 }
示例#8
0
 public static Dictionary<int, int> ChooseCoins(IList<int> coins, int targetSum)
 {
     var sortedCoins = coins.OrderByDescending(coin => coin)
         .ToList();
     var chosenCoin= new Dictionary<int,int>();
     var currentSum = 0;
     var coinIndex = 0;
     while (currentSum != targetSum && coinIndex< sortedCoins.Count)
     {
         var currentCoinValue = sortedCoins[coinIndex];
         var remainingSum = targetSum - currentSum;
         var numberOfCoinToTake = remainingSum / currentCoinValue;
         if (numberOfCoinToTake>0)
         {
             chosenCoin[currentCoinValue] = numberOfCoinToTake;
             currentSum += currentCoinValue * numberOfCoinToTake;
         }
         coinIndex++;
     }
     if (currentSum != targetSum)
     {
         throw new InvalidOperationException("Target sum can not be reached");
     }
     return chosenCoin;
 }
示例#9
0
 public ABMCierreY(CierreY cy)
 {
     InitializeComponent();
     CargarCombo();
     dpCierre.Value = DateTime.Now;
     dpApertura.Value = DateTime.Now;
     if (cy.Id != 0)
     {
         cierreY = new CierreY();
         cierreY = cy;
         cbCaja.Enabled = false;
         cbCajero.Enabled = false;
         CargarDatos();
     }
     else
     {
         listaY = gestorz.buscarCierreY(true, 0);
         listaY = listaY.OrderByDescending(c => c.Numero).ToList();
         if (listaY.Count > 0)
         {
             CierreY ciey = new CierreY();
             ciey = listaY[0];
             txtNumero.Text = (ciey.Numero + 1).ToString();
         }
         else
         { txtNumero.Text = "1"; }
     }
     txtRendido.Focus();
 }
        public void cargarDatos()
        {
            listaZ = gestor.buscar(false, 0, new EstadoCierreZ(), DateTime.MinValue, DateTime.MinValue);
            listaZ = listaZ.OrderByDescending(cz => cz.Numero).ToList();
            if (listaZ.Count > 0)
            {
                cierreZ = new CierreZ();
                cierreZ = listaZ[0];
                txtFinal.Text = cierreZ.SaldoFinal.ToString();
                txtNumero.Text = cierreZ.Numero.ToString();
                txtRendido.Text = cierreZ.SaldoRendido.ToString();
                txtSaldoInicial.Text = cierreZ.SaldoInicial.ToString();
                dpApertura.Value = cierreZ.Apertura;
                listacierrey = cierreZ.ListaCierreY;
                txtEstado.Text = cierreZ.EstadoCierrez.Descripcion;
                cargarGrilla();

                Utils.habilitar(true, txtNumero, btnBuscar);

            }
            else
            {
                estadoInicial();
                MessageBox.Show("No hay cierrezZ", "Atención");
            }
        }
        /// <summary>
        /// Selects the chromosomes which will be reinserted.
        /// </summary>
        /// <returns>The chromosomes to be reinserted in next generation..</returns>
        /// <param name="population">The population.</param>
        /// <param name="offspring">The offspring.</param>
        /// <param name="parents">The parents.</param>
        protected override IList<IChromosome> PerformSelectChromosomes(Population population, IList<IChromosome> offspring, IList<IChromosome> parents)
        {
            if (offspring.Count > population.MaxSize) {
                return offspring.OrderByDescending (o => o.Fitness).Take (population.MaxSize).ToList ();
            }

            return offspring;
        }
示例#12
0
        /// <summary>
        /// Returns the combinations of containers that can be used to completely fill
        /// one or more containers completely with the specified total volume of eggnog.
        /// </summary>
        /// <param name="volume">The volume of eggnog.</param>
        /// <param name="containerVolumes">The volumes of the containers.</param>
        /// <returns>
        /// The combinations of containers that can store the volume specified by <paramref name="volume"/>.
        /// </returns>
        internal static IList<ICollection<long>> GetContainerCombinations(int volume, IList<int> containerVolumes)
        {
            var containers = containerVolumes
                .OrderByDescending((p) => p)
                .ToList();

            return Maths.GetCombinations(volume, containers);
        }
示例#13
0
        /// <summary>
        /// The build manifest.
        /// </summary>
        /// <param name="execution">
        /// The execution.
        /// </param>
        /// <param name="orders">
        /// The orders.
        /// </param>
        /// <param name="bmllQueries">
        /// The queries.
        /// </param>
        /// <param name="factSetQueries">
        /// The fact set queries.
        /// </param>
        /// <param name="refinitivIntraDayQueries">
        /// The refinitiv intra day queries.
        /// </param>
        /// <param name="refinitivInterDayQueries">
        /// The refinitiv inter day queries.
        /// </param>
        /// <returns>
        /// The <see cref="IDataManifest"/>.
        /// </returns>
        private IDataManifest BuildManifest(
            ScheduledExecution execution,
            IList <UnfilteredOrdersQuery> orders,
            IList <BmllTimeBarQuery> bmllQueries,
            IList <FactSetTimeBarQuery> factSetQueries,
            IList <RefinitivIntraDayTimeBarQuery> refinitivIntraDayQueries,
            IList <RefinitivInterDayTimeBarQuery> refinitivInterDayQueries)
        {
            var stackedOrders = new Stack <UnfilteredOrdersQuery>();

            orders = orders?.OrderByDescending(_ => _.StartUtc)?.ToList() ?? new List <UnfilteredOrdersQuery>();
            foreach (var order in orders)
            {
                stackedOrders.Push(order);
            }

            var stackedBmllQueries = new Stack <BmllTimeBarQuery>();

            bmllQueries = bmllQueries?.OrderByDescending(_ => _.StartUtc)?.ToList() ?? new List <BmllTimeBarQuery>();
            foreach (var bmllQuery in bmllQueries)
            {
                stackedBmllQueries.Push(bmllQuery);
            }

            var stackedFactSetQueries = new Stack <FactSetTimeBarQuery>();

            factSetQueries = factSetQueries?.OrderByDescending(_ => _.StartUtc)?.ToList() ?? new List <FactSetTimeBarQuery>();
            foreach (var factSetQuery in factSetQueries)
            {
                stackedFactSetQueries.Push(factSetQuery);
            }

            var stackedRefinitivIntraDayQueries = new Stack <RefinitivIntraDayTimeBarQuery>();

            refinitivIntraDayQueries = refinitivIntraDayQueries?.OrderByDescending(_ => _.StartUtc)?.ToList() ?? new List <RefinitivIntraDayTimeBarQuery>();
            foreach (var refinitivQuery in refinitivIntraDayQueries)
            {
                stackedRefinitivIntraDayQueries.Push(refinitivQuery);
            }

            var stackedRefinitivInterDayQueries = new Stack <RefinitivInterDayTimeBarQuery>();

            refinitivInterDayQueries = refinitivInterDayQueries?.OrderByDescending(_ => _.StartUtc)?.ToList() ?? new List <RefinitivInterDayTimeBarQuery>();
            foreach (var refinitivQuery in refinitivInterDayQueries)
            {
                stackedRefinitivInterDayQueries.Push(refinitivQuery);
            }

            return(new DataManifest(
                       execution,
                       stackedOrders,
                       stackedBmllQueries,
                       stackedFactSetQueries,
                       stackedRefinitivIntraDayQueries,
                       stackedRefinitivInterDayQueries));
        }
示例#14
0
 public void Print(IList<Transaction> transactions)
 {
     _Console.WriteLine(StatementHeader);
     var balance = new Money(transactions.Sum(a => a.Money.Amount));
     foreach (var transaction in transactions.OrderByDescending(a => a.Date))
     {
          _Console.WriteLine(GetFormattedLine(transaction, balance));
          balance.Amount -= transaction.Money.Amount;
     }
 }
示例#15
0
 public void PrintWall(IList<Message> messages)
 {
     DateTime now = _Clock.CurrentDateAndTime;
     foreach (var message in messages.OrderByDescending(a => a.Time))
     {
         string humanizedTimeSpan = GetHumanizedTimeSpan(now.Subtract(message.Time));
         var formattedMessage = string.Format("{0} - {1} ({2} ago)", message.Author.Name, message.Text, humanizedTimeSpan);
         _Console.WriteLine(formattedMessage);
     }
 }
示例#16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SimulationEngine"/> class.
 /// </summary>
 /// <param name="historicalTasks">The historical tasks.</param>
 public SimulationEngine(IList<Task> historicalTasks)
 {
     if (historicalTasks != null)
     {
         // Sorts the tasks with the newest first:
         this.historicalTasks
             = historicalTasks
             .OrderByDescending(t => t.EndDate)
             .ToList();
     }
 }
示例#17
0
        static void OrderByTest()
        {
            //排序
            //var orderByResult = from s in studentList
            //                    orderby s.StudentName
            //                    select s;
            //var orderByDescendingResult = from s in studentList
            //                    orderby s.StudentName descending
            //                    select s;
            var orderByResult           = studentList.OrderBy(s => s.StudentName);
            var orderByDescendingResult = studentList.OrderByDescending(s => s.StudentName);

            foreach (var item in orderByResult)
            {
                Console.WriteLine(item);
            }
            foreach (var item in orderByDescendingResult)
            {
                Console.WriteLine(item);
            }
        }
        private async void UpdateMatches()
        {
            Matches.Clear();
            IList <Match> matches = await _matchService.GetAllMatchesAsync();

            matches = matches.OrderByDescending(m => m.Date).ToList();

            foreach (Match match in matches)
            {
                Matches.Add(match);
            }
        }
示例#19
0
 public IList <IProduct> OrderPrice(IList <IProduct> list, string order)
 {
     if (order == "Lowest price")
     {
         list = list.OrderBy(c => c.Price).ToList();
     }
     if (order == "Heights price")
     {
         list = list.OrderByDescending(c => c.Price).ToList();
     }
     return(list);
 }
示例#20
0
        public IList <IList <int> > TransformStringListToReversedIntMatrix(IList <string> lNums)
        {
            int lNumMax = lNums.OrderByDescending(n => n.Length).First().Length;

            IList <IList <int> > matrix = new List <IList <int> >();

            for (int i = 0; i < lNums.Count; i++)
            {
                matrix.Add(TransformStringtoReverseIntList(lNums[i]));
            }
            return(matrix);
        }
示例#21
0
        private void AddScoresInSubAreaToArea(Dictionary <string, double> dicArea, IList <DataRow> DataRows, int sortByColumnIndex)
        {
            DataRows = DataRows.OrderByDescending(x => Convert.ToDouble(x[sortByColumnIndex])).ToList();
            Dictionary <int, double> dicScores = SharedData.CalculateScoreEachItem(DataRows,
                                                                                   sortByColumnIndex);

            foreach (var kv in dicScores)
            {
                string name = DataRows[kv.Key][0].ToString();
                dicArea.Add(name, kv.Value);
            }
        }
示例#22
0
        private void Init()
        {
            seniorViewModelList = MappingHelper.MapSeniorModelToSeniorViewModel(GoldenHandContext.Instance.Seniors.ToList());

            var seniorsSorted = seniorViewModelList.OrderByDescending(x => x.Name).ToList();

            bsSeniors.DataSource = new BindingList <SeniorViewModel>(seniorsSorted);
            dgSeniors.DataSource = bsSeniors;


            Style.StyleDataGrid(dgSeniors);
        }
示例#23
0
        public async Task <IList <Product> > SortProducts(IList <Product> products, string sortOption)
        {
            switch (sortOption.ToLower())
            {
            case ProductSortHelper.LowToHigh:
                return(products?.OrderBy(x => x.Price).ToList());

            case ProductSortHelper.HighToLow:
                return(products?.OrderByDescending(x => x.Price).ToList());

            case ProductSortHelper.Ascending:
                return(products?.OrderBy(x => x.Name).ToList());

            case ProductSortHelper.Descending:
                return(products?.OrderByDescending(x => x.Name).ToList());

            case ProductSortHelper.Recommended:
                return(await SortProductsRecommendedByShoppingHistory(products));
            }
            return(products);
        }
示例#24
0
        public TubesheetModel(double diameter, double pitch, IList <TubeM> tubes)
        {
            Diameter = Diameter;
            Pitch    = pitch;
            Tubes    = new ObservableCollection <TubeM>(tubes.OrderByDescending(t => t.Row).ThenBy(t => t.Column));
            Model    = Tubes.FirstOrDefault().modelT;
            Model.ConnectTubesheet(this);
            NumRows = Tubes.Max(t => t.Row);
            NumCols = Tubes.Max(t => t.Column);

            Debug.Assert(NumRows == NumCols);
        }
示例#25
0
        private static MinMax GetExtremes(IList <double> resolutions)
        {
            if (resolutions == null || resolutions.Count == 0)
            {
                return(null);
            }
            resolutions = resolutions.OrderByDescending(r => r).ToList();
            var mostZoomedOut = resolutions[0];
            var mostZoomedIn  = resolutions[resolutions.Count - 1] / 2; // divide by two to allow one extra level zoom-in

            return(new MinMax(mostZoomedOut, mostZoomedIn));
        }
示例#26
0
        public static IList <Army> InitializePopulation(IList <Unit> basePool, int maxPopulation)
        {
            IList <Army> pop          = new List <Army>();
            decimal      smallestCost = basePool.Min(u => u.Cost);

            for (int i = 0; i < maxPopulation; i++)
            {
                pop.Add(GetRandomPermutation(basePool.OrderByDescending(u => u.Cost), Gold, smallestCost));
            }

            return(pop);
        }
示例#27
0
        public async Task <JsonResult> GetExContacts(ExContactIndexViewModel filterCond)
        {
            try
            {
                var contacts = await _extendedContactService.GetExternalContacts();

                IList <ExternalContact> filteredData = contacts;

                if (!string.IsNullOrEmpty(filterCond.FullName))
                {
                    filteredData = filteredData.Where(x => x.FullName.ToLower().Contains(filterCond.FullName.Trim().ToLower())).ToList();
                }

                if (!string.IsNullOrEmpty(filterCond.ContactNo1))
                {
                    filteredData = filteredData.Where(x => x.ContactNo1.ToLower().EndsWith(filterCond.ContactNo1.Trim())).ToList();
                }

                if (!string.IsNullOrEmpty(filterCond.City))
                {
                    filteredData = filteredData.Where(x => x.City.EmptyIfNull().ToLower().Contains(filterCond.City.Trim().ToLower())).ToList();
                }

                if (!string.IsNullOrEmpty(filterCond.District))
                {
                    filteredData = filteredData.Where(x => x.District.EmptyIfNull() == filterCond.District).ToList();
                }

                if (!string.IsNullOrEmpty(filterCond.Class))
                {
                    filteredData = filteredData.Where(x => x.Class.EmptyIfNull().ToLower() == filterCond.Class.Trim().ToLower()).ToList();
                }

                var orderedData = filteredData.OrderByDescending(x => x.Id);

                string strNums   = String.Empty;
                string strEmails = String.Empty;
                if (filteredData.Count() > 0)
                {
                    var nums   = filteredData.ToList().Select(x => x.ContactNo1).Distinct();
                    var emails = filteredData.ToList().Select(x => x.Email1).Distinct();
                    strNums   = string.Join(",", nums);
                    strEmails = string.Join(",", emails);
                }

                return(Json(new { datas = orderedData, Emails = strEmails, Nums = strNums, tcount = contacts.Count(), rcount = filteredData.Count(), status = "Successful", message = "" }));
            }
            catch (Exception ex)
            {
                var contacts = new List <ExternalContact>();
                return(Json(new { datas = contacts, Emails = string.Empty, Nums = string.Empty, tcount = contacts.Count(), rcount = contacts.Count(), status = "Successful", message = ex.Message }));
            }
        }
示例#28
0
 public void Write(IList <Warehouse> list)
 {
     foreach (var warehouse in list.OrderByDescending(x => x.TotalQuantity).ThenByDescending(x => x.Name))
     {
         _output.WriteLine($@"{warehouse.Name} (total {warehouse.TotalQuantity})");
         foreach (var product in warehouse.Quantities.OrderBy(x => x.Material.Id))
         {
             _output.WriteLine($@"[{product.Material.Id}]: {product.Quantity}");
         }
         _output.WriteLine();
     }
 }
        private static int MapMessages(Conference conference, IList <InstantMessageResponse> messageResponses)
        {
            if (messageResponses == null || !messageResponses.Any())
            {
                return(0);
            }

            messageResponses = messageResponses.OrderByDescending(x => x.Time_stamp).ToList();
            var vhoMessage = messageResponses.FirstOrDefault(m => IsNonParticipantMessage(conference, m));

            return(vhoMessage == null?messageResponses.Count() : messageResponses.IndexOf(vhoMessage));
        }
        public ActionResult Sort(string key, bool asc)
        {
            ViewData["OrderAsc"] = !asc;

            IList <BugReport> reports = brService.GetBugReports();
            IOrderedEnumerable <BugReport> sorted;

            switch (key)
            {
            case "Number":
                sorted = asc ?
                         reports.OrderBy(m => m.Number)
                        : reports.OrderByDescending(m => m.Number);
                break;

            case "ReportedBy":
                sorted = asc ?
                         reports.OrderBy(m => m.ReportedBy)
                        : reports.OrderByDescending(m => m.ReportedBy);
                break;

            case "ReportedTime":
                sorted = asc ?
                         reports.OrderBy(m => m.ReportedTime)
                        : reports.OrderByDescending(m => m.ReportedTime);
                break;

            case "OwnedBy":
                sorted = asc ?
                         reports.OrderBy(m => m.OwnedBy)
                        : reports.OrderByDescending(m => m.OwnedBy);
                break;

            default:
                sorted = reports.OrderByDescending(m => m.ReportedTime);
                break;
            }

            return(View("Index", sorted.ToList()));
        }
示例#31
0
        public Material SeedMaterial(Category category, string title, int commentsCount, string firstLine,
                                     string lineElement, LinesCount linesCount)
        {
            var publishDate       = dataContainer.IterateCommentPublishDate();
            int linesCountCurrent = ran.Next(linesCount.Min, linesCount.Max);

            Material material = new Material
            {
                Id           = dataContainer.NextMaterialId(),
                Title        = title,
                Text         = MakeSeedText(lineElement, 8, linesCountCurrent, firstLine),
                AuthorId     = dataContainer.GetRandomUserId(),
                CategoryId   = category.Id,
                PublishDate  = publishDate,
                LastActivity = publishDate
            };

            var(preview, description) = MaterialExtensions.MakePreviewAndDescription(material.Text,
                                                                                     MaterialDescriptionLength,
                                                                                     MaterialPreviewLength);

            material.Preview = preview;

            SectionType sectionType = category.GetSectionType();

            if (sectionType != null && sectionType.Name == SectionTypeNames.Articles)
            {
                material.Description = "Описание материала: " + material.Title;
            }
            else
            {
                material.Description = description;
            }


            if (commentsCount > 0)
            {
                IList <Comment> comments = MakeComments(material, commentsCount);

                //Comment last = comments.OrderByDescending(x=>x.PublishDate).First();
                //material.SetLastComment(last);

                material.LastActivity  = comments.OrderByDescending(x => x.PublishDate).First().PublishDate;
                material.CommentsCount = comments.Count;

                dataContainer.Comments.AddRange(comments);
            }

            dataContainer.Materials.Add(material);

            return(material);
        }
示例#32
0
        public ActionResult Register()
        {
            IList <CommonInfo> currencies = CommonInfoService.GetInstance().GetList(new CommonInfo()
            {
                pid = CommonInfo.Currency
            });
            IList <SelectListItem> items = new List <SelectListItem>();

            foreach (CommonInfo currency in currencies)
            {
                items.Add(new SelectListItem()
                {
                    Text = string.Format("{0}:{1}", currency.code, currency.name), Value = currency.code
                });
            }

            ViewData["currencies"] = items;

            //为登录用户
            if (UserUtil.getCurUser() == null)
            {
                //创建语言服务
                LanguageService languageservice = LanguageService.GetInstance();
                //获取所有语言信息
                IList <Language> languages = languageservice.GetList();
                string           langName  = "en-us";
                if (Request.UserLanguages != null && Request.UserLanguages.Length != 0)
                {
                    langName = Request.UserLanguages[0];
                }
                languages             = languages.OrderByDescending(lang => lang.codename.ToLower().Equals(langName)).ToList <Language>();
                ViewData["languages"] = languages;
                base.GetLanguage();
                return(View());
            }
            else
            {
                UserService userService = UserService.GetInstance();
                int         languageId  = userService.GetLanguageIdById(UserUtil.getCurUser().id);
                //创建语言服务
                LanguageService languageservice = LanguageService.GetInstance();
                //获取所有语言信息
                Language         language  = languageservice.GetNameByLanguageId(languageId);
                IList <Language> languages = languageservice.GetList();
                ViewData["lang"]      = language;
                ViewData["languages"] = languages;
                UserService userservice = UserService.GetInstance();
                ViewData["langs"] = LanguageService.GetInstance().GetList();
                base.GetLanguage();
                return(View(userservice.Get(UserUtil.getCurUser().id)));
            }
        }
示例#33
0
        static public bool Mem_Alloc(Process PS, ref IList <Hole> Hole_List, char mt, SortedList <int, Segment> Memory)
        {
            bool fit;

            if (mt == 'F')
            {
                Hole_List = Hole_List.OrderBy(a => a.start).ToList();
            }
            for (int i = 0; i < PS.sg_num; i++)
            {
                fit = false;
                if (mt == 'B')
                {
                    Hole_List = Hole_List.OrderBy(a => a.size).ToList();
                }
                else if (mt == 'W')
                {
                    Hole_List = Hole_List.OrderByDescending(a => a.size).ToList();
                }
                for (int j = 0; j < Hole_List.Count; j++)
                {
                    if (Hole_List[j].size >= PS.sgmnt[i].sg_size)
                    {
                        fit                        = true;
                        sg_temp.sg_name            = PS.sgmnt[i].sg_name;
                        sg_temp.sg_size            = PS.sgmnt[i].sg_size;
                        Memory[Hole_List[j].start] = sg_temp;
                        sg_temp.sg_size            = Hole_List[j].size - PS.sgmnt[i].sg_size;
                        if (sg_temp.sg_size == 0)
                        {
                            Removed_Holes.Push(Hole_List[j].num);
                            Hole_List.RemoveAt(j);
                        }
                        else
                        {
                            sg_temp.sg_name = "Hole " + Hole_List[j].num.ToString();
                            hole_temp.num   = Hole_List[j].num;
                            hole_temp.start = Hole_List[j].start + PS.sgmnt[i].sg_size;
                            hole_temp.size  = sg_temp.sg_size;
                            Hole_List[j]    = hole_temp;
                            Memory.Add(hole_temp.start, sg_temp);
                        }
                        break;
                    }
                }
                if (!fit)
                {
                    return(false);
                }
            }
            return(true);
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="source"></param>
        /// <param name="weight"></param>
        /// <param name="partitionCount">lists having identical total weight (as best as possible).</param>
        /// <returns></returns>
        public static IEnumerable <IList <TSource> > PartitionWithWeight <TSource>(
            this IList <TSource> source,
            Func <TSource, long> weight,
            int partitionCount)
        {
            var description = string.Format("Creating {0} partition(s) for {1} element(s)", partitionCount, source.Count);

            using (new TimeElapsedLogger(description))
            {
                var partitions = source
                                 .GetPartitionSizes(partitionCount)
                                 .Select(x => new Partition <TSource>
                {
                    MaxCount = x,
                    Items    = new List <TSource>(x)
                })
                                 .ToList();

                // Create MinHeap of partitions (wrt Weight function).
                var minHeap = new MinHeap <Partition <TSource> >(new PartitionWeightComparer <TSource>());
                partitions.ForAll(x => minHeap.Add(x));

                // Distribute items using MinHeap.
                source
                // Sort so that elements with highest weight are first, so that we
                // have a better chance of ending with partitions of same total weight
                // - it is easier to adjust with elements of low weight than with
                // elements of high weight.
                .OrderByDescending(weight)
                .ForAll(item =>
                {
                    var min = minHeap.Remove();
                    min.Items.Add(item);
                    min.TotalWeight += weight(item);
                    if (min.Items.Count < min.MaxCount)
                    {
                        minHeap.Add(min);
                    }
                });

#if false
                Logger.LogInfo("Created {0} partitions for a total ot {1:n0} elements and weight of {2:n0}.",
                               partitions.Count,
                               partitions.Aggregate(0L, (c, x) => c + x.Items.Count),
                               partitions.Aggregate(0L, (c, x) => c + x.TotalWeight));
                partitions.ForAll(x => {
                    Logger.LogInfo("  Partition count is {0:n0}, total weight is {1:n0}.", x.Items.Count, x.TotalWeight);
                });
#endif
                return(partitions.Select(x => x.Items));
            }
        }
示例#35
0
        protected void SortByCategory()
        {
            if (!sortCategoryDesc)
            {
                _sortedCategories = _sortedCategories.OrderBy(c => c.CategoryName).ToList();
            }
            else
            {
                _sortedCategories = _sortedCategories.OrderByDescending(c => c.CategoryName).ToList();
            }

            sortCategoryDesc = !sortCategoryDesc;
        }
        /// <summary>
        /// Seleccionar un subconjunto de la poblacion, los <size> mejores
        /// </summary>
        public void Select(IList<IIndividual> Individuals, int size)
        {
            IList<IIndividual> newIndividuals = new List<IIndividual>();

            newIndividuals = Individuals.OrderByDescending(
                    i => i.Fitness
                ).Take(size).ToList();
            Individuals.Clear();

            (newIndividuals as List<IIndividual>).ForEach(
                    i => Individuals.Add(i)
                );
        }
示例#37
0
        protected void SortBySupplier()
        {
            if (!sortSupplierDesc)
            {
                _sortedSuppliers = _sortedSuppliers.OrderBy(c => c.SupplierName).ToList();
            }
            else
            {
                _sortedSuppliers = _sortedSuppliers.OrderByDescending(c => c.SupplierName).ToList();
            }

            sortSupplierDesc = !sortSupplierDesc;
        }
示例#38
0
        private void RefreshMatchList()
        {
            matches = matches.OrderByDescending(match => match.Attendance).ToList();

            flpMatchStatistics.Controls.Clear();
            foreach (var match in matches)
            {
                MatchStats ms = new MatchStats((match as Match));


                flpMatchStatistics.Controls.Add(ms);
            }
        }
示例#39
0
        public static IList <Website.Data.Blog> OrderBy(this IList <Website.Data.Blog> list, BlogCollection.OrderBy orderBy)
        {
            if (orderBy == BlogCollection.OrderBy.PublishedAscending)
            {
                return(list.OrderBy(x => x.Published).ToList());
            }
            if (orderBy == BlogCollection.OrderBy.PublishedDescending)
            {
                return(list.OrderByDescending(x => x.Published).ToList());
            }

            return(list);
        }
示例#40
0
        private async Task LoadData()
        {
            Repository m_Repository = new Repository();
            //User user = await m_Repository.GetUser("creasewp");

            IList <User> poolUsers = await m_Repository.GetPoolUsers(string.Empty);//TODO

            m_PoolUsers = new List <User>();
            foreach (User poolUser in poolUsers.OrderByDescending(item => item.PoolScore))
            {
                m_PoolUsers.Add(poolUser);
            }
        }
示例#41
0
        /// <summary>
        /// Validate Expired Password
        /// </summary>
        /// <param name="pwdLog"></param>
        public static bool ValidatePasswordExpiration(IList <UserPwdHistoryDto> result, int days)
        {
            var lastPasswordDate = result.OrderByDescending(x => x.PwdModifyDate).Select(x => x.PwdModifyDate).FirstOrDefault();

            if (Convert.ToDateTime(lastPasswordDate) < DateTime.Now.AddDays(days))
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
示例#42
0
 /// <summary>
 /// Determines Eligibility for the ConcurrencyRate sample among the given data (Assumes past week's data)
 /// </summary>
 /// <param name="pastWeekData">Window of data in which to determine sample eligibility</param>
 /// <returns>Eligible ConcurrencyRate sample data</returns>
 internal IList <UserExperience> DetermineEligibleConcurrencySample(IList <UserExperience> pastWeekData)
 {
     // Calculate arrival rate + concurrency sample
     return(pastWeekData
            .OrderByDescending(data => data.ArrivalRate)
            .Where((data, i) =>
                   (data.HasPoisonWaits || i < 33) &&
                   data.ArrivalRate > 0.05m &&
                   data.ActiveUsers > 1)
            .OrderByDescending(data => data.Concurrency)
            .Take(33)
            .ToList());
 }
 private void LoadHistoryEntries()
 {
     _histories = new List <HistoryRow>();
     foreach (var history in Decisions.Where(d => !d.DoDelete).SelectMany(decision => decision.History))
     {
         _histories.Add(new HistoryRow
         {
             Date           = history.Modified,
             HistoryEntries = new[] { history }.ToList()
         });
     }
     _histories = _histories.OrderByDescending(x => x.Date).ToList();
 }
示例#44
0
 private void UpdateSyncLogCollection(IList <SyncLog> syncLogs, bool undoFilteEnabled)
 {
     Device.BeginInvokeOnMainThread(() =>
     {
         if (syncLogs.Any())
         {
             _syncLogsInternal.AddRange(syncLogs.OrderByDescending(_ => _.SyncDate).ToList());
         }
         DeleteHistoryCommand.IsEnabled = _syncLogsInternal.Any();
         UndoFilterCommand.IsEnabled    = undoFilteEnabled;
         DeleteHistoryButtonText        = undoFilteEnabled ? DeleteHistoryButtonTextFiltered : DeleteHistoryButtonTextStandard;
     });
 }
示例#45
0
        public IList <IMessage> SearchOtherRoleMessageData(IList <IMessage> messages, string searchString, string role)
        {
            IList <IMessage> selected = messages.OrderByDescending(m => m.TimeStamp).
                                        Where(m => m.Role == role && (
                                                  m.ReplyTo.ToLower().Contains(searchString.ToLower()) ||
                                                  m.Body.ToLower().Contains(searchString.ToLower()) ||
                                                  m.Role.ToLower().Contains(searchString.ToLower()) ||
                                                  m.Subject.ToLower().Contains(searchString.ToLower()) ||
                                                  m.TimeStamp.ToString().Contains(searchString) ||
                                                  m.messageType.ToString().ToLower().Contains(searchString.ToLower()))).ToList();

            return(selected);
        }
示例#46
0
        public IList <IMessage> SearchPUMessageData(IList <IMessage> messages, string searchString)
        {
            List <IMessage> selected = messages.OrderByDescending(m => m.TimeStamp).
                                       Where(m => m.ReplyTo.ToLower().Contains(searchString.ToLower()) ||
                                             m.Body.ToLower().Contains(searchString.ToLower()) ||
                                             m.Role.ToLower().Contains(searchString.ToLower()) ||
                                             m.Subject.ToLower().Contains(searchString.ToLower()) ||
                                             m.TimeStamp.ToString().Contains(searchString) ||
                                             m.messageType.ToString().ToLower().Contains(searchString.ToLower()) ||
                                             (m.FullName != null && m.FullName.ToString().ToLower().Contains(searchString.ToLower()))).ToList();

            return(selected);
        }
        /// <summary>
        /// Selects the chromosomes which will be reinserted.
        /// </summary>
        /// <returns>The chromosomes to be reinserted in next generation..</returns>
        /// <param name="population">The population.</param>
        /// <param name="offspring">The offspring.</param>
        /// <param name="parents">The parents.</param>
        protected override IList<IChromosome> PerformSelectChromosomes(Population population, IList<IChromosome> offspring, IList<IChromosome> parents)
        {
            var diff = population.MinSize - offspring.Count;

            if (diff > 0) {
                var bestParents = parents.OrderByDescending (p => p.Fitness).Take (diff);

                foreach (var p in bestParents) {
                    offspring.Add (p);
                }
            }

            return offspring;
        }
        public static IList<string> sortOnMostLiked(IList<Track> tracks, string dir, string[] songsDownloaded)
        {
            IList<string> newM3U = new List<string>();
            newM3U.Add("# Simple M3U playlist. Sorted on most liked (on SoundCloud). Generated by the SoundCloud Playlist Sync tool.");

            IEnumerable<Track> sortedTracks = tracks.OrderByDescending(r => r.GetType().GetProperty("favoritings_count").GetValue(r, null));
            foreach (Track track in sortedTracks)
            {
                string relativeTrackPath = MakeRelative(track.LocalPath, dir);
                newM3U.Add(relativeTrackPath);
            }

            return newM3U;
        }
示例#49
0
 public string CreateNewGame()
 {
     _ships = ShipInfo.CreateGameShips();
     _shots = new List<CellCoords>();
     foreach (var ship in _ships.OrderByDescending(s => s.Size))
     {
         var cells = GetCellsForShip(ship.Size, 10);
         ship.PositionCells.Clear();
         foreach (var cell in cells)
         {
             ship.PositionCells.Add(cell);
         }
     }
     _view.AddShips(_ships);
     return "42";
 }
示例#50
0
        /// <summary>
        /// Returns a list of backup files, removing the smallest versions of each database
        /// </summary>
        /// <param name="files">The files.</param>
        /// <returns></returns>
        public IList<BackupFile> RemoveDuplicatesBySize(IList<BackupFile> files)
        {
            var results = new List<BackupFile>();
            var sorted = files.OrderByDescending(x => x.Length);

            foreach (var file in sorted)
            {
                if (results.Any(x => x.DatabaseName == file.DatabaseName))
                {
                    continue;
                }
                results.Add(file);
            }

            return results;
        }
示例#51
0
        /// <summary>
        /// Check the winners from list of players
        /// </summary>
        /// <param name="playersToShowDown">List of players to check for winner</param>
        /// <param name="userInterface">Get the UserInterface where to print the message</param>
        public void CheckWinners(IList<IPlayer> playersToShowDown, IUserInterface userInterface)
        {
            double bestHand =
                playersToShowDown.OrderByDescending(player => player.Result.Power)
                    .Select(player => player.Result.Power)
                    .FirstOrDefault();
            this.winners = playersToShowDown.Where(player => player.Result.Power == bestHand).ToList();

            foreach (var player in this.winners)
            {
                if (player.Result.Type >= 0 && player.Result.Type <= Common.MaxRankWinningHands)
                {
                    WinningHandsTypes handsType = (WinningHandsTypes)player.Result.Type;

                    userInterface.PrintMessage("{0} wins with {1}!", player, handsType.ToString());
                }
            }
        }
示例#52
0
        public static List<int[]> ChooseSets(IList<int[]> sets, IList<int> universe)
        {
            var selectedSets = new List<int[]>();
            while (universe.Count > 0)
            {
                var currentSet = sets.
                    OrderByDescending(set => set.Count(universe.Contains)).
                    First();

                selectedSets.Add(currentSet);
                sets.Remove(currentSet);
                foreach (var item in currentSet)
                {
                    universe.Remove(item);
                }
            }

            return selectedSets;
        }
示例#53
0
        public _CommentsViewModel(IList<Comment> comments, Guid? replyTo = null, bool? invert = null)
        {
            Invert = invert;
            IsFork = true;
            ReplyTo = replyTo;

            var firstComment = comments.FirstOrDefault();
            if (firstComment != null)
            {
                IsDiscussionClosed = firstComment.Content.IsDiscussionClosed;
                ContentId = firstComment.Content.Id;
            }

            if (invert.HasValue && invert.Value)
                Comments = comments.OrderBy(c => c.DateTime).ToPaginationList(ConstHelper.CommentsPerPage, x => new _Comments_CommentViewModel(x));
            else
                Comments = comments.OrderByDescending(c => c.DateTime).ToPaginationList(ConstHelper.CommentsPerPage, x => new _Comments_CommentViewModel(x));

            CommentsCount = Comments.Count(c => !c.IsHidden);
        }
示例#54
0
        /// <summary>
        /// Sorts a Person collection and returns the sorted results.
        /// </summary>
        /// <param name="people"></param>
        /// <param name="sortFormat"></param>
        /// <returns></returns>
        public IList<Person> Sort(IList<Person> people, SortOutputFormat sortFormat)
        {
            IList<Person> sorted = null;

            switch(sortFormat)
            {
                case SortOutputFormat.Output1:
                    {
                        sorted = people.OrderBy(p => p.Gender).ThenBy((p => p.LastName)).ToList();
                        break;
                    }
                case SortOutputFormat.Output2:
                    {
                        sorted = people.OrderBy(p => p.DateOfBirth).ToList();
                        break;
                    }
                case SortOutputFormat.Output3:
                        sorted = people.OrderByDescending(p => p.LastName).ToList();
                        break;
            }

            return sorted;
        }
        /// <summary>
        /// Renders the specified albums.
        /// </summary>
        /// <param name="uploads">The uploads.</param>
        /// <param name="username">The username.</param>
        /// <returns></returns>
        public static string Render(IList<RecentUploads> uploads, string username)
        {
            StringBuilder builder = new StringBuilder();
            uploads = uploads.OrderByDescending(o => o.CreateDate).ToList();

            if (uploads == null) { throw new System.ArgumentNullException("uploads", "Parameter 'uploads' is null, value expected"); }

            if (uploads.Count > 0)
            {
                string albumUrl = _urlService.CreateUrl(username, "recent");
                builder.AppendLine(string.Format("<h3><a href=\"{0}\" >recent uploads</a></h3>", albumUrl));
                string val = BuildUpload(uploads);

                builder.AppendLine("<table class=\"recent\" ><tbody>");
                builder.AppendLine(val);
                builder.AppendLine("</tbody></table>");
                builder.AppendLine(uploads.Count > 4
                                       ? string.Format("<p class=\"clearboth marginbottom40\" ><a href=\"{0}/#/\" title=\"view additional uploads\">more...</a></p>", albumUrl)
                                       : "<br class=\"clearboth\" />");
            }

            return builder.ToString();
        }
示例#56
0
        public CompositeFileSystem(IList<Tuple<string, IFileSystem>> fss)
        {
            var ixs = fss.OrderBy(fs => fs.Item1, StringComparer.OrdinalIgnoreCase)
                .Select((fs, ix) => ix);

            _fslist = fss.OrderByDescending(fs => fs.Item1, StringComparer.OrdinalIgnoreCase).Select(fs =>
                Tuple.Create(Util.CombinePath(fs.Item1,""),fs.Item2)
            );

              foreach (var ix in ixs) {
                var fs = fss[ix];
                var k = fs.Item1;
                var n = Util.CombinePath(k, "");
                ProcessPath(fs.Item2, "/", n);
            }

            foreach (var p in _fs.Keys.ToArray()) {
                foreach (var s in NewSegments(p)) {
                    if (s.Equals("/"))
                        continue;

                    var name = s.Substring(s.TrimEnd('/').LastIndexOf('/')).Trim('/');
                    _fs[s] = new CompositePlaceHolderDir() { Name = name };
                }
            }

            var dirs = from nv in _fs
                                 let k = nv.Key.TrimEnd('/')
                                 let gk = k.Length > 0 ? k.Substring(0, k.LastIndexOf('/')) : ""
                                 group nv by gk.ToLowerInvariant();

            foreach (var g in dirs) {
                var k = g.Key.Length > 0 ? Util.CombinePath(g.Key, "") : "/";
                _dir[k] = g.Select(v => v.Value).ToList();
            }
            return;
        }
示例#57
0
        public List<Type> CompileModules(IList<IPersistentAssemblyInfo> persistentAssemblyInfos)
        {
            var definedModules = new List<Type>();

            foreach (IPersistentAssemblyInfo persistentAssemblyInfo in persistentAssemblyInfos.OrderByDescending(info => info.CompileOrder)) {
                string path = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),persistentAssemblyInfo.Name);
                if (File.Exists(path+".dll"))
                    File.Delete(path+".dll");
                persistentAssemblyInfo.CompileErrors = null;
                Type compileModule = CompileModule(persistentAssemblyInfo);

                if (compileModule != null) {
                    definedModules.Add(compileModule);
                }
                else if (File.Exists(path)) {
                    var fileInfo=new FileInfo(path);
                    fileInfo.CopyTo(path+".dll");
                    Assembly assembly = Assembly.LoadFile(path+".dll");
                    Type single = assembly.GetTypes().Where(type => typeof(ModuleBase).IsAssignableFrom(type)).Single();
                    definedModules.Add(single);
                }
            }
            return definedModules;
        }
        static void DumpPlayerGroupStats( TextWriter writer, IList<PlayerInfo> infos, string groupName )
        {
            RankStats stat = new RankStats();
            foreach( Rank rank2 in RankManager.Ranks ) {
                stat.PreviousRank.Add( rank2, 0 );
            }

            int totalCount = infos.Count;
            int bannedCount = infos.Count( info => info.IsBanned );
            int inactiveCount = infos.Count( info => info.TimeSinceLastSeen.TotalDays >= 30 );
            infos = infos.Where( info => (info.TimeSinceLastSeen.TotalDays < 30 && !info.IsBanned) ).ToList();

            if( infos.Count == 0 ) {
                writer.WriteLine( "{0}: {1} players, {2} banned, {3} inactive",
                                  groupName, totalCount, bannedCount, inactiveCount );
                writer.WriteLine();
                return;
            }

            for( int i = 0; i < infos.Count; i++ ) {
                stat.TimeSinceFirstLogin += infos[i].TimeSinceFirstLogin;
                stat.TimeSinceLastLogin += infos[i].TimeSinceLastLogin;
                stat.TotalTime += infos[i].TotalTime;
                stat.BlocksBuilt += infos[i].BlocksBuilt;
                stat.BlocksDeleted += infos[i].BlocksDeleted;
                stat.BlocksDrawn += infos[i].BlocksDrawn;
                stat.TimesVisited += infos[i].TimesVisited;
                stat.MessagesWritten += infos[i].MessagesWritten;
                stat.TimesKicked += infos[i].TimesKicked;
                stat.TimesKickedOthers += infos[i].TimesKickedOthers;
                stat.TimesBannedOthers += infos[i].TimesBannedOthers;
                if( infos[i].PreviousRank != null ) stat.PreviousRank[infos[i].PreviousRank]++;
            }

            stat.BlockRatio = stat.BlocksBuilt / (double)Math.Max( stat.BlocksDeleted, 1 );
            stat.BlocksChanged = stat.BlocksDeleted + stat.BlocksBuilt;

            stat.TimeSinceFirstLoginMedian = DateTime.UtcNow.Subtract( infos.OrderByDescending( info => info.FirstLoginDate )
                                                                            .ElementAt( infos.Count / 2 ).FirstLoginDate );
            stat.TimeSinceLastLoginMedian = DateTime.UtcNow.Subtract( infos.OrderByDescending( info => info.LastLoginDate )
                                                                           .ElementAt( infos.Count / 2 ).LastLoginDate );
            stat.TotalTimeMedian = infos.OrderByDescending( info => info.TotalTime ).ElementAt( infos.Count / 2 ).TotalTime;
            stat.BlocksBuiltMedian = infos.OrderByDescending( info => info.BlocksBuilt ).ElementAt( infos.Count / 2 ).BlocksBuilt;
            stat.BlocksDeletedMedian = infos.OrderByDescending( info => info.BlocksDeleted ).ElementAt( infos.Count / 2 ).BlocksDeleted;
            stat.BlocksDrawnMedian = infos.OrderByDescending( info => info.BlocksDrawn ).ElementAt( infos.Count / 2 ).BlocksDrawn;
            PlayerInfo medianBlocksChangedPlayerInfo = infos.OrderByDescending( info => (info.BlocksDeleted + info.BlocksBuilt) ).ElementAt( infos.Count / 2 );
            stat.BlocksChangedMedian = medianBlocksChangedPlayerInfo.BlocksDeleted + medianBlocksChangedPlayerInfo.BlocksBuilt;
            PlayerInfo medianBlockRatioPlayerInfo = infos.OrderByDescending( info => (info.BlocksBuilt / (double)Math.Max( info.BlocksDeleted, 1 )) )
                                                    .ElementAt( infos.Count / 2 );
            stat.BlockRatioMedian = medianBlockRatioPlayerInfo.BlocksBuilt / (double)Math.Max( medianBlockRatioPlayerInfo.BlocksDeleted, 1 );
            stat.TimesVisitedMedian = infos.OrderByDescending( info => info.TimesVisited ).ElementAt( infos.Count / 2 ).TimesVisited;
            stat.MessagesWrittenMedian = infos.OrderByDescending( info => info.MessagesWritten ).ElementAt( infos.Count / 2 ).MessagesWritten;
            stat.TimesKickedMedian = infos.OrderByDescending( info => info.TimesKicked ).ElementAt( infos.Count / 2 ).TimesKicked;
            stat.TimesKickedOthersMedian = infos.OrderByDescending( info => info.TimesKickedOthers ).ElementAt( infos.Count / 2 ).TimesKickedOthers;
            stat.TimesBannedOthersMedian = infos.OrderByDescending( info => info.TimesBannedOthers ).ElementAt( infos.Count / 2 ).TimesBannedOthers;

            stat.TopTimeSinceFirstLogin = infos.OrderBy( info => info.FirstLoginDate ).ToArray();
            stat.TopTimeSinceLastLogin = infos.OrderBy( info => info.LastLoginDate ).ToArray();
            stat.TopTotalTime = infos.OrderByDescending( info => info.TotalTime ).ToArray();
            stat.TopBlocksBuilt = infos.OrderByDescending( info => info.BlocksBuilt ).ToArray();
            stat.TopBlocksDeleted = infos.OrderByDescending( info => info.BlocksDeleted ).ToArray();
            stat.TopBlocksDrawn = infos.OrderByDescending( info => info.BlocksDrawn ).ToArray();
            stat.TopBlocksChanged = infos.OrderByDescending( info => (info.BlocksDeleted + info.BlocksBuilt) ).ToArray();
            stat.TopBlockRatio = infos.OrderByDescending( info => (info.BlocksBuilt / (double)Math.Max( info.BlocksDeleted, 1 )) ).ToArray();
            stat.TopTimesVisited = infos.OrderByDescending( info => info.TimesVisited ).ToArray();
            stat.TopMessagesWritten = infos.OrderByDescending( info => info.MessagesWritten ).ToArray();
            stat.TopTimesKicked = infos.OrderByDescending( info => info.TimesKicked ).ToArray();
            stat.TopTimesKickedOthers = infos.OrderByDescending( info => info.TimesKickedOthers ).ToArray();
            stat.TopTimesBannedOthers = infos.OrderByDescending( info => info.TimesBannedOthers ).ToArray();

            writer.WriteLine( "{0}: {1} players, {2} banned, {3} inactive",
                              groupName, totalCount, bannedCount, inactiveCount );
            writer.WriteLine( "    TimeSinceFirstLogin: {0} mean,  {1} median,  {2} total",
                              TimeSpan.FromTicks( stat.TimeSinceFirstLogin.Ticks / infos.Count ).ToCompactString(),
                              stat.TimeSinceFirstLoginMedian.ToCompactString(),
                              stat.TimeSinceFirstLogin.ToCompactString() );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopTimeSinceFirstLogin.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimeSinceFirstLogin.ToCompactString(), info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopTimeSinceFirstLogin.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimeSinceFirstLogin.ToCompactString(), info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopTimeSinceFirstLogin ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimeSinceFirstLogin.ToCompactString(), info.Name );
                }
            }
            writer.WriteLine();

            writer.WriteLine( "    TimeSinceLastLogin: {0} mean,  {1} median,  {2} total",
                              TimeSpan.FromTicks( stat.TimeSinceLastLogin.Ticks / infos.Count ).ToCompactString(),
                              stat.TimeSinceLastLoginMedian.ToCompactString(),
                              stat.TimeSinceLastLogin.ToCompactString() );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopTimeSinceLastLogin.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimeSinceLastLogin.ToCompactString(), info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopTimeSinceLastLogin.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimeSinceLastLogin.ToCompactString(), info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopTimeSinceLastLogin ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimeSinceLastLogin.ToCompactString(), info.Name );
                }
            }
            writer.WriteLine();

            writer.WriteLine( "    TotalTime: {0} mean,  {1} median,  {2} total",
                              TimeSpan.FromTicks( stat.TotalTime.Ticks / infos.Count ).ToCompactString(),
                              stat.TotalTimeMedian.ToCompactString(),
                              stat.TotalTime.ToCompactString() );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopTotalTime.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TotalTime.ToCompactString(), info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopTotalTime.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TotalTime.ToCompactString(), info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopTotalTime ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TotalTime.ToCompactString(), info.Name );
                }
            }
            writer.WriteLine();

            writer.WriteLine( "    BlocksBuilt: {0} mean,  {1} median,  {2} total",
                              stat.BlocksBuilt / infos.Count,
                              stat.BlocksBuiltMedian,
                              stat.BlocksBuilt );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopBlocksBuilt.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20}  {1}", info.BlocksBuilt, info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopBlocksBuilt.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20}  {1}", info.BlocksBuilt, info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopBlocksBuilt ) {
                    writer.WriteLine( "        {0,20}  {1}", info.BlocksBuilt, info.Name );
                }
            }
            writer.WriteLine();

            writer.WriteLine( "    BlocksDeleted: {0} mean,  {1} median,  {2} total",
                              stat.BlocksDeleted / infos.Count,
                              stat.BlocksDeletedMedian,
                              stat.BlocksDeleted );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopBlocksDeleted.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20}  {1}", info.BlocksDeleted, info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopBlocksDeleted.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20}  {1}", info.BlocksDeleted, info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopBlocksDeleted ) {
                    writer.WriteLine( "        {0,20}  {1}", info.BlocksDeleted, info.Name );
                }
            }
            writer.WriteLine();

            writer.WriteLine( "    BlocksChanged: {0} mean,  {1} median,  {2} total",
                              stat.BlocksChanged / infos.Count,
                              stat.BlocksChangedMedian,
                              stat.BlocksChanged );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopBlocksChanged.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20}  {1}", (info.BlocksDeleted + info.BlocksBuilt), info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopBlocksChanged.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20}  {1}", (info.BlocksDeleted + info.BlocksBuilt), info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopBlocksChanged ) {
                    writer.WriteLine( "        {0,20}  {1}", (info.BlocksDeleted + info.BlocksBuilt), info.Name );
                }
            }
            writer.WriteLine();

            writer.WriteLine( "    BlocksDrawn: {0} mean,  {1} median,  {2} total",
                              stat.BlocksDrawn / infos.Count,
                              stat.BlocksDrawnMedian,
                              stat.BlocksDrawn );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopBlocksDrawn.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20}  {1}", info.BlocksDrawn, info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopBlocksDrawn.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20}  {1}", info.BlocksDrawn, info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopBlocksDrawn ) {
                    writer.WriteLine( "        {0,20}  {1}", info.BlocksDrawn, info.Name );
                }
            }

            writer.WriteLine( "    BlockRatio: {0:0.000} mean,  {1:0.000} median",
                              stat.BlockRatio,
                              stat.BlockRatioMedian );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopBlockRatio.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20:0.000}  {1}", (info.BlocksBuilt / (double)Math.Max( info.BlocksDeleted, 1 )), info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopBlockRatio.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20:0.000}  {1}", (info.BlocksBuilt / (double)Math.Max( info.BlocksDeleted, 1 )), info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopBlockRatio ) {
                    writer.WriteLine( "        {0,20:0.000}  {1}", (info.BlocksBuilt / (double)Math.Max( info.BlocksDeleted, 1 )), info.Name );
                }
            }
            writer.WriteLine();

            writer.WriteLine( "    TimesVisited: {0} mean,  {1} median,  {2} total",
                              stat.TimesVisited / infos.Count,
                              stat.TimesVisitedMedian,
                              stat.TimesVisited );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopTimesVisited.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimesVisited, info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopTimesVisited.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimesVisited, info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopTimesVisited ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimesVisited, info.Name );
                }
            }
            writer.WriteLine();

            writer.WriteLine( "    MessagesWritten: {0} mean,  {1} median,  {2} total",
                              stat.MessagesWritten / infos.Count,
                              stat.MessagesWrittenMedian,
                              stat.MessagesWritten );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopMessagesWritten.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20}  {1}", info.MessagesWritten, info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopMessagesWritten.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20}  {1}", info.MessagesWritten, info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopMessagesWritten ) {
                    writer.WriteLine( "        {0,20}  {1}", info.MessagesWritten, info.Name );
                }
            }
            writer.WriteLine();

            writer.WriteLine( "    TimesKicked: {0:0.0} mean,  {1} median,  {2} total",
                              stat.TimesKicked / (double)infos.Count,
                              stat.TimesKickedMedian,
                              stat.TimesKicked );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopTimesKicked.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimesKicked, info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopTimesKicked.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimesKicked, info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopTimesKicked ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimesKicked, info.Name );
                }
            }
            writer.WriteLine();

            writer.WriteLine( "    TimesKickedOthers: {0:0.0} mean,  {1} median,  {2} total",
                              stat.TimesKickedOthers / (double)infos.Count,
                              stat.TimesKickedOthersMedian,
                              stat.TimesKickedOthers );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopTimesKickedOthers.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimesKickedOthers, info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopTimesKickedOthers.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimesKickedOthers, info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopTimesKickedOthers ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimesKickedOthers, info.Name );
                }
            }
            writer.WriteLine();

            writer.WriteLine( "    TimesBannedOthers: {0:0.0} mean,  {1} median,  {2} total",
                              stat.TimesBannedOthers / (double)infos.Count,
                              stat.TimesBannedOthersMedian,
                              stat.TimesBannedOthers );
            if( infos.Count() > TopPlayersToList * 2 + 1 ) {
                foreach( PlayerInfo info in stat.TopTimesBannedOthers.Take( TopPlayersToList ) ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimesBannedOthers, info.Name );
                }
                writer.WriteLine( "                           ...." );
                foreach( PlayerInfo info in stat.TopTimesBannedOthers.Reverse().Take( TopPlayersToList ).Reverse() ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimesBannedOthers, info.Name );
                }
            } else {
                foreach( PlayerInfo info in stat.TopTimesBannedOthers ) {
                    writer.WriteLine( "        {0,20}  {1}", info.TimesBannedOthers, info.Name );
                }
            }
            writer.WriteLine();
        }
示例#59
0
        public IEnumerable<Card> GetAllowedCards(Contract contract, IList<Card> currentTrickCards)
        {
            if (currentTrickCards == null || !currentTrickCards.Any())
            {
                // The player is first and can play any card
                return this;
            }

            var firstCard = currentTrickCards[0];

            // For all trumps the player should play bigger card from the same suit if available.
            // If bigger card is not available, the player should play any card of the same suit if available.
            if (contract.Type == ContractType.AllTrumps)
            {
                if (this.Any(x => x.Suit == firstCard.Suit))
                {
                    var bestCard = currentTrickCards.Where(card => card.Suit == firstCard.Suit).OrderByDescending(x => x.Type.GetOrderForAllTrumps()).First();

                    if (this.Any(card => card.Suit == firstCard.Suit && card.Type.GetOrderForAllTrumps() > bestCard.Type.GetOrderForAllTrumps()))
                    {
                        // Has bigger card(s)
                        return this.Where(card => card.Suit == firstCard.Suit && card.Type.GetOrderForAllTrumps() > bestCard.Type.GetOrderForAllTrumps());
                    }

                    // Any other card from the same suit
                    return this.Where(card => card.Suit == firstCard.Suit);
                }

                // No card of the same suit available
                return this;
            }

            // For no trumps the player should play card from the same suit if available.
            if (contract.Type == ContractType.NoTrumps)
            {
                if (this.Any(x => x.Suit == firstCard.Suit))
                {
                    return this.Where(x => x.Suit == firstCard.Suit);
                }

                // No card of the same suit available
                return this;
            }

            // Playing Clubs, Diamonds, Hearts or Spades
            if (firstCard.Suit == contract.Type.ToCardSuit())
            {
                // Trump card played
                if (this.Any(x => x.Suit == firstCard.Suit))
                {
                    var bestCard = currentTrickCards.Where(card => card.Suit == firstCard.Suit).OrderByDescending(x => x.Type.GetOrderForAllTrumps()).First();

                    if (this.Any(card => card.Suit == firstCard.Suit && card.Type.GetOrderForAllTrumps() > bestCard.Type.GetOrderForAllTrumps()))
                    {
                        // Has bigger card(s)
                        return this.Where(card => card.Suit == firstCard.Suit && card.Type.GetOrderForAllTrumps() > bestCard.Type.GetOrderForAllTrumps());
                    }

                    // Any other card from the same suit
                    return this.Where(card => card.Suit == firstCard.Suit);
                }

                // No card of the same suit available
                return this;
            }
            else
            {
                // Non-trump card played
                if (this.Any(x => x.Suit == firstCard.Suit))
                {
                    // If the player has the same card suit, he should play a card from the suit
                    return this.Where(x => x.Suit == firstCard.Suit);
                }
                else
                {
                    // The player has not a card with the same suit
                    if (this.Any(x => x.Suit == contract.Type.ToCardSuit()))
                    {
                        var currentPlayerTeamIsCurrentTrickWinner = false;
                        if (currentTrickCards.Count > 1)
                        {
                            // The teammate played card
                            Card bestCard;
                            if (currentTrickCards.Any(x => x.Suit == contract.Type.ToCardSuit()))
                            {
                                // Someone played trump
                                bestCard = currentTrickCards.Where(x => x.Suit == contract.Type.ToCardSuit()).OrderByDescending(x => x.Type.GetOrderForAllTrumps()).First();
                            }
                            else
                            {
                                // No one played trump
                                bestCard = currentTrickCards.OrderByDescending(x => x.Type.GetOrderForNoTrumps()).First();
                            }

                            if (currentTrickCards[currentTrickCards.Count - 2] == bestCard)
                            {
                                // The teammate has the best card in current trick
                                currentPlayerTeamIsCurrentTrickWinner = true;
                            }
                        }

                        // The player has trump card
                        if (currentPlayerTeamIsCurrentTrickWinner)
                        {
                            // The current trick winner is the player or his teammate.
                            // The player is not obligatory to play any trump
                            return this;
                        }
                        else
                        {
                            // The current trick winner is the rivals of the current player
                            if (currentTrickCards.Any(x => x.Suit == contract.Type.ToCardSuit()))
                            {
                                // Someone of the rivals has played trump card and is winning the trick
                                var biggestTrumpCard = currentTrickCards.OrderByDescending(x => x.Type.GetOrderForAllTrumps()).First();
                                if (this.Any(x => x.Suit == contract.Type.ToCardSuit() && x.Type.GetOrderForAllTrumps() > biggestTrumpCard.Type.GetOrderForAllTrumps()))
                                {
                                    // The player has bigger trump card(s) and should play one of them
                                    return this.Where(x => x.Suit == contract.Type.ToCardSuit() && x.Type.GetOrderForAllTrumps() > biggestTrumpCard.Type.GetOrderForAllTrumps());
                                }

                                // The player hasn't any bigger trump card so he can play any card
                                return this;
                            }
                            else
                            {
                                // No one played trump card, but the player should play one of them
                                return this.Where(x => x.Suit == contract.Type.ToCardSuit());
                            }
                        }
                    }

                    // The player has not any trump card or card from the played suit
                    return this;
                }
            }
        }
示例#60
0
 public Engine(IList<ISubtitleSource> sources)
 {
     _sources = sources.OrderByDescending(x => x.Reliability).ToList();
 }