Example #1
0
 public void MergeAllTranslation(IDictionary<string, TemplateItem> items)
 {
     foreach (var language in _repository.GetAvailableLanguages())
     {
         var filesNames = items.GroupBy(x => x.Value.FileName).Select(x => x.Key).ToList();
         MergeTranslation(items, _repository.GetTranslation(language.LanguageShortTag, filesNames, false));
     }
 }
        /// <summary>
        /// Returns a collapsed list of <see cref="ModuleDefinition"/>.
        /// </summary>
        /// <param name="modules"><see cref="IDictionary{TKey, TValue}"/> of <see cref="Module"/> to <see cref="ModuleDefinition"/> to collapse.</param>
        /// <returns><see cref="IDictionary{TKey, TValue}"/> of <see cref="Module"/> to <see cref="ModuleDefinition"/>.</returns>
        public static IDictionary <Module, ModuleDefinition> GetCollapsedModules(this IDictionary <Module, ModuleDefinition> modules)
        {
            var collapsedModules = new Dictionary <Module, ModuleDefinition>();

            foreach (var group in modules.GroupBy(_ => _.Value.Name))
            {
                var module   = group.ElementAt(0);
                var features = new Dictionary <Feature, FeatureDefinition>(module.Value.Features);
                features = features.Concat(group.Skip(1).SelectMany(_ => _.Value.Features)).ToDictionary(_ => _.Key, _ => _.Value);

                var newModule = new ModuleDefinition(module.Value.Name, features.GetCollapsedFeatures());
                collapsedModules[module.Key] = newModule;
            }

            return(collapsedModules);
        }
        /// <summary>
        /// Saves a template file which is a all strings (needing translation) used in the entire project. Not language dependent
        /// </summary>
        /// <param name="items">A list of template items to save. The list should be all template items for the entire project.</param>
        public bool SaveTemplate(IDictionary <string, TemplateItem> items)
        {
            if (!_localizationOptions.GenerateTemplatePerFile)
            {
                return(SaveTemplate(items, string.Empty));
            }

            var result = false;

            foreach (var item in items.GroupBy(x => x.Value.FileName))
            {
                result |= SaveTemplate(item.ToDictionary(x => x.Key, x => x.Value), item.Key);
            }

            return(result);
        }
Example #4
0
        /// <summary>
        /// Calculates the daily rate of change
        /// </summary>
        /// <param name="dictionary"><see cref="IDictionary{DateTime, Double}"/> with prices keyed by time</param>
        /// <returns><see cref="List{Double}"/> with daily rate of change</returns>
        private List <double> CalculateDailyRateOfChange(IDictionary <DateTime, double> dictionary)
        {
            var daily = dictionary.GroupBy(kvp => kvp.Key.Date)
                        .ToDictionary(x => x.Key, v => v.LastOrDefault().Value)
                        .Values.ToArray();

            var rocp = new double[daily.Length];

            for (var i = 1; i < daily.Length; i++)
            {
                rocp[i] = (daily[i] - daily[i - 1]) / daily[i - 1];
            }
            rocp[0] = 0;

            return(rocp.ToList());
        }
Example #5
0
 /// <summary>
 /// Saves a template file which is a all strings (needing translation) used in the entire project. Not language dependent
 /// </summary>
 /// <param name="items">A list of template items to save. The list should be all template items for the entire project.</param>
 public bool SaveTemplate(IDictionary<string, TemplateItem> items)
 {
     if (_settings.GenerateTemplatePerFile)
     {
         bool result = false;
         foreach (var item in items.GroupBy(x => x.Value.FileName))
         {
             result |= SaveTemplate(item.ToDictionary(x => x.Key, x => x.Value), item.Key);
         }
         return result;
     }
     else
     {
         return SaveTemplate(items, string.Empty);
     }
 }
Example #6
0
        public IDictionary <string, Warehouse> SortWarehouses(IDictionary <string, Warehouse> warehouse)
        {
            IDictionary <string, Warehouse> result = new Dictionary <string, Warehouse>();

            var group = warehouse.GroupBy(x => x.Value.TotalAmount);

            foreach (var item in group)
            {
                var orderedGroup = item.OrderByDescending(x => x.Value.Name);

                foreach (var item2 in orderedGroup)
                {
                    result.Add(item2.Key, item2.Value);
                }
            }
            return(result);
        }
Example #7
0
        public static int Part2(IDictionary <TestInstructions, IList <string> > opTest)
        {
            var used    = new HashSet <string>();
            var opCodes = new Dictionary <int, Action <int, int, int, int> >();

            var grp = opTest
                      .GroupBy(x => x.Key.Instruction.A)
                      .Select(x => new { x.Key, Possibilities = x.SelectMany(d => d.Value).Distinct().ToList() })
                      .Select(x => new { x.Key, x.Possibilities, Count = x.Possibilities.Count() })
                      .OrderBy(x => x.Possibilities.Count())
                      .ToList();

            while (opCodes.Count < 16)
            {
                foreach (var op in grp.OrderBy(x => x.Count))
                {
                    var ops = op.Possibilities.Where(x => !used.Contains(x));
                    if (ops.Count() != 1)
                    {
                        continue;
                    }

                    var opString = ops.Single();

                    used.Add(ops.Single());

                    opCodes.Add(op.Key, OpCodeImpl[opString]);
                }
            }

            var inst = File.ReadAllLines("input2.txt").Select(x =>
            {
                var i = x.Split(" ");
                return(int.Parse(i[0]), int.Parse(i[1]), int.Parse(i[2]), int.Parse(i[3]));
            });

            R[0] = R[1] = R[2] = R[3] = 0;

            foreach (var i in inst)
            {
                opCodes[i.Item1].Invoke(i.Item1, i.Item2, i.Item3, i.Item4);
            }

            return(R[0]);
        }
Example #8
0
        /// <summary>Reload one of the game's core assets (if applicable).</summary>
        /// <param name="content">The content manager through which to reload the asset.</param>
        /// <param name="assets">The asset keys and types to reload.</param>
        /// <returns>Returns a lookup of asset names to whether they've been propagated.</returns>
        public IDictionary <string, bool> Propagate(LocalizedContentManager content, IDictionary <string, Type> assets)
        {
            // group into optimized lists
            var buckets = assets.GroupBy(p =>
            {
                if (this.IsInFolder(p.Key, "Characters") || this.IsInFolder(p.Key, "Characters\\Monsters"))
                {
                    return(AssetBucket.Sprite);
                }

                if (this.IsInFolder(p.Key, "Portraits"))
                {
                    return(AssetBucket.Portrait);
                }

                return(AssetBucket.Other);
            });

            // reload assets
            IDictionary <string, bool> propagated = assets.ToDictionary(p => p.Key, p => false, StringComparer.OrdinalIgnoreCase);

            foreach (var bucket in buckets)
            {
                switch (bucket.Key)
                {
                case AssetBucket.Sprite:
                    this.ReloadNpcSprites(content, bucket.Select(p => p.Key), propagated);
                    break;

                case AssetBucket.Portrait:
                    this.ReloadNpcPortraits(content, bucket.Select(p => p.Key), propagated);
                    break;

                default:
                    foreach (var entry in bucket)
                    {
                        propagated[entry.Key] = this.PropagateOther(content, entry.Key, entry.Value);
                    }
                    break;
                }
            }
            return(propagated);
        }
Example #9
0
        private IList <ColourPair> GetColourPairs()
        {
            var dotsGroupedByTag = _coordsToDots.GroupBy(kvp => kvp.Value,
                                                         kvp => new { Coords = kvp.Key })
                                   .ToList();

            if (dotsGroupedByTag.Any(grouping => grouping.Count() != 2))
            {
                throw new InvalidOperationException("Dots must be in pairs!");
            }

            return(dotsGroupedByTag.Select(grouping =>
            {
                var startCoords = grouping.ElementAt(0).Coords;
                var endCoords = grouping.ElementAt(1).Coords;
                var dotColour = grouping.Key;
                return new ColourPair(startCoords, endCoords, dotColour);
            }).ToList());
        }
Example #10
0
 public IEnumerable <IOrderedEnumerable <KeyValuePair <string, int> > > Sort()
 {
     foreach (var word in _wordList)
     {
         if (_sortWords.ContainsKey(word))
         {
             _sortWords[word] += 1;
         }
         else
         {
             _sortWords.Add(word, 1);
         }
     }
     return(_sortWords
            .GroupBy(x => x.Key.ToString().First())
            .OrderBy(x => x.Key)
            .Select(x => x.OrderByDescending(y => y.Value))
            );
 }
Example #11
0
        public DealerCutRound(IList <Player> players, IEventBroker domainEvents)
        {
            this.players      = players;
            this.domainEvents = domainEvents;

            checkCutsComplete = domainEvents.Subscribe <DealerCardCut>(c =>
            {
                dealerCuts[c.player] = c.card;
                // check if we've all cut
                if ((players.Count - dealerCuts.Count) == 0)
                {
                    // find the winner so we can make them dealer, deal with DRAW!!
                    var cutsGroupedByCardAndOrderedHighestFirst = dealerCuts.GroupBy(x => x.Value).OrderByDescending(x => x.Key);
                    var CutsWithHighCard = cutsGroupedByCardAndOrderedHighestFirst.First();
                    if (CutsWithHighCard.Count() > 1)
                    {
                        domainEvents.Publish(new DealerCutDrawn(CutsWithHighCard.ToList()));
                    }
                    else
                    {
                        var dealer = cutsGroupedByCardAndOrderedHighestFirst.First().Single().Key;
                        domainEvents.Publish(new DealerChosen(dealer));
                    }
                }
            });

            onDraw = domainEvents.Subscribe <DealerCutDrawn>(e =>
            {
                onDraw.Dispose();
                onFinish.Dispose();
                checkCutsComplete.Dispose();
                var dealerCutRound = new DealerCutRound(e.players, domainEvents);
            });

            onFinish = domainEvents.Subscribe <DealerChosen>(e =>
            {
                onDraw.Dispose();
                onFinish.Dispose();
                checkCutsComplete.Dispose();
            });
        }
Example #12
0
        public void Save(
            IDictionary <RestoredCommandIdentifier, RestoredCommand> restoredCommandMap,
            DirectoryPath nuGetGlobalPackagesFolder)
        {
            EnsureFileStorageExists();

            foreach (var distinctPackageIdAndRestoredCommandMap in restoredCommandMap.GroupBy(x => x.Key.PackageId))
            {
                PackageId distinctPackageId = distinctPackageIdAndRestoredCommandMap.Key;
                string    packageCacheFile  = GetCacheFile(distinctPackageId);
                if (_fileSystem.File.Exists(packageCacheFile))
                {
                    var existingCacheTable = GetCacheTable(packageCacheFile);

                    var diffedRow = distinctPackageIdAndRestoredCommandMap
                                    .Where(pair => !TryGetMatchingRestoredCommand(
                                               pair.Key,
                                               nuGetGlobalPackagesFolder,
                                               existingCacheTable, out _))
                                    .Select(pair => ConvertToCacheRow(pair.Key, pair.Value, nuGetGlobalPackagesFolder));

                    _fileSystem.File.WriteAllText(
                        packageCacheFile,
                        JsonConvert.SerializeObject(existingCacheTable.Concat(diffedRow)));
                }
                else
                {
                    var rowsToAdd =
                        distinctPackageIdAndRestoredCommandMap
                        .Select(mapWithSamePackageId
                                => ConvertToCacheRow(
                                    mapWithSamePackageId.Key,
                                    mapWithSamePackageId.Value,
                                    nuGetGlobalPackagesFolder));

                    _fileSystem.File.WriteAllText(
                        packageCacheFile,
                        JsonConvert.SerializeObject(rowsToAdd));
                }
            }
        }
Example #13
0
        /// <summary>Reload one of the game's core assets (if applicable).</summary>
        /// <param name="content">The content manager through which to reload the asset.</param>
        /// <param name="assets">The asset keys and types to reload.</param>
        /// <returns>Returns the number of reloaded assets.</returns>
        public int Propagate(LocalizedContentManager content, IDictionary <string, Type> assets)
        {
            // group into optimized lists
            var buckets = assets.GroupBy(p =>
            {
                if (this.IsInFolder(p.Key, "Characters") || this.IsInFolder(p.Key, "Characters\\Monsters"))
                {
                    return(AssetBucket.Sprite);
                }

                if (this.IsInFolder(p.Key, "Portraits"))
                {
                    return(AssetBucket.Portrait);
                }

                return(AssetBucket.Other);
            });

            // reload assets
            int reloaded = 0;

            foreach (var bucket in buckets)
            {
                switch (bucket.Key)
                {
                case AssetBucket.Sprite:
                    reloaded += this.ReloadNpcSprites(content, bucket.Select(p => p.Key));
                    break;

                case AssetBucket.Portrait:
                    reloaded += this.ReloadNpcPortraits(content, bucket.Select(p => p.Key));
                    break;

                default:
                    reloaded += bucket.Count(p => this.PropagateOther(content, p.Key, p.Value));
                    break;
                }
            }
            return(reloaded);
        }
        public IDisposable Initialize()
        {
            var groups = _allNodes.GroupBy(item => item.Value, item => item.Key).ToArray();

            foreach (var group in groups)
            {
                switch (group.Key)
                {
                case NodeType.IfTrue:
                    _ifTrueNodes = group.ToList().AsReadOnly();
                    break;

                case NodeType.IfFalse:
                    _ifFalseNodes = group.ToList().AsReadOnly();
                    break;

                case NodeType.Test:
                    group.ForEach(item => item.Changed += OnChanged);
                    break;
                }
            }

            var ifTrueChildDisposable  = IfTrueChild?.Initialize();
            var ifFalseChildDisposable = IfFalseChild?.Initialize();

            Update(true);

            return(Disposable.Create(() =>
            {
                Update(false);

                _ifTrueNodes = null;
                _ifFalseNodes = null;
                groups.FirstOrDefault(item => item.Key == NodeType.Test)?
                .ForEach(item => item.Changed -= OnChanged);

                ifTrueChildDisposable?.Dispose();
                ifFalseChildDisposable?.Dispose();
            }));
        }
Example #15
0
        /// <summary>
        /// Checking Duplicate Values Check
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="maxLimit"></param>
        /// <returns></returns>
        private bool RepeatedValuesCheck(IDictionary <string, string> fields, string maxLimit, out string remarks)
        {
            bool isSpam = false;
            int  limit  = Int32.Parse(maxLimit);

            remarks = string.Empty;
            var duplicateValues = fields.GroupBy(x => x.Value).Select(x => new { Item = x.First(), Count = x.Count() }).ToList();

            foreach (var item in duplicateValues)
            {
                if (!string.IsNullOrEmpty(item.Item.Value))
                {
                    if (item.Count > limit)
                    {
                        isSpam  = true;
                        remarks = "Repeated Values Detected.";
                        break;
                    }
                }
            }
            return(isSpam);
        }
Example #16
0
        public Table(
            string name,
            string[] keyColumnsNames,
            IDictionary <string, SqlType> columns,
            string schema = null,
            SchemaSynchronizationStrategy synchronizationStrategy = SchemaSynchronizationStrategy.UntilSuccess)
        {
            if (keyColumnsNames == null)
            {
                throw new ArgumentNullException(nameof(keyColumnsNames));
            }
            _synchronizationStrategy = synchronizationStrategy;
            var repeatedKeyColumn = keyColumnsNames.GroupBy(k => k).FirstOrDefault(c => c.Count() > 1);

            if (repeatedKeyColumn != null)
            {
                throw new ArgumentException($"The key column named '{repeatedKeyColumn.Key}' appears more than once", nameof(columns));
            }
            if (columns == null)
            {
                throw new ArgumentNullException(nameof(columns));
            }
            if (columns.Count == 0)
            {
                throw new ArgumentException(@"The table must define at least one column", nameof(columns));
            }
            var repeatedColumn = columns.GroupBy(c => c.Key).FirstOrDefault(c => c.Count() > 1);

            if (repeatedColumn != null)
            {
                throw new ArgumentException($"The column named '{repeatedColumn.Key}' appears more than once", nameof(columns));
            }
            Name            = name ?? throw new ArgumentNullException(nameof(name));
            KeyColumnsNames = keyColumnsNames;
            Columns         = columns;
            Schema          = schema;
            _schemaSynchronizedSemaphore = new SemaphoreSlim(1);
        }
Example #17
0
        private IEnumerable <ShapeDescriptor> MergeDescriptors(IDictionary <string, ShapeDescriptor> shapeDescriptors)
        {
            return(shapeDescriptors
                   .GroupBy(x => x.Value.ShapeType)
                   .Select(
                       group => new ShapeDescriptor(group.Key)
            {
                Bindings = group
                           .SelectMany(x => x.Value.Bindings)
                           .GroupBy(x => x.Key, StringComparer.OrdinalIgnoreCase)
                           .Select(x => x.Last())
                           .ToDictionary(x => x.Key, x => x.Value),

                Wrappers = group
                           .SelectMany(sd => sd.Value.Wrappers)
                           .ToList(),

                CreatingAsync = group
                                .SelectMany(sd => sd.Value.CreatingAsync)
                                .ToList(),

                CreatedAsync = group
                               .SelectMany(sd => sd.Value.CreatedAsync)
                               .ToList(),

                DisplayingAsync = group
                                  .SelectMany(sd => sd.Value.DisplayingAsync)
                                  .ToList(),

                ProcessingAsync = group
                                  .SelectMany(sd => sd.Value.ProcessingAsync)
                                  .ToList(),

                DisplayedAsync = group
                                 .SelectMany(sd => sd.Value.DisplayedAsync)
                                 .ToList()
            }));
        }
        private static IEnumerable <ConfigMapCount> GetConfigMapCounts(Type type, Func <Type, bool> comparer, IDictionary <string, string> switchMapping)
        {
            var arrayNames = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                             .Where(b => comparer(b.PropertyType))
                             .Select(prop => prop.Name)
                             .ToList();

            var mappings = switchMapping.GroupBy(map => map.Value);

            foreach (var name in arrayNames)
            {
                var mapping = mappings.FirstOrDefault(map => string.Equals(map.Key, name, StringComparison.OrdinalIgnoreCase))
                              ?.Select(map => map.Key) ?? Enumerable.Empty <string>();
                var key = $"--{name}";

                yield return(new ConfigMapCount
                {
                    Tags = new HashSet <string>(mapping.Concat(new[] { key }), StringComparer.OrdinalIgnoreCase),
                    ExpectedTag = key,
                    Count = 0
                });
            }
        }
        private static void PrintDegreesDist(IDictionary <int, String> vertices, IDictionary <int, IList <int> > edges)
        {
            StringBuilder keyList = new StringBuilder(), countList = new StringBuilder();

            keyList.Append("Degrees : ");
            countList.Append("Counts : ");

            foreach (var groupInfo in edges.GroupBy(x => {
                return(x.Value.Count);
                //int nCount = 0;
                //for (; nCount < segmentList.Count; nCount++) { if (x.Value.Count < segmentList[nCount]) break; }
                //return segmentList[nCount];
            }).OrderBy(x => x.Key))
            {
                //Console.WriteLine(@"{0}:{1}", groupInfo.Key, groupInfo.Count());
                keyList.Append(groupInfo.Key);
                keyList.Append(',');
                countList.Append(groupInfo.Count());
                countList.Append(',');
            }

            Console.WriteLine(keyList.ToString());
            Console.WriteLine(countList.ToString());
        }
Example #20
0
 public RewriteVisitor(IDictionary <ScalarExpression, ScalarExpression> rewrites)
 {
     _mappings = rewrites
                 .GroupBy(kvp => kvp.Key.ToSql())
                 .ToDictionary(g => g.Key, g => g.First().Value);
 }
Example #21
0
        public static void Populate(IDictionary <string, string> ianaMap, IDictionary <string, string> windowsMap, IDictionary <string, string> railsMap, IDictionary <string, IList <string> > inverseRailsMap)
        {
            IEnumerable <string> mapping      = GetEmbeddedData("TimeZoneConverter.Data.Mapping.csv.gz");
            IEnumerable <string> aliases      = GetEmbeddedData("TimeZoneConverter.Data.Aliases.csv.gz");
            IEnumerable <string> railsMapping = GetEmbeddedData("TimeZoneConverter.Data.RailsMapping.csv.gz");

            var links = new Dictionary <string, string>();

            foreach (string link in aliases)
            {
                string[] parts = link.Split(',');
                string   value = parts[0];
                foreach (string key in parts[1].Split())
                {
                    links.Add(key, value);
                }
            }

            var similarIanaZones = new Dictionary <string, IList <string> >();

            foreach (string item in mapping)
            {
                string[] parts       = item.Split(',');
                string   windowsZone = parts[0];
                string   territory   = parts[1];
                string[] ianaZones   = parts[2].Split();

                // Create the Windows map entry
                if (!links.TryGetValue(ianaZones[0], out string value))
                {
                    value = ianaZones[0];
                }

                var key = $"{territory}|{windowsZone}";
                windowsMap.Add(key, value);

                // Create the IANA map entries
                foreach (string ianaZone in ianaZones)
                {
                    if (!ianaMap.ContainsKey(ianaZone))
                    {
                        ianaMap.Add(ianaZone, windowsZone);
                    }
                }

                if (ianaZones.Length > 1)
                {
                    foreach (string ianaZone in ianaZones)
                    {
                        similarIanaZones.Add(ianaZone, ianaZones.Except(new[] { ianaZone }).ToArray());
                    }
                }
            }

            // Expand the IANA map to include all links (both directions)
            foreach (KeyValuePair <string, string> link in links)
            {
                if (!ianaMap.ContainsKey(link.Key) && ianaMap.ContainsKey(link.Value))
                {
                    ianaMap.Add(link.Key, ianaMap[link.Value]);
                }
                else if (!ianaMap.ContainsKey(link.Value) && ianaMap.ContainsKey(link.Key))
                {
                    ianaMap.Add(link.Value, ianaMap[link.Key]);
                }
            }

            foreach (string item in railsMapping)
            {
                string[] parts     = item.Split(',');
                string   railsZone = parts[0];
                string[] ianaZones = parts[1].Split();

                for (var i = 0; i < ianaZones.Length; i++)
                {
                    string ianaZone = ianaZones[i];
                    if (i == 0)
                    {
                        railsMap.Add(railsZone, ianaZone);
                    }
                    else
                    {
                        inverseRailsMap.Add(ianaZone, new[] { railsZone });
                    }
                }
            }

            foreach (IGrouping <string, string> grouping in railsMap.GroupBy(x => x.Value, x => x.Key))
            {
                inverseRailsMap.Add(grouping.Key, grouping.ToList());
            }

            // Expand the Inverse Rails map to include similar IANA zones
            foreach (string ianaZone in ianaMap.Keys)
            {
                if (inverseRailsMap.ContainsKey(ianaZone) || links.ContainsKey(ianaZone))
                {
                    continue;
                }

                if (similarIanaZones.TryGetValue(ianaZone, out IList <string> similarZones))
                {
                    foreach (string otherZone in similarZones)
                    {
                        if (inverseRailsMap.TryGetValue(otherZone, out IList <string> railsZones))
                        {
                            inverseRailsMap.Add(ianaZone, railsZones);
                            break;
                        }
                    }
                }
            }

            // Expand the Inverse Rails map to include links (in either direction)
            foreach (KeyValuePair <string, string> link in links)
            {
                if (!inverseRailsMap.ContainsKey(link.Key))
                {
                    if (inverseRailsMap.TryGetValue(link.Value, out IList <string> railsZone))
                    {
                        inverseRailsMap.Add(link.Key, railsZone);
                    }
                }
                else if (!inverseRailsMap.ContainsKey(link.Value))
                {
                    if (inverseRailsMap.TryGetValue(link.Key, out IList <string> railsZone))
                    {
                        inverseRailsMap.Add(link.Value, railsZone);
                    }
                }
            }

            // Expand the Inverse Rails map to use CLDR golden zones
            foreach (string ianaZone in ianaMap.Keys)
            {
                if (!inverseRailsMap.ContainsKey(ianaZone))
                {
                    if (ianaMap.TryGetValue(ianaZone, out string windowsZone))
                    {
                        if (windowsMap.TryGetValue("001|" + windowsZone, out string goldenZone))
                        {
                            if (inverseRailsMap.TryGetValue(goldenZone, out IList <string> railsZones))
                            {
                                inverseRailsMap.Add(ianaZone, railsZones);
                            }
                        }
                    }
                }
            }
        }
Example #22
0
        public static void Populate(IDictionary <string, string> ianaMap, IDictionary <string, string> windowsMap, IDictionary <string, string> railsMap, IDictionary <string, IList <string> > inverseRailsMap)
        {
            var mapping      = GetEmbeddedData("Adhan.Test.TimeZoneConverter.Mapping.csv.gz");
            var aliases      = GetEmbeddedData("Adhan.Test.TimeZoneConverter.Aliases.csv.gz");
            var railsMapping = GetEmbeddedData("Adhan.Test.TimeZoneConverter.RailsMapping.csv.gz");

            var links = new Dictionary <string, string>();

            foreach (var link in aliases)
            {
                var parts = link.Split(',');
                var value = parts[0];
                foreach (var key in parts[1].Split())
                {
                    links.Add(key, value);
                }
            }

            var similarIanaZones = new Dictionary <string, IList <string> >();

            foreach (var item in mapping)
            {
                var parts       = item.Split(',');
                var windowsZone = parts[0];
                var territory   = parts[1];
                var ianaZones   = parts[2].Split();

                // Create the Windows map entry
                if (!links.TryGetValue(ianaZones[0], out var value))
                {
                    value = ianaZones[0];
                }

                var key = $"{territory}|{windowsZone}";
                windowsMap.Add(key, value);

                // Create the IANA map entries
                foreach (var ianaZone in ianaZones)
                {
                    if (!ianaMap.ContainsKey(ianaZone))
                    {
                        ianaMap.Add(ianaZone, windowsZone);
                    }
                }

                if (ianaZones.Length > 1)
                {
                    foreach (var ianaZone in ianaZones)
                    {
                        similarIanaZones.Add(ianaZone, ianaZones.Except(new[] { ianaZone }).ToArray());
                    }
                }
            }

            // Expand the IANA map to include all links
            foreach (var link in links)
            {
                if (ianaMap.ContainsKey(link.Key))
                {
                    continue;
                }

                ianaMap.Add(link.Key, ianaMap[link.Value]);
            }

            foreach (var item in railsMapping)
            {
                var parts     = item.Split(',');
                var railsZone = parts[0].Trim('"');
                var ianaZone  = parts[1].Trim('"');
                railsMap.Add(railsZone, ianaZone);
            }

            foreach (var grouping in railsMap.GroupBy(x => x.Value, x => x.Key))
            {
                inverseRailsMap.Add(grouping.Key, grouping.ToList());
            }

            // Expand the Inverse Rails map to include similar IANA zones
            foreach (var ianaZone in ianaMap.Keys)
            {
                if (inverseRailsMap.ContainsKey(ianaZone) || links.ContainsKey(ianaZone))
                {
                    continue;
                }

                if (similarIanaZones.TryGetValue(ianaZone, out var similarZones))
                {
                    foreach (var otherZone in similarZones)
                    {
                        if (inverseRailsMap.TryGetValue(otherZone, out var railsZones))
                        {
                            inverseRailsMap.Add(ianaZone, railsZones);
                            break;
                        }
                    }
                }
            }

            // Expand the Inverse Rails map to include links
            foreach (var link in links)
            {
                if (inverseRailsMap.ContainsKey(link.Key))
                {
                    continue;
                }

                if (inverseRailsMap.TryGetValue(link.Value, out var railsZone))
                {
                    inverseRailsMap.Add(link.Key, railsZone);
                }
            }
        }
Example #23
0
 public static void AddCondidates(TextBox textBox, IDictionary<string, object> dict)
 {
     var dict2 = AutoComplete.GetCandidates(textBox);
     foreach(var grp in dict.GroupBy(pair => pair.Key, pair => pair, StringComparer.OrdinalIgnoreCase)){
         dict2.Add(grp.Key, grp.ToArray());
     }
 }
 public static double[] GetOpNodeProbabilities(IDictionary<Operator, double> operatorAndProbabilityMap)
 {
     return operatorAndProbabilityMap
         .GroupBy(e => e.Key.Arity)
         .Where(g => g.Key > 0)
         .OrderBy(g => g.Key)
         .Select(g => g.Sum(e => e.Value))
         .Where(p => p > 0)
         .ToArray();
 }
Example #25
0
 public IEnumerable <TextPosition> GetRepeatingFolds(IDictionary <TextPosition, TextPosition> folds) =>
 folds.GroupBy(pair => pair.Key.Line)
 .Where(group => group.Count() > 1)
 .SelectMany(group => group)
 .Select(pair => pair.Key);
Example #26
0
        public static void PrintResult(IDictionary <string, PlatformResult> dict)
        {
            if (dict.All(it => it.Value.Result != null))
            {
                if (AppVeyor)
                {
                    PostTestResultToAppveyor(dict);
                }

                var result = dict.Select(it => it.Value.Result).First();
                if (TeamCity)
                {
                    Console.WriteLine("##teamcity[testStarted name='{2}.{1}.{0}' captureStandardOutput='true']",
                                      result.Test.Name.TeamCityEncode(),
                                      result.Test.Fixture.Name.TeamCityEncode(),
                                      result.Test.Fixture.Assembly.Name.TeamCityEncode());
                }
                else if (Verbose)
                {
                    Console.Write(result.Test.Fixture.Assembly.Name + ".");
                    Console.Write(result.Test.Fixture.Name + ".");
                }
                if (TeamCity || Verbose)
                {
                    Console.WriteLine(result.Test.Name);
                }
                foreach (var grpResult in dict.GroupBy(it => it.Value.Result.Kind))
                {
                    if (Verbose || TeamCity)
                    {
                        Console.Write("{0}:", grpResult.Key);
                        foreach (var keyValuePair in grpResult)
                        {
                            Console.Write(" ");
                            Console.Write(keyValuePair.Value.Platform);
                        }
                    }
                    if (TeamCity)
                    {
                        switch (grpResult.Key)
                        {
                        case ResultKind.Fail:
                        case ResultKind.Error:
                            Console.WriteLine(
                                "##teamcity[testFailed name='{2}.{1}.{0}' message='See log or details']",
                                result.Test.Name.TeamCityEncode(),
                                result.Test.Fixture.Name.TeamCityEncode(),
                                result.Test.Fixture.Assembly.Name.TeamCityEncode());
                            break;

                        case ResultKind.Ignore:
                            Console.WriteLine(
                                "##teamcity[testIgnored name='{2}.{1}.{0}' message='See log or details']",
                                result.Test.Name.TeamCityEncode(),
                                result.Test.Fixture.Name.TeamCityEncode(),
                                result.Test.Fixture.Assembly.Name.TeamCityEncode());
                            break;
                        }
                    }
                    if (Verbose || TeamCity)
                    {
                        Console.WriteLine();
                    }
                }
                if (Verbose || TeamCity)
                {
                    var span = new TimeSpan();
                    foreach (var r in dict.Select(it => it.Value.Result))
                    {
                        span += (r.EndTime - r.StartTime);
                    }
                    Console.WriteLine("avg time:{0}", new TimeSpan(span.Ticks / dict.Count));
                }

                if (Verbose || TeamCity)
                {
                    foreach (var lup in dict.ToLookup(it => it.Value.Result.Output))
                    {
                        var name = String.Join(",", lup.Select(it => it.Value.Platform));

                        Console.WriteLine("{0}:", name);
                        Console.WriteLine(lup.Key);
                    }
                }

                if (TeamCity)
                {
                    Console.WriteLine("##teamcity[testFinished name='{2}.{1}.{0}' duration='{3}']",
                                      result.Test.Name.TeamCityEncode(),
                                      result.Test.Fixture.Name.TeamCityEncode(),
                                      result.Test.Fixture.Assembly.Name.TeamCityEncode(),
                                      (result.EndTime - result.StartTime).TotalMilliseconds);
                }
                else
                {
                    if (dict.Any(it => it.Value.Result.Kind == ResultKind.Fail))
                    {
                        if (Verbose)
                        {
                            Console.WriteLine("!!!!!!!!!!!!!!!!!!!!!!!!!");
                        }
                        else if (dict.All(it => it.Value.Result.Kind == ResultKind.Fail))
                        {
                            Console.Write("!  ");
                        }
                        else
                        {
                            Console.Write("!{0} ", dict.Where(it => it.Value.Result.Kind == ResultKind.Fail).Count());
                        }
                    }
                    else if (dict.Any(it => it.Value.Result.Kind == ResultKind.Error))
                    {
                        if (Verbose)
                        {
                            Console.WriteLine("EEEEEEEEEEEEEEEEEEEEEEEEE");
                        }
                        else if (dict.All(it => it.Value.Result.Kind == ResultKind.Error))
                        {
                            Console.Write("E  ");
                        }
                        else
                        {
                            Console.Write("E{0} ", dict.Where(it => it.Value.Result.Kind == ResultKind.Error).Count());
                        }
                    }
                    else if (dict.Any(it => it.Value.Result.Kind == ResultKind.Ignore))
                    {
                        if (Verbose)
                        {
                            Console.WriteLine("?????????????????????????");
                        }
                        else if (dict.All(it => it.Value.Result.Kind == ResultKind.Ignore))
                        {
                            Console.Write("?  ");
                        }
                        else
                        {
                            Console.Write("?{0} ", dict.Where(it => it.Value.Result.Kind == ResultKind.Ignore).Count());
                        }
                    }
                    else if (dict.All(it => it.Value.Result.Kind == ResultKind.Success))
                    {
                        if (Verbose)
                        {
                            Console.WriteLine("-------------------------");
                        }
                        else
                        {
                            Console.Write(".  ");
                        }
                    }
                    else
                    {
                        if (Verbose)
                        {
                            Console.WriteLine(".........................");
                        }
                        else if (dict.All(it => it.Value.Result.Kind == ResultKind.NoError))
                        {
                            Console.Write("_  ");
                        }
                        else
                        {
                            Console.Write("_{0} ", dict.Where(it => it.Value.Result.Kind == ResultKind.NoError).Count());
                        }
                    }
                    if (Verbose || ++_resultCount % 26 == 0)
                    {
                        Console.WriteLine(String.Empty);
                    }
                }
            }
        }
Example #27
0
        public static void PrintResult(IDictionary<string, PlatformResult> dict)
        {
            if (dict.All(it => it.Value.Result != null))
            {

                if (AppVeyor)
                {
                    PostTestResultToAppveyor(dict);
                }

                var result = dict.Select(it => it.Value.Result).First();
                if (TeamCity)
                {
                    Console.WriteLine("##teamcity[testStarted name='{2}.{1}.{0}' captureStandardOutput='true']",
                                      result.Test.Name.TeamCityEncode(),
                                      result.Test.Fixture.Name.TeamCityEncode(),
                                      result.Test.Fixture.Assembly.Name.TeamCityEncode());
                }
                else if(Verbose)
                {
                    Console.Write(result.Test.Fixture.Assembly.Name + ".");
                    Console.Write(result.Test.Fixture.Name + ".");
                }
                if (TeamCity || Verbose) {
                  Console.WriteLine (result.Test.Name);
                }
                foreach (var grpResult in dict.GroupBy(it => it.Value.Result.Kind))
                {
                  if (Verbose || TeamCity) {
                    Console.Write ("{0}:", grpResult.Key);
                    foreach (var keyValuePair in grpResult) {
                      Console.Write (" ");
                      Console.Write (keyValuePair.Value.Platform);
                    }
                  }
                    if (TeamCity)
                    {
                        switch (grpResult.Key)
                        {
                            case ResultKind.Fail:
                            case ResultKind.Error:
                                Console.WriteLine(
                                    "##teamcity[testFailed name='{2}.{1}.{0}' message='See log or details']",
                                      result.Test.Name.TeamCityEncode(),
                                      result.Test.Fixture.Name.TeamCityEncode(),
                                      result.Test.Fixture.Assembly.Name.TeamCityEncode());
                                break;
                            case ResultKind.Ignore:
                                Console.WriteLine(
                                    "##teamcity[testIgnored name='{2}.{1}.{0}' message='See log or details']",
                                      result.Test.Name.TeamCityEncode(),
                                      result.Test.Fixture.Name.TeamCityEncode(),
                                      result.Test.Fixture.Assembly.Name.TeamCityEncode());
                                break;
                        }

                    }
                  if (Verbose || TeamCity) {
                    Console.WriteLine ();
                  }
                }
            if (Verbose || TeamCity) {
              var span = new TimeSpan ();
              foreach (var r in dict.Select(it => it.Value.Result)) {
            span += (r.EndTime - r.StartTime);
              }
              Console.WriteLine ("avg time:{0}", new TimeSpan (span.Ticks / dict.Count));
            }

            if (Verbose || TeamCity) {

                    foreach (var lup in dict.ToLookup(it => it.Value.Result.Output)) {
                        var name = String.Join (",", lup.Select (it => it.Value.Platform));

                        Console.WriteLine ("{0}:", name);
                        Console.WriteLine (lup.Key);
                    }
                }

                if (TeamCity)
                {
                    Console.WriteLine("##teamcity[testFinished name='{2}.{1}.{0}' duration='{3}']",
                         result.Test.Name.TeamCityEncode(),
                         result.Test.Fixture.Name.TeamCityEncode(),
                         result.Test.Fixture.Assembly.Name.TeamCityEncode(),
                        (result.EndTime - result.StartTime).TotalMilliseconds);
                }
                else
                {

                    if (dict.Any(it => it.Value.Result.Kind == ResultKind.Fail))
                    {
                        if (Verbose)
                            Console.WriteLine ("!!!!!!!!!!!!!!!!!!!!!!!!!");
                        else if (dict.All(it => it.Value.Result.Kind == ResultKind.Fail))
                            Console.Write("!  ");
                        else
                            Console.Write ("!{0} ", dict.Where (it => it.Value.Result.Kind == ResultKind.Fail).Count ());
                    }
                    else if (dict.Any(it => it.Value.Result.Kind == ResultKind.Error))
                    {
                        if (Verbose)
                            Console.WriteLine("EEEEEEEEEEEEEEEEEEEEEEEEE");
                        else if (dict.All(it => it.Value.Result.Kind == ResultKind.Error))
                            Console.Write("E  ");
                        else
                            Console.Write ("E{0} ", dict.Where (it => it.Value.Result.Kind == ResultKind.Error).Count ());

                    }
                    else if (dict.Any(it => it.Value.Result.Kind == ResultKind.Ignore))
                    {
                        if (Verbose)
                            Console.WriteLine("?????????????????????????");
                        else if (dict.All(it => it.Value.Result.Kind == ResultKind.Ignore))
                            Console.Write("?  ");
                        else
                            Console.Write ("?{0} ", dict.Where (it => it.Value.Result.Kind == ResultKind.Ignore).Count ());
                    }
                    else if (dict.All(it => it.Value.Result.Kind == ResultKind.Success))
                    {
                        if (Verbose)
                            Console.WriteLine("-------------------------");
                        else
                            Console.Write(".  ");
                    }
                    else
                    {
                        if (Verbose)
                            Console.WriteLine (".........................");
                        else if (dict.All (it => it.Value.Result.Kind == ResultKind.NoError))
                            Console.Write ("_  ");
                        else
                            Console.Write ("_{0} ", dict.Where (it => it.Value.Result.Kind == ResultKind.NoError).Count ());
                    }
                    if (Verbose || ++_resultCount % 26 == 0 )
                        Console.WriteLine(String.Empty);

                }
            }
        }
Example #28
0
 public static IDictionary <TValue, TKey> ReverseDictionary <TKey, TValue>(this IDictionary <TKey, TValue> dict)
 {
     return(dict.GroupBy(p => p.Value)
            .ToDictionary(g => g.Key, g => g.Select(pp => pp.Key).FirstOrDefault()));
 }
 public IEnumerable<TextPosition> GetRepeatingFolds(IDictionary<TextPosition, TextPosition> folds) =>
     folds.GroupBy(pair => pair.Key.Line)
          .Where(group => group.Count() > 1)
          .SelectMany(group => group)
          .Select(pair => pair.Key);
 protected override IEnumerable <IGrouping <string, KeyValuePair <string, string> > > GroupProperties(IDictionary <string, string> properties)
 {
     return(properties.GroupBy(x => x.Key));
 }
Example #31
0
 public IEnumerable <IGrouping <IScoreRetrievalService, string> > GetBackendNames() => _backendsByName.GroupBy(x => x.Value, x => x.Key);
        public void Write(IDictionary<Channel, double[]> output)
        {
            var ns = output.Values.Select(v => v.Count()).Distinct().ToList();
            if (ns.Count() > 1)
                throw new ArgumentException("Preload sample buffers must be homogenous in length");
            int nsamples = ns.First();

            var groups = output.GroupBy(kv => kv.Key.Type).ToDictionary(g => g.Key, g => g.ToDictionary(kv => kv.Key, kv => kv.Value));

            var tasks = new List<Task>();

            if (groups.ContainsKey(ChannelType.AO))
                tasks.Add(Task.Factory.StartNew(() => WriteAnalog(groups[ChannelType.AO], nsamples)));
            if (groups.ContainsKey(ChannelType.DO))
                tasks.Add(Task.Factory.StartNew(() => WriteDigital(groups[ChannelType.DO], nsamples)));

            Task.WaitAll(tasks.ToArray());

            foreach (var task in tasks)
            {
                if (task.IsFaulted)
                    throw task.Exception;
            }
        }
Example #33
0
 public static IEnumerable <string> GetDupeKeys <T>(this IDictionary <string, T> list)
 {
     return(list.GroupBy(x => x.Key)
            .Where(group => group.Count() > 1).Select(a => a.Key));
 }
 /// <summary>
 /// Saves a template file which is a all strings (needing translation) used in the entire project. Not language dependent
 /// </summary>
 /// <param name="items">A list of template items to save. The list should be all template items for the entire project.</param>
 public void SaveTemplate(IDictionary<string, TemplateItem> items)
 {
     if (_settings.GenerateTemplatePerFile)
     {
         foreach (var item in items.GroupBy(x => x.Value.FileName))
         {
             SaveTemplate(item.ToDictionary(x => x.Key, x => x.Value), item.Key);
         }
     }
     else
     {
         SaveTemplate(items, string.Empty);
     }
 }