private static CounterRecord AggregateDuplicates <T>(IGrouping <T, CounterRecord> records)
        {
            if (records.Count() <= 1)
            {
                return(records.First());
            }

            List <CounterRecord> listRecords = records.ToList();

            if (records.Count() <= 1)
            {
                return(records.First());
            }

            CounterRecord record = new CounterRecord
            {
                ItemName     = listRecords[0].ItemName,
                ItemPlatform = listRecords[0].ItemPlatform,
                ItemType     = listRecords[0].ItemType,
                RunDate      = listRecords[0].RunDate,
                Identifiers  = listRecords.SelectMany(x => x.Identifiers).Distinct(new CounterIdentifierComparer()).ToArray(),
                Metrics      = listRecords.SelectMany(x => x.Metrics).Distinct(new CounterMetricComparer()).GroupBy(x => x.MetricType).Select(x => new CounterMetric {
                    MetricType = x.Key, MetricValue = x.Sum(y => y.MetricValue)
                }).ToArray(),
            };

            return(record);
        }
예제 #2
0
        private static StringBuilder GenerateClass(IGrouping <string, RouteInfo> group, bool isLast)
        {
            string        classFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller";
            string        crefNamespace = GetCrefNamespace(classFullName, GetConvertedNamespace(group.First().Namespace));
            StringBuilder sb            = new StringBuilder();

            sb.AppendLine($"    /// <summary>");
            sb.AppendLine($"    /// <see cref=\"{crefNamespace}\"/>");
            sb.AppendLine($"    /// </summary>");
            sb.AppendLine($"    public class {group.Key}Route");
            sb.AppendLine("    {");
            for (int i = 0; i < group.Count(); i++)
            {
                var item          = group.ElementAt(i);
                var renamedAction = RenameOverloadedAction(group, i);
                sb.AppendLine("        /// <summary>");
                sb.AppendLine($"        /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>");
                sb.AppendLine("        /// </summary>");
                sb.AppendLine($"        public const string {renamedAction} = \"{item.Path}\";");

                if (i != group.Count() - 1)
                {
                    sb.AppendLine();
                }
            }

            sb.AppendLine("    }");
            if (!isLast)
            {
                sb.AppendLine();
            }

            return(sb);
        }
예제 #3
0
 public MeshUsage(IGrouping <int?, Mesh> group)
 {
     count          = group.Count();
     mesh           = group.First();
     triangleCount  = mesh.triangles.Length / 3;
     sceneTriangles = group.Count() * triangleCount;
 }
예제 #4
0
        private static StringBuilder GenerateEnum(IGrouping <string, EnumInfo> group, bool isLast)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"    public enum {group.Key}Enum");
            sb.AppendLine("    {");
            for (int i = 0; i < group.Count(); i++)
            {
                var item = group.ElementAt(i);
                var name = GetFiledName(group.ElementAt(i));
                sb.AppendLine($"        {name} = {item.Id},");

                if (i != group.Count() - 1)
                {
                    sb.AppendLine();
                }
            }

            sb.AppendLine("    }");
            if (!isLast)
            {
                sb.AppendLine();
            }

            return(sb);
        }
        private TesturaMutationReportItem CreateTesturaMutationReportItem(
            string headCategory,
            string subCategory,
            IGrouping <string, MutationDocumentResult> mutationDocumentResults)
        {
            var survived = mutationDocumentResults.Count(m => m.Survived);
            var killed   = mutationDocumentResults.Count(m => !m.Survived && m.CompilationResult != null && m.CompilationResult.IsSuccess);

            double mutationScore = 0.0;

            if (survived + killed != 0)
            {
                mutationScore = (double)killed / (survived + killed);
            }

            return(new TesturaMutationReportItem
            {
                HeadCategory = headCategory.ToString(),
                SubCategory = subCategory,
                FailedOnCompilation = mutationDocumentResults.Count(m => !m.CompilationResult.IsSuccess),
                Killed = killed,
                Survived = survived,
                MutationScore = mutationScore,
            });
        }
예제 #6
0
        private static StringBuilder GenerateClass2(IGrouping<string, FileInfo> group, bool isLast)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"    public class {GetClassName(group.Key)}");
            sb.AppendLine("    {");
            for (int i = 0; i < group.Count(); i++)
            {
                var item = group.ElementAt(i);
                var renamedAction = GetFiledName(group.ElementAt(i));
                sb.AppendLine($"        public const string {renamedAction} = \"{GetRelativeName(item.FullName)}\";");

                if (i != group.Count() - 1)
                {
                    sb.AppendLine();
                }
            }

            sb.AppendLine("    }");
            if (!isLast)
            {
                sb.AppendLine();
            }

            return sb;
        }
예제 #7
0
 private VisaStatisticItem VisaInfoGroupToVisaStatisticItem(IGrouping <DateTime, VisaInfo> visaInfoGroup)
 {
     return(new VisaStatisticItem(
                visaInfoGroup.Key,
                visaInfoGroup.Count(y => y.Result == VisaResult.InService),
                visaInfoGroup.Count(y => y.Result == VisaResult.Failure),
                visaInfoGroup.Count(y => y.Result == VisaResult.Success)));
 }
예제 #8
0
        private HudMessage MakeAnimalProduceHudMessage(IGrouping <string, FarmAnimal> groupOfAnimalsInBarn)
        {
            var translationSuffix = groupOfAnimalsInBarn.Count() > 1 ? "plural" : "singular";
            var message           = _translationHelper.Get($"news-feed.harvest-animals-found-in-location-notice.{translationSuffix}", new {
                numberOfItems = groupOfAnimalsInBarn.Count(),
                locationName  = groupOfAnimalsInBarn.Key,
            });

            return(new HudMessage(message, HudMessageType.NewQuest));
        }
예제 #9
0
        public static float RootMeanSquare(this IGrouping <float, SampleData> source)
        {
            if (source.Count() < 2)
            {
                throw new System.InvalidOperationException("Source must have at least 2 elements");
            }

            double s = source.Aggregate(0.0, (x, d) => x += Mathf.Pow((float)d.interSampleAngle, 2));

            return(Mathf.Sqrt((float)(s / source.Count())));
        }
예제 #10
0
        private static int SelectQuantity(int capacity, IGrouping <string, IMeatProducing> group)
        {
            int maxAvailable = new int[] { capacity, group.Count() }.Min();
            int desiredQuantity = StandardMessages.GetNumber(
                $"Selected {group.Key} with {group.Count()} animals available to process.\n" +
                $"Meat processor has {capacity} spaces of available capacity.\n\n" +
                $"How many should be processed, maximum of {maxAvailable}?",
                maxAvailable
                );

            return(desiredQuantity);
        }
예제 #11
0
        private static void CreateHeader(StringBuilder sb, IGrouping <DateTime, RaidModel> raidDate)
        {
            var killed = raidDate.Count(i => i.Killed);
            var failed = raidDate.Count(i => !i.Killed);
            var bosses = raidDate.Select(i => i.EncounterName).Distinct().Count();

            var tryTime = new TimeSpan(raidDate.Select(i => i.OccurenceEnd - i.OccurenceStart)
                                       .Sum(i => i.Ticks));
            var raidTime = raidDate.Max(i => i.OccurenceEnd) - raidDate.Min(i => i.OccurenceStart);

            sb.Append(HtmlCreator.CreateHeaderHtml(raidDate.Key, killed, failed, tryTime, raidTime, bosses));
        }
        private static BelStockArchiveLine ToBelStockArchiveDayOfMonth(IGrouping <string, BelStockArchiveLine> days)
        {
            var belStockMonth = new BelStockArchiveLine()
            {
                Timestamp = days.Key
            };

            belStockMonth.UsdTurnover  = days.Sum(d => d.UsdTurnover) / days.Count();
            belStockMonth.EuroTurnover = days.Sum(d => d.EuroTurnover) / days.Count();
            belStockMonth.RubTurnover  = days.Sum(d => d.RubTurnover) / days.Count();
            return(belStockMonth);
        }
        static TableRow CreateRow(int i, IGrouping <string, Game> game)
        {
            // Create 1 row to the table.
            TableRow tr1 = new TableRow();
            // Add a cell to each column in the row.
            TableCell tc1 = new TableCell(new Paragraph(new Run(new Text(game.Key))));
            TableCell tc2 = new TableCell(new Paragraph(new Run(new Text(game.First().Price.ToString() + " ₽"))));
            TableCell tc3 = new TableCell(new Paragraph(new Run(new Text(game.Count().ToString()))));
            TableCell tc4 = new TableCell(new Paragraph(new Run(new Text((game.Count() * game.First().Price).ToString() + " ₽"))));

            tr1.Append(tc1, tc2, tc3, tc4);
            return(tr1);
        }
        private static int SelectQuantity(int capacity, IGrouping <string, ISeedProducing> group)
        {
            int maxAvailable = new int[] { capacity, group.Count() }.Min();

            int response = StandardMessages.GetNumber(
                $"Selected {group.Key} with {group.Count()} rows of plants available to process.\n" +
                $"Seed Harvester has {capacity} rows of available capacity.\n\n" +
                $"How many should be processed, maximum of {maxAvailable}?",
                maxAvailable
                );

            return(response);
        }
예제 #15
0
        private static decimal CalculateForDiscount(decimal total, IGrouping <string, Item> item, string discountType)
        {
            // we disocunt if we have a set amount of items
            var quantityRequired = int.Parse(discountType.Split(" ")[0].Trim());
            var price            = decimal.Parse(discountType.Split(" ")[2].Trim());

            if (item.Count() >= quantityRequired)
            {
                var individualPrice = item.First().Price;
                total += ((item.Count() / quantityRequired) * price) + ((item.Count() % quantityRequired) * individualPrice);
            }

            return(total);
        }
예제 #16
0
        public int CalculateSpecialPrice(SpecialPrice specialPrice, IGrouping <string, Product> grouping)
        {
            var result     = 0;
            var groupCount = grouping.Count() - specialPrice.Quantity;

            //1- No Special price, just add standard price
            if (groupCount < 0)
            {
                result += grouping.Sum(g => g.Price);
                return(result);
            }

            //2- Scanned items exactly equals special price quantity.
            if (grouping != null && grouping.Count() == groupCount)
            {
                result += specialPrice.Price;
                var group = grouping.FirstOrDefault();
                if (group != null)
                {
                    result += groupCount * group.Price;
                }
                return(result);
            }

            //3- Scanned items > special price quantity & < twice the special price quantity
            result += specialPrice.Price;

            if (grouping != null && !grouping.Any())
            {
                return(result);
            }

            //4- Scanned items > twice the special price quantity
            var discountedGroups   = groupCount / specialPrice.Quantity;
            var nonDiscountedPrice = groupCount % specialPrice.Quantity;

            if (discountedGroups > 0)
            {
                result += discountedGroups * specialPrice.Price;
            }

            var product = grouping?.FirstOrDefault();

            if (product != null)
            {
                result += nonDiscountedPrice * product.Price;
            }

            return(result);
        }
        private static void InsertData(List <DateOpenClosedStatDto> list, IGrouping <string, PatchData> c)
        {
            int sumFixed         = c.Count(x => x.Compliance == "Fixed");
            int sumNotFixed      = c.Count(x => x.Compliance == "NotFixed");
            int sumNotApplicable = c.Count(x => x.Compliance == "NotApplicable");

            list.Add(new DateOpenClosedStatDto()
            {
                Date          = c.Key.ToString(),
                Fixed         = sumFixed,
                NotFixed      = sumNotFixed,
                NotApplicable = sumNotApplicable
            });
        }
예제 #18
0
        /// <summary>
        /// Returns any method definition errors.
        /// </summary>
        private IEnumerable <CodeQuestionError> GetMethodDefinitionErrors(
            IGrouping <string, RequiredMethod> requiredMethods,
            ClassDefinition submittedClass)
        {
            var submittedOverloads = submittedClass.Methods
                                     .Where(m => m.Name == requiredMethods.Key);

            if (requiredMethods.Count() != submittedOverloads.Count())
            {
                yield return(new MethodCountError
                             (
                                 Question.ClassName,
                                 requiredMethods.Key,
                                 requiredMethods.First().IsStatic,
                                 requiredMethods.Count()
                             ));

                yield break;
            }

            foreach (var requiredMethod in requiredMethods)
            {
                var matchingSubmittedMethod = submittedClass.Methods.FirstOrDefault
                                              (
                    submittedMethod =>
                    submittedMethod.Name == requiredMethod.Name &&
                    submittedMethod.IsPublic == requiredMethod.IsPublic &&
                    submittedMethod.IsStatic == requiredMethod.IsStatic &&
                    submittedMethod.ReturnType == StripGenericsFromType(requiredMethod.ReturnType) &&
                    submittedMethod.ParameterTypes.SequenceEqual
                    (
                        requiredMethod.ParamTypeList.Select(StripGenericsFromType)
                    )
                                              );

                if (matchingSubmittedMethod == null)
                {
                    yield return(new MethodDefinitionError
                                 (
                                     submittedClass.Name,
                                     requiredMethod.Name,
                                     requiredMethod.IsStatic,
                                     requiredMethod.IsPublic,
                                     requiredMethod.ParamTypes,
                                     requiredMethod.ReturnType
                                 ));
                }
            }
        }
예제 #19
0
        private static StringBuilder GenerateClass(IGrouping <string, RouteInfo> group, bool isLast)
        {
            string        classFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller";
            string        crefNamespace = GetCrefNamespace(classFullName, GetConvertedNamespace(group.First().Namespace));
            StringBuilder sb            = new StringBuilder();

            sb.AppendLine($"    /// <summary>");
            sb.AppendLine($"    /// <see cref=\"{crefNamespace}\"/>");
            sb.AppendLine($"    /// </summary>");
            sb.AppendLine($"    public class {group.Key}Route");
            sb.AppendLine("    {");
            for (int i = 0; i < group.Count(); i++)
            {
                var item          = group.ElementAt(i);
                var renamedAction = RenameOverloadedAction(group, i);
                sb.AppendLine("        /// <summary>");
                sb.AppendLine($"        /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>");
                sb.AppendLine("        /// </summary>");
                sb.AppendLine($"        public const string {renamedAction} = \"{item.Path}\";");

                if (config != null && config.GenerateMethod)
                {
                    sb.AppendLine($"        public static async Task<T> {item.ActionName}Async<T>({GeneraParameters(item.Parameters, true, false)})");
                    sb.AppendLine("        {");
                    sb.AppendLine($"            var routeInfo = new {nameof(RouteInfo)}");
                    sb.AppendLine("            {");
                    sb.AppendLine($"                {nameof(RouteInfo.HttpMethods)} = \"{item.HttpMethods}\",");
                    sb.AppendLine($"                {nameof(RouteInfo.Path)} = {renamedAction},");
                    sb.Append(GenerateParameters(item.Parameters));
                    sb.AppendLine("            };");
                    sb.AppendLine($"            return await {nameof(HttpClientAsync)}.{nameof(HttpClientAsync.Async)}<T>(routeInfo{GeneraParameters(item.Parameters, false, true)});");
                    sb.AppendLine("        }");
                }

                if (i != group.Count() - 1)
                {
                    sb.AppendLine();
                }
            }

            sb.AppendLine("    }");
            if (!isLast)
            {
                sb.AppendLine();
            }

            return(sb);
        }
예제 #20
0
        private static Transaction[] GenerateTxsForRefunds(IGrouping <Address, DepositDetails> depositGroup, DevKeyStoreWallet wallet)
        {
            Console.WriteLine();
            Console.Write($"Provide nonce for {depositGroup.Key}: ");
            int nonce = int.Parse(Console.ReadLine());

            Console.Write($"Provide address to send the refund to: ");
            string  hexAddress = Console.ReadLine();
            Address refundTo   = new Address(hexAddress);

            SecureString securedPassword = ConsoleUtils.ReadSecret("Provide password: "******"Password has been accepted.");
                Console.WriteLine();
                Console.WriteLine($"Great, will generate refund transactions for deposits of {depositGroup.Key} starting with nonce {nonce}. ETH/DAI will be sent to {refundTo}.");
                List <Transaction> transactions = new List <Transaction>(depositGroup.Count());
                foreach (DepositDetails depositDetails in depositGroup)
                {
                    Deposit     deposit     = depositDetails.Deposit;
                    RefundClaim refundClaim = new RefundClaim(deposit.Id, depositDetails.DataAsset.Id, deposit.Units,
                                                              deposit.Value, deposit.ExpiryTime, depositDetails.Pepper, depositDetails.DataAsset.Provider.Address, refundTo);
                    UInt256 gasPrice = 20.GWei();

                    AbiEncoder  abiEncoder  = new AbiEncoder();
                    byte[]      txData      = abiEncoder.Encode(AbiEncodingStyle.IncludeSignature, ContractData.ClaimRefundSig, depositDetails.DataAsset.Id, refundClaim.Units, refundClaim.Value, refundClaim.ExpiryTime, refundClaim.Pepper, refundClaim.Provider, depositDetails.Consumer);
                    Transaction transaction = new Transaction();
                    transaction.Value         = 0;
                    transaction.Data          = txData;
                    transaction.To            = new Address("0xb1AD03b75bD9E5AB89968D7a37d99F9dd220796D");
                    transaction.SenderAddress = depositDetails.Consumer;
                    transaction.GasLimit      = 100000;
                    transaction.GasPrice      = gasPrice;
                    transaction.Nonce         = (UInt256)nonce++;
                    wallet.Sign(transaction, ChainId.Mainnet);

                    EthereumEcdsa ecdsa            = new EthereumEcdsa(ChainId.Mainnet, LimboLogs.Instance);
                    Address       recoveredAddress = ecdsa.RecoverAddress(transaction);
                    if (recoveredAddress != transaction.SenderAddress)
                    {
                        Console.WriteLine("Signature failure");
                        return(new Transaction[0]);
                    }

                    transactions.Add(transaction);
                }

                return(transactions.ToArray());
            }

            Console.WriteLine("Incorrect password.");
            return(new Transaction[0]);
        }
예제 #21
0
        internal Boolean ValidarAtributos(ComboBox[] arrayAtributos)
        {
            int    countLeer = 0;
            string vacio     = "";

            //Con este array miro que no esten vacios
            for (int i = 0; i <= arrayAtributos.Length - 1; i++)
            {
                if (arrayAtributos[i].Text == "")
                {
                    countLeer += 1;
                    vacio     += Environment.NewLine + arrayAtributos[i].Tag.ToString();
                }
            }
            if (countLeer > 0)
            {
                MessageBox.Show("El siguiente campo esta vacio: " + vacio);
                return(false);
            }
            IEnumerable <IGrouping <string, ComboBox> > groups = arrayAtributos.GroupBy(x => x.Text);
            IGrouping <string, ComboBox> largest = groups.OrderByDescending(x => x.Count()).First();
            string name = largest.Key;

            if (largest.Count() != 1)
            {
                MessageBox.Show("El siguiente campo esta repetido: " + name);
                return(false);
            }
            return(true);
        }
        private ICollection <JsonExpectedSchema> GenerateExpectedSchemas(
            IGrouping <string, OperationResponseDescription> group, OperationProcessorContext context)
        {
            if (group.Count() > 1)
            {
                var expectedSchemas = new List <JsonExpectedSchema>();
                foreach (var response in group)
                {
                    var contextualResponseType = response.ResponseType.ToContextualType();

                    var isNullable = _settings.ReflectionService.GetDescription(contextualResponseType, _settings).IsNullable;
                    var schema     = context.SchemaGenerator.GenerateWithReferenceAndNullability <JsonSchema>(
                        contextualResponseType, isNullable, context.SchemaResolver);

                    expectedSchemas.Add(new JsonExpectedSchema
                    {
                        Schema      = schema,
                        Description = response.Description
                    });
                }

                return(expectedSchemas);
            }
            return(null);
        }
예제 #23
0
        private static async Task ProcessDuplicatesAsync(IGraphServiceClient graphClient, Calendar calendar, IGrouping <GroupByFields, Event> duplicateGroup)
        {
            WriteInfo($"- {duplicateGroup.Key} ({duplicateGroup.Count()} items)");

            // Check if more than one event have the same ID.
            var idGroups = duplicateGroup.GroupBy(e => e.Id).ToList();

            if (idGroups.Any(g => g.Count() > 1))
            {
                WriteInfo("  The impossible seems to have happened: Multiple events have the same id. Here they are:");
                foreach (var idGroup in idGroups.Where(g => g.Count() > 1))
                {
                    WriteInfo($"  - {idGroup.Count()} events with ID {idGroup.Key}");
                }
            }

            // Double-check for existance so that we don't use "phantom" events.
            var events = await GetNonPhantomsAsync(graphClient, calendar, idGroups.Select(g => g.Key).ToList());

            WriteInfo($"  Number of unique \"non-phantom\" IDs: {events.Count}");

            if (events.Count > 1 && _options.Fix)
            {
                if (calendar.CanEdit.HasValue && calendar.CanEdit.Value)
                {
                    await RemoveDuplicatesAsync(graphClient, calendar, events);
                }
                else
                {
                    WriteInfo("  Calendar is not editable so we can't fix.");
                }
            }
        }
예제 #24
0
        private List <PokemonData> GetPokemonByPossibleEvolve(IGrouping <PokemonId, PokemonData> pokemon, int limit)
        {
            PokemonSettings setting = null;

            if (!PokeSettings.TryGetValue(pokemon.Key, out setting))
            {
                LogCaller(new LoggerEventArgs(String.Format("Failed to find settings for pokemon {0}", pokemon.Key), LoggerTypes.Info));

                return(new List <PokemonData>());
            }

            Candy pokemonCandy = PokemonCandy.FirstOrDefault(x => x.FamilyId == setting.FamilyId);

            int candyToEvolve = setting.CandyToEvolve;
            int totalPokemon  = pokemon.Count();
            int totalCandy    = pokemonCandy.Candy_;

            if (candyToEvolve == 0)
            {
                return(new List <PokemonData>());
            }

            int maxPokemon = totalCandy / candyToEvolve;

            if (maxPokemon > limit)
            {
                maxPokemon = limit;
            }

            return(pokemon.OrderByDescending(x => x.Cp).Skip(maxPokemon).ToList());
        }
예제 #25
0
파일: Program.cs 프로젝트: lewyg/asn1scc
        //ANTLRReaderStream
        public static Tuple <ITree, string, IToken[]> Parse <L, P>(IGrouping <string, string> fileGrouping, Func <ICharStream, L> lexer, Func <ITokenStream, P> parser, Func <P, ITree> root)
            where L : Lexer where P : Parser
        {
            CommonTokenStream stream = null;

            if (fileGrouping.Count() > 1)
            {
                MemoryStream memStream = new MemoryStream();
                foreach (var filename in fileGrouping)
                {
                    byte[] fileData = File.ReadAllBytes(filename);
                    memStream.Write(fileData, 0, fileData.Length);
                    memStream.WriteByte(32);    //append a space in case there is no character after ASN.1 END
                }
                memStream.Position = 0;
                stream             = new CommonTokenStream(lexer(new ANTLRInputStream(memStream)));
            }
            else
            {
                foreach (var filename in fileGrouping)
                {
                    stream = new CommonTokenStream(lexer(new ANTLRFileStream(filename)));
                }
            }

            var tokens = stream.GetTokens().Cast <IToken>().ToArray();
            var tree   = root(parser(stream));

            return(Tuple.Create(tree, fileGrouping.Key, tokens));
        }
예제 #26
0
        private FunctionalSkillEarning CreateEarning(IGrouping <string, LearningDeliveryPeriodisedValues> groupItem)
        {
            if (groupItem.Count() > 1)
            {
                throw new ArgumentException($"More than one functional skill earning of type {groupItem.Key}");
            }

            const byte earningPeriods = 12;

            var periods = new EarningPeriod[earningPeriods];

            for (byte i = 1; i <= earningPeriods; i++)
            {
                var periodValues = groupItem.Select(p => p.GetPeriodValue(i)).ToArray();
                var periodValue  = periodValues.SingleOrDefault(v => v.GetValueOrDefault(0) != 0).GetValueOrDefault(0);

                periods[i - 1] = new EarningPeriod
                {
                    Period = i,
                    Amount = periodValue.AsRounded(),
                    SfaContributionPercentage = 1,
                };
            }

            return(new FunctionalSkillEarning
            {
                Type = TypeMap[groupItem.Key],
                Periods = new ReadOnlyCollection <EarningPeriod>(periods),
            });
        }
예제 #27
0
 // Reduce() returns a list of Key/value pairs representing the results
 // An IGrouping<> represents a set of values that have the same key
 private static IEnumerable <KeyValuePair <string, int> > Reduce(IGrouping <string, string> group)
 {
     return(new KeyValuePair <string, int>[]
     {
         new KeyValuePair <string, int>(group.Key, group.Count())
     });
 }
예제 #28
0
        private IEnumerable <QuizInfoForDb> CreateQuizInfoForDb(OrderingBlock orderingBlock, IGrouping <string, QuizAnswer> answers)
        {
            var ans = answers.Select(x => x.ItemId).ToList()
                      .Select(x => new QuizInfoForDb
            {
                QuizId            = orderingBlock.Id,
                IsRightAnswer     = true,
                ItemId            = x,
                Text              = null,
                QuizType          = typeof(OrderingBlock),
                QuizBlockScore    = 0,
                QuizBlockMaxScore = orderingBlock.MaxScore
            }).ToList();

            var isRightQuizBlock = answers.Count() == orderingBlock.Items.Length &&
                                   answers.Zip(orderingBlock.Items, (answer, item) => answer.ItemId == item.GetHash()).All(x => x);
            var blockScore = isRightQuizBlock ? orderingBlock.MaxScore : 0;

            foreach (var info in ans)
            {
                info.QuizBlockScore = blockScore;
            }

            return(ans);
        }
예제 #29
0
 public static CallRecordDto FromEntityGroup(IGrouping <string, CallRecord> entity)
 => new CallRecordDto
 {
     TotalDuration = TimeSpan.FromSeconds(entity.Sum(x => x.Duration)),
     TotalCount    = entity.Count(),
     SubscriberId  = entity.Key
 };
예제 #30
0
        private HudMessage MakeAnimalProduceHudMessage(IGrouping <string, FarmAnimal> groupOfAnimalsInBarn)
        {
            var toolsNeededForProduce = groupOfAnimalsInBarn
                                        .Select(_ => _.toolUsedForHarvest.Value)
                                        .Distinct()
                                        .OrderBy(_ => _);

            var translationSuffix = groupOfAnimalsInBarn.Count() > 1 ? "plural" : "singular";
            var message           = _translationHelper.Get($"news-feed.harvest-animals-found-in-location-notice.{translationSuffix}", new {
                numberOfItems         = groupOfAnimalsInBarn.Count(),
                locationName          = groupOfAnimalsInBarn.Key,
                toolsNeededForProduce = string.Join(", ", toolsNeededForProduce),
            });

            return(new HudMessage(message, HudMessageType.NewQuest));
        }
 public void ShowItem(IGrouping<string, LootItem> lootItemGroup)
 {
     ItemCountText.text = String.Format("{0}X", lootItemGroup.Count().ToString());
     LootItem lootItemSample = lootItemGroup.FirstElement();
     ItemGroupNameText.text = lootItemSample.Name;
     ItemGroupIcon.sprite = lootItemSample.IconSprite;
     this.gameObject.SetActive(true);
 }
예제 #32
0
 public HeroStatistic(IGrouping<string, Match> group)
 {
     Hero = group.Key;
     Matches = group.Count();
     Wins = group.Where(m => m.Win).Count();
     Losses = group.Where(m => m.Win == false).Count();
     WinRatio = Convert.ToInt32((double)Wins / (double)Matches * 100);
     TimePlayed = group.Select(g => g.Duration).Aggregate(TimeSpan.Zero, (subtotal, t) => subtotal.Add(t));
 }
예제 #33
0
        private Customer BuildCustomer(IGrouping<int, Bet> bets)
        {
            Customer customer = new Customer();

            customer.Id = bets.Key;
            customer.TotalNumberOfBets = bets.Count();
            customer.NumberOfSettledBets = bets.Count(bet => bet.BetStatus == BetStatus.Settled);
            customer.NumberOfUnsettledBets = bets.Count(bet => bet.BetStatus == BetStatus.Unsettled);
            customer.NumberOfWinningBets = bets.Count(bet => bet.BetStatus == BetStatus.Settled && bet.Win > 0);
            customer.TotalSettledStake = bets.Where(bet => bet.BetStatus == BetStatus.Settled).Sum(bet => bet.Stake);
            customer.TotalSettledWin = bets.Where(bet => bet.BetStatus == BetStatus.Settled).Sum(bet => bet.Win);
            customer.TotalUnsettledStake = bets.Where(bet => bet.BetStatus == BetStatus.Unsettled).Sum(bet => bet.Stake);
            customer.TotalUnsettledWin = bets.Where(bet => bet.BetStatus == BetStatus.Unsettled).Sum(bet => bet.Win);

            _customerRiskCalculator.DetermineCustomerRisk(customer);

            return customer;
        }
 public void ShowItemGroup(IGrouping<string, LootItem> lootItemGroup)
 {
     this.lootItemGroup = lootItemGroup;
     GroupCountText.text = String.Format("{0}X", lootItemGroup.Count().ToString());
     LootItem lootItemSample = lootItemGroup.FirstElement();
     EffectDurationValueText.text = lootItemSample.EffectDuration.TotalSeconds.ToString();
     PowerValueText.text = lootItemSample.PowerValue.ToString();
     ItemGroupIcon.sprite = lootItemSample.IconSprite;
     this.gameObject.SetActive(true);
 }
        public PeerSubscription Select(IGrouping<string, PeerSubscription> potentials)
        {
            int current = -1;

            lock (_currentOrdinals)
            {
                _currentOrdinals.TryGetValue(potentials.Key, out current);

                current = (current + 1) % potentials.Count();

                _currentOrdinals[potentials.Key] = current;
            }

            return potentials.ElementAt(current);
        }
 private IEnumerable<TempFile> createTempFilesForProject(IGrouping<string, RealtimeChangeMessage> project, List<string> projects)
 {
     var files = new List<TempFile>();
     var file = TempFileFromFile(project.Key);
     files.Add(new TempFile(null, file, project.Key));
     var content = File.ReadAllText(project.Key);
     if (project.Count(x => x.File != null) > 0)
         project.ToList().ForEach(x => files.Add(updateContent(ref content, x)));
     projects.ForEach(x => files.Add(updateProjectReference(ref content, x)));
     File.WriteAllText(file, content);
     Logger.WriteDebug("Project written " + file);
     var relativePath = getRelativePath(_solution, project.Key);
     _solutionContent = _solutionContent.Replace("\"" + relativePath + "\"", "\"" + getRelativePath(_solution, file) + "\"");
     _solutionContent = _solutionContent.Replace("\"" + project.Key + "\"", "\"" + getRelativePath(_solution, file) + "\"");
     Logger.WriteDebug(string.Format("Replacing {0} or {1} with {2}", relativePath, project.Key, file));
     return files;
 }
 public NameCount(IGrouping<string, string> grouping)
 {
     Name = grouping.Key;
     Count = grouping.Count();
 }
예제 #38
0
 /// <summary>
 /// Private method to be passed as linqs Select parameter. Lambda was too cumbersom
 /// </summary>
 /// <param name="wordCount"> The grouping result of the GroupBy method </param>
 /// <returns> A new KeyValuePair of count values </returns>
 private static KeyValuePair<string, int> NewWordCount(IGrouping<string, string> wordCount)
 {
     return new KeyValuePair<string, int>(wordCount.Key, wordCount.Count());
 }
        /// <summary>
        /// Validates a group of operations with the same context Uri.
        /// </summary>
        /// <param name="operations">Operations to validate.</param>
        private void ValidateOperationMetadataGroup(IGrouping<string, ODataOperation> operations)
        {
            Debug.Assert(operations != null, "operations must not be null.");
            Debug.Assert(operations.Any(), "operations.Any()");
            Debug.Assert(operations.All(o => this.GetOperationMetadataString(o) == operations.Key), "The operations should be grouped by their metadata.");

            if (operations.Count() > 1 && operations.Any(o => o.Target == null))
            {
                throw new ODataException(OData.Core.Strings.ODataJsonLightEntryAndFeedSerializer_ActionsAndFunctionsGroupMustSpecifyTarget(operations.Key));
            }

            foreach (IGrouping<string, ODataOperation> operationsByTarget in operations.GroupBy(this.GetOperationTargetUriString))
            {
                if (operationsByTarget.Count() > 1)
                {
                    throw new ODataException(OData.Core.Strings.ODataJsonLightEntryAndFeedSerializer_ActionsAndFunctionsGroupMustNotHaveDuplicateTarget(operations.Key, operationsByTarget.Key));
                }
            }
        }
예제 #40
0
        private PdfPTable CreateMemberNameData(PdfPTable table, IGrouping<string, ReportDataModel> data, string groupByClauseHeader, bool includeLeavingDetails, bool includeHeader)
        {
            if (includeHeader)
            {
                table.AddCell(GetHeaderCell(groupByClauseHeader));

                table.AddCell(GetHeaderCell("Start Date"));
                table.AddCell(GetHeaderCell("Gender"));
                table.AddCell(GetHeaderCell("Ethnicity"));
                table.AddCell(GetHeaderCell("Time At Smart"));
                table.AddCell(GetHeaderCell("Agency"));
                table.AddCell(GetHeaderCell("Project"));

                if (includeLeavingDetails)
                {
                    table.AddCell(GetHeaderCell("Date Of Leaving"));
                    table.AddCell(GetHeaderCell("Reason Of Leaving"));
                }
            }

            var cnt = 0;
            foreach (var item in data)
            {
                if (cnt <= 0)
                {
                    var groupByClauseColumn = GetGroupRowCell(data.Key, _rowFont);
                    groupByClauseColumn.Rowspan = data.Count() + 2;
                    table.AddCell(groupByClauseColumn);
                    cnt++;
                }
                var stDt = item.StartDate.HasValue ? item.StartDate.Value.ToShortDateString() : string.Empty;
                table.AddCell(new Phrase(stDt, _rowFont));
                table.AddCell(new Phrase(item.GenderName, _rowFont));
                table.AddCell(new Phrase(item.EthnicityName, _rowFont));
                table.AddCell(new Phrase(item.TimeAtSmart, _rowFont));
                table.AddCell(new Phrase(item.Agency, _rowFont));
                table.AddCell(new Phrase(item.ProjectName, _rowFont));
                if (includeLeavingDetails)
                {
                    table.AddCell(new Phrase(item.ExitDate.HasValue ? item.ExitDate.Value.ToShortDateString() : null, _rowFont));
                    table.AddCell(new Phrase(item.ReasonOfLeaving, _rowFont));
                }
            }

            return table;
        }
예제 #41
0
 private static bool IsSingleEvent(IGrouping<DateTime, EconomicEvent> item)
 {
     return item.Count() == 1;
 }
예제 #42
0
        private void UpdateBeeStatus(IGrouping<BeeState, Bee> stateGroup)
        {
            status.Items.Add(string.Format("{0}: {1} bee{2}", stateGroup.Key, stateGroup.Count(), stateGroup.Count() == 1 ? string.Empty : "s"));
            bool beesAreNotActive = stateGroup.Key.ToString() == "Idle" && stateGroup.Count() == _world.Bees.Count &&
                                 _framesRun > 0;

            if (beesAreNotActive)
                EndSimulation();
        }
예제 #43
0
		private IEnumerable<QuizInfoForDb> CreateQuizInfoForDb(OrderingBlock orderingBlock, IGrouping<string, QuizAnswer> answers)
		{
			var ans = answers.Select(x => x.ItemId).ToList()
				.Select(x => new QuizInfoForDb
				{
					QuizId = orderingBlock.Id,
					IsRightAnswer = true,
					ItemId = x,
					Text = null,
					QuizType = typeof(OrderingBlock),
					QuizBlockScore = 0,
					QuizBlockMaxScore = orderingBlock.MaxScore
				}).ToList();

			var isRightQuizBlock = answers.Count() == orderingBlock.Items.Length &&
				answers.Zip(orderingBlock.Items, (answer, item) => answer.ItemId == item.GetHash()).All(x => x);
			var blockScore = isRightQuizBlock ? orderingBlock.MaxScore : 0;
			foreach (var info in ans)
				info.QuizBlockScore = blockScore;

			return ans;
		}
예제 #44
0
 private MutationNode GroupOrMutant(IGrouping<string, MutationTarget> byGroupGrouping)
 {
     if(byGroupGrouping.Count() == 1)
     {
         var mutationTarget = byGroupGrouping.First();
         return new Mutant(mutationTarget.Id, mutationTarget);
     }
     else
     {
         return new MutantGroup(byGroupGrouping.Key,
             from mutationTarget in byGroupGrouping
             select new Mutant(mutationTarget.Id, mutationTarget)
             );
     }
 }
 private static string BuildMessage(IGrouping<int, Migration>[] doubledUpMigrations)
 {
     return "You have " + doubledUpMigrations.Count() + " migrations with the same Id:" +
            string.Join(",", doubledUpMigrations.Select(m => m.Key + " (" + m.Count() + ")"));
 }
        /// <summary>
        /// Writes a group of operation (all actions or all functions) that have the same "metadata".
        /// </summary>
        /// <remarks>
        /// Expects the actions or functions scope to already be open.
        /// </remarks>
        /// <param name="operations">A grouping of operations that are all actions or all functions and share the same "metadata".</param>
        private void WriteOperationMetadataGroup(IGrouping<string, ODataOperation> operations)
        {
            this.ValidateOperationMetadataGroup(operations);
            this.JsonLightOutputContext.JsonWriter.WriteName(operations.Key);
            bool useArray = operations.Count() > 1;
            if (useArray)
            {
                this.JsonLightOutputContext.JsonWriter.StartArrayScope();
            }

            foreach (ODataOperation operation in operations)
            {
                this.WriteOperation(operation);
            }

            if (useArray)
            {
                this.JsonLightOutputContext.JsonWriter.EndArrayScope();
            }
        }