示例#1
0
 /// <summary>
 /// 获取合并的数据。
 /// </summary>
 /// <typeparam name="TRight"></typeparam>
 /// <typeparam name="TLeft"></typeparam>
 /// <typeparam name="TKey"></typeparam>
 /// <param name="lefts"></param>
 /// <param name="leftKeyCreator">从集合的元素中提取key,key不可重复。</param>
 /// <param name="rights"></param>
 /// <param name="rightKeyCreator">从集合的元素中提取key,key不可重复。</param>
 /// <param name="leftOnly">应移除的对象,null则忽略此参数。</param>
 /// <param name="rightOnly">应增加的对象,null则忽略此参数。</param>
 /// <param name="overlaps">应修改的对象,null则忽略此参数。</param>
 /// <param name="compare">若省略或为null,则使用默认比较器。当前版本保留未用,可忽略。</param>
 /// <exception cref="ArgumentException">从集合的元素中提取key,key不可重复。</exception>
 public static void GetMergeInfo<TLeft, TRight, TKey>(this IEnumerable<TLeft> lefts, Func<TLeft, TKey> leftKeyCreator, IEnumerable<TRight> rights, Func<TRight, TKey> rightKeyCreator,
     ICollection<TLeft> leftOnly, ICollection<TRight> rightOnly, ICollection<Tuple<TRight, TLeft>> overlaps, IComparer<TKey> compare = null)
 {
     if (null == compare)
         compare = Comparer<TKey>.Default;
     var intersectKeys = lefts.Join(rights, leftKeyCreator, rightKeyCreator, (dest, src) => Tuple.Create(src, dest)).ToDictionary(c => leftKeyCreator(c.Item2));  //重合的key集合
     overlaps?.AddRange(intersectKeys.Values);  //生成更新对象集合
     leftOnly?.AddRange(lefts.Where(c => !intersectKeys.ContainsKey(leftKeyCreator(c)))); //生成删除对象集合
     rightOnly?.AddRange(rights.Where(c => !intersectKeys.ContainsKey(rightKeyCreator(c))));   //生成追加对象集合
 }
        public void AddRange_requires_the_collection()
        {
            // Arrange
            ICollection <int> list        = Enumerable.Range(3, 3).ToList();
            IEnumerable <int> newElements = null;
            Action            action      = () => list.AddRange(newElements);

            // Act
            // Assert
            action.Should().Throw <ArgumentNullException>();
        }
        public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items, Func<T, bool> predicate)
        {
            if (collection == null)
                throw new ArgumentNullException(nameof(collection));
            if (predicate == null)
                throw new ArgumentNullException(nameof(predicate));
            if (items == null)
                return;

            collection.AddRange(items.Where(predicate));
        }
示例#4
0
        /// <summary>
        ///     Set the list to a range of items
        /// </summary>
        /// <typeparam name="T">the type the list contains</typeparam>
        /// <param name="list">the destination list</param>
        /// <param name="itemsToAdd">the source list</param>
        public static void SetRange <T>(this ICollection <T> list, IEnumerable <T> itemsToAdd)
        {
            if (list == null)
            {
                throw new ArgumentNullException(nameof(list));
            }

            list.Clear();

            list.AddRange(itemsToAdd);
        }
        /// <summary>
        /// Maps a collection of <typeparamref name="TFrom"/> into a list of <typeparamref name="TTo"/>.
        /// </summary>
        /// <typeparam name="TFrom">The type of the source objects.</typeparam>
        /// <typeparam name="TTo">The type of the destination objects.</typeparam>
        /// <param name="mapper">The mapper.</param>
        /// <param name="from">The source collection.</param>
        /// <param name="to">The destination collection.</param>
        /// <returns>A list of <typeparamref name="TTo"/>.</returns>
        public static void MapCollection <TFrom, TTo>(this IMapper <TFrom, TTo> mapper, IEnumerable <TFrom> from, ICollection <TTo> to)
            where TFrom : class
            where TTo : class, new()
        {
            Guard.NotNull(mapper, nameof(mapper));
            Guard.NotNull(from, nameof(from));
            Guard.NotNull(to, nameof(to));

            to.Clear();
            to.AddRange(from.Select(x => mapper.Map <TFrom, TTo>(x)));
        }
示例#6
0
 private static ICollection <TDestination> Map <TDestination>(
     string source, ICollection <TDestination> destination,
     ResolutionContext context, ProfileMap profileMap)
 {
     if (!string.IsNullOrEmpty(source))
     {
         var values = source.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                      .Select(x => context.Mapper.Map <TDestination>(x));
         destination.AddRange(values);
     }
     return(destination);
 }
        public void CollectionExtensions_ICollection_AddRange_ThrowsIfTargetArgumentIsNull()
        {
            // Arrange
            ICollection <string> actual = null;

            // Act
            Assert.Throws <ArgumentNullException>(
                // ReSharper disable once ExpressionIsAlwaysNull test a null target
                () => actual.AddRange(new[] { "1", "2" }));

            // Assert
        }
示例#8
0
        public FSharpReferenceSearcher(IDeclaredElementsSet elements, bool findCandidates)
        {
            myElements       = new DeclaredElementsSet(elements.Where(e => !(e is IFSharpSymbolElement)));
            myFSharpSymbols  = elements.OfType <IFSharpSymbolElement>().Select(e => e.Symbol).ToIList();
            myFindCandidates = findCandidates;
            myElementNames   = new HashSet <string>();

            foreach (var element in elements)
            {
                myElementNames.AddRange(FSharpNamesUtil.GetPossibleSourceNames(element));
            }
        }
示例#9
0
        private bool ValidateMember(ICustomAttributeProvider member, ValidationContext context, ICollection<ValidationResult> results, object value)
        {
            var originalCount = results.Count;
            results.AddRange(
                attributeProvider
                    .GetAttributes(member)
                    .Select(attribute => attribute.GetValidationResult(value, context))
                    .Where(result => result != ValidationResult.Success)
            );

            return results.Count > originalCount;
        }
        /// <summary>
        /// 替换项
        /// </summary>
        /// <typeparam name="TItem">项类型</typeparam>
        /// <typeparam name="TNewItem">新项类型</typeparam>
        /// <param name="collection">集合</param>
        /// <param name="newItems">新项集合</param>
        /// <param name="createItemAction">创建项操作</param>
        public static void ReplaceItems <TItem, TNewItem>(this ICollection <TItem> collection,
                                                          IEnumerable <TNewItem> newItems, Func <TNewItem, TItem> createItemAction)
        {
            collection.CheckNotNull(nameof(collection));
            newItems.CheckNotNull(nameof(newItems));
            createItemAction.CheckNotNull(nameof(createItemAction));

            collection.Clear();
            var convertedNewItems = newItems.Select(createItemAction);

            collection.AddRange(convertedNewItems);
        }
示例#11
0
        public void Extensions_AddRange_With_Null_Source_Throws_Exception()
        {
            ICollection <int> target = Enumerable.Range(1, 10).ToList();

            // Act
            void AddFromNullCollection() => target.AddRange(null);

            // Assert
            var message = Assert.Throws <ArgumentNullException>(AddFromNullCollection).Message;

            Assert.That(message, Is.EqualTo("Value cannot be null.\r\nParameter name: source"));
        }
 /// <summary>
 /// 安全批量添加
 /// <para>微软提供的方法在添加时候会触发 ArgumentNullException</para>
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="this"></param>
 /// <param name="values"></param>
 public static void SafeAddRange <T>(this ICollection <T> @this, IEnumerable <T> values)
 {
     if (@this == null)
     {
         return;
     }
     if (values.IsInvalid())
     {
         return;
     }
     @this.AddRange <T>(values);
 }
        public void AddRange_returns_the_collection()
        {
            // Arrange
            ICollection <int> list = Enumerable.Range(0, 3).ToList();
            var newElements        = Enumerable.Range(3, 3);

            // Act
            var result = list.AddRange(newElements);

            // Assert
            result.Should().BeSameAs(list);
        }
示例#14
0
        public static void UpdateFrom <T>(this ICollection <T> changelist, IEnumerable <T> inputlist)
        {
            Contract.Requires(changelist != null);
            Contract.Requires(inputlist != null);

            var input         = inputlist.ToList(); // Memoize the input list, as we want to go through it twice
            var itemsToAdd    = input.Except(changelist).ToList();
            var itemsToRemove = changelist.Except(input).ToList();

            changelist.RemoveRange(itemsToRemove);
            changelist.AddRange(itemsToAdd);
        }
示例#15
0
        public void Extensions_AddRange_With_Null_Target_Throws_Exception()
        {
            ICollection <int> target = null;

            // Act
            Action addToNullCollection = () => target.AddRange(Enumerable.Range(1, 10));

            // Assert
            var message = Assert.Throws <ArgumentNullException>(() => addToNullCollection()).Message;

            Assert.That(message, Is.EqualTo("Value cannot be null.\r\nParameter name: target"));
        }
示例#16
0
        public static void AddRange<TDest, TSource>(this ICollection<TDest> collection, IEnumerable<TSource> items,
            Func<TSource, TDest> converter)
        {
            if (collection == null)
                throw new ArgumentNullException(nameof(collection));
            if (converter == null)
                throw new ArgumentNullException(nameof(converter));
            if (items == null)
                return;

            collection.AddRange(items.Select(converter));
        }
        public void AddRange_adds_multiple_elements()
        {
            // Arrange
            ICollection <int> list = Enumerable.Range(0, 3).ToList();
            var newElements        = Enumerable.Range(3, 3);
            var expected           = Enumerable.Range(0, 6).ToList();

            // Act
            list.AddRange(newElements);

            // Assert
            list.Should().BeEquivalentTo(expected);
        }
示例#18
0
        /// <summary>
        /// Maps a collection of <typeparamref name="TFrom"/> into a list of <typeparamref name="TTo"/>.
        /// </summary>
        /// <typeparam name="TFrom">The type of the source objects.</typeparam>
        /// <typeparam name="TTo">The type of the destination objects.</typeparam>
        /// <param name="mapper">The mapper.</param>
        /// <param name="from">The source collection.</param>
        /// <param name="to">The destination collection.</param>
        /// <param name="parameters">Custom parameters</param>
        /// <returns>A list of <typeparamref name="TTo"/>.</returns>
        public static async Task MapCollectionAsync <TFrom, TTo>(this IMapper <TFrom, TTo> mapper, IEnumerable <TFrom> from, ICollection <TTo> to, dynamic parameters = null)
            where TFrom : class
            where TTo : class, new()
        {
            Guard.NotNull(mapper, nameof(mapper));
            Guard.NotNull(from, nameof(from));
            Guard.NotNull(to, nameof(to));

            to.Clear();
            var items = await MapArrayAsync(mapper, from, (object)parameters);

            to.AddRange(items);
        }
示例#19
0
        public static void Insert <T>(this ICollection <T> collection, int index, T item)
        {
            if (index < 0 || index > collection.Count)
            {
                throw new ArgumentOutOfRangeException(nameof(index), "Index was out of range. Must be non-negative and less than the size of the collection.");
            }

            if (collection is IList <T> list)
            {
                list.Insert(index, item);
            }
            else
            {
                List <T> temp = new List <T>(collection);

                collection.Clear();

                collection.AddRange(temp.Take(index));
                collection.Add(item);
                collection.AddRange(temp.Skip(index));
            }
        }
示例#20
0
        /// <summary>
        /// Clears the current collection and replaces it with the specified collection.
        /// </summary>
        public static void ReplaceRange <T>(this ICollection <T> collection, IEnumerable <T> items)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }

            if (collection.Count > 0)
            {
                collection.Clear();
            }
            collection.AddRange(items);
        }
示例#21
0
        public static void UpdateFromOrdered <T, U>(
            this ICollection <T> changelist,
            IEnumerable <U> inputlist,
            Func <T, U> convert,
            Func <U, T> convertBack,
            Func <U, bool> conditionAdd,
            Func <T, bool> conditionRemove)
            where T : class
        {
            Contract.Requires(changelist != null);
            Contract.Requires(inputlist != null);
            Contract.Requires(convert != null);
            Contract.Requires(convertBack != null);

            // Memoize the input list, as we want to go through it twice
            var input = inputlist.ToList();

            var inputKeepAdd = input.Where(conditionAdd).GroupJoin(
                changelist,
                m => m,
                convert,
                (model, bm) => new { model, bm });

            var inputKeepRemove = changelist.GroupJoin(
                input,
                convert,
                m => m,
                (bm, model) => new { bm, model });

            // add existing binding models in order specified by model list, if binding model does not exist, create it for the corresponding model
            var itemsToAdd = inputKeepAdd.Select(ika => ika.bm.SingleOrDefault() ?? convertBack(ika.model)).ToList();

            // keep binding models which should normally be removed because they are not in model list, but for which the condition to remove the binding model evaluates to false
            var itemsToKeep = inputKeepRemove.Where(ikr => !ikr.model.Any() && !conditionRemove(ikr.bm)).Select(ikr => ikr.bm).ToList();

            changelist.Clear();
            changelist.AddRange(itemsToAdd);
            changelist.AddRange(itemsToKeep);
        }
示例#22
0
        public void Extensions_AddRange_With_Null_Target_Throws_Exception()
        {
            ICollection <int> target = null;

            // Act
            // ReSharper disable once ExpressionIsAlwaysNull
            void AddToNullCollection() => target.AddRange(Enumerable.Range(1, 10));

            // Assert
            var message = Assert.Throws <ArgumentNullException>(AddToNullCollection).Message;

            Assert.That(message, Is.EqualTo("Value cannot be null.\r\nParameter name: target"));
        }
示例#23
0
        private void PrepareGpx()
        {
            Logger.Log("Reading GPX files");

            var dirSource = File.ReadLines(@"..\..\..\Path.txt").First();

            _paths.AddRange(Directory.GetFiles(dirSource, "*.gpx").Select(ReadGpxFile));

            //File.WriteAllLines(@"C:\Users\Albert\Desktop\Nowy folder\Wavelo\stats.txt",
            //    _paths.OrderBy(p => p.Id).Select(p => p.ToString()));

            Logger.Log("");
        }
        public ThirdPartyProcessorPayment(Guid id, Guid paymentSourceId, string description, decimal totalAmount, IEnumerable <ThidPartyProcessorPaymentItem> items)
            : this()
        {
            Id = id;
            PaymentSourceId = paymentSourceId;
            Description     = description;
            TotalAmount     = totalAmount;
            Items.AddRange(items);

            AddEvent(new PaymentInitiated {
                SourceId = id, PaymentSourceId = paymentSourceId
            });
        }
示例#25
0
        /// <remarks>Similar with GetComponentsInChildren when match is null.</remarks>
        public static void FindComponentsInChildren <T>(this Transform self,
                                                        ICollection <T> result, Func <T, bool> match = null, bool findInSelf = true)
            where T : Component
        {
            Ensure.Argument.NotNull(self, nameof(self));
            Ensure.Argument.NotNull(result, "result");

            if (findInSelf)
            {
                result.AddRange(FindComponents(self, match));
            }

            for (int i = 0; i < self.childCount; ++i)
            {
                var child = self.GetChild(i);
                if (!findInSelf)
                {
                    result.AddRange(FindComponents(child, match));
                }
                FindComponentsInChildren(child, result, match, findInSelf);
            }
        }
示例#26
0
        private void BuildMarkCollections(ICollection <IMarkCollection> markCollection,
                                          BeatBarSettingsData settings)
        {
            List <MarkCollection> retVal = new List <MarkCollection>();

            m_featureSet = GenerateFeatures(m_plugin, m_fSamplesAll);
            String[] beatCollectionNames  = settings.BeatCollectionNames(false);
            String[] splitCollectionNames = settings.BeatCollectionNames(true);

            if (settings.BarsEnabled)
            {
                markCollection.RemoveAll(x => x.Name.Equals(settings.BarsCollectionName));
                var mc = ExtractBarMarksFromFeatureSet(m_featureSet[1], settings);
                mc.Decorator.Color = settings.BarsColor;
                retVal.Add(mc);
            }

            if (settings.BeatCollectionsEnabled)
            {
                foreach (String name in beatCollectionNames)
                {
                    markCollection.RemoveAll(x => x.Name.Equals(name));
                }
                List <MarkCollection> mcl = ExtractBeatCollectionsFromFeatureSet(m_featureSet[2], settings, retVal);
                mcl.ForEach(x => x.Decorator.Color = settings.BeatCountsColor);
                retVal.AddRange(mcl);
            }

            if (settings.BeatSplitsEnabled)
            {
                foreach (String name in splitCollectionNames)
                {
                    markCollection.RemoveAll(x => x.Name.Equals(name));
                }
                List <MarkCollection> mcl = ExtractSplitCollectionsFromFeatureSet(m_featureSet[2], settings, retVal);
                mcl.ForEach(x => x.Decorator.Color = settings.BeatSplitsColor);
                retVal.AddRange(mcl);
            }

            if (settings.AllFeaturesEnabled)
            {
                markCollection.RemoveAll(x => x.Name.Equals(settings.AllCollectionName));
                MarkCollection mc = ExtractAllMarksFromFeatureSet(m_featureSet[0], settings);
                mc.Decorator.Color = settings.AllFeaturesColor;
                retVal.Add(mc);
            }

            retVal.RemoveAll(x => x.Marks.Count == 0);

            markCollection.AddRange(retVal.OrderBy(x => x.Name));
        }
示例#27
0
        static public int PartOut <T>(this IEnumerable <IEnumerable <T> > item, ICollection <T> output1, ICollection <T> output2, ICollection <T> output3, ICollection <T> output4, ICollection <T> output5, ICollection <T> output6, ICollection <T> output7)
        {
            output1.Clear();
            output2.Clear();
            output3.Clear();
            output4.Clear();
            output5.Clear();
            output6.Clear();
            output7.Clear();

            using (IEnumerator <IEnumerable <T> > iterator = item.GetEnumerator())
            {
                if (iterator.MoveNext())
                {
                    output1.AddRange(iterator.Current);
                    if (iterator.MoveNext())
                    {
                        output2.AddRange(iterator.Current);
                        if (iterator.MoveNext())
                        {
                            output3.AddRange(iterator.Current);
                            if (iterator.MoveNext())
                            {
                                output4.AddRange(iterator.Current);
                                if (iterator.MoveNext())
                                {
                                    output5.AddRange(iterator.Current);
                                    if (iterator.MoveNext())
                                    {
                                        output6.AddRange(iterator.Current);
                                        if (iterator.MoveNext())
                                        {
                                            output7.AddRange(iterator.Current);
                                            return(7);
                                        }
                                        return(6);
                                    }
                                    return(5);
                                }
                                return(4);
                            }
                            return(3);
                        }
                        return(2);
                    }
                    return(1);
                }
            }

            return(0);
        }
示例#28
0
 public static ICollection <T> GetComponentsInScenes <T>([NotNull] this IEnumerable <Scene> scenes, ICollection <T> collection = null)
 {
     if (scenes == null)
     {
         throw new ArgumentNullException(nameof(scenes));
     }
     collection?.Clear();
     collection = collection ?? new List <T>();
     foreach (var scene in scenes)
     {
         collection.AddRange(scene.GetComponentsInScene <T>());
     }
     return(collection);
 }
示例#29
0
        public static void Reset <T>(this ICollection <T> collection, params T[] items)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            collection.Clear();
            collection.AddRange(items);
        }
        public static void CopyTo <T>(this IEnumerable <T> sourceCollection, ICollection <T> targetCollection)
        {
            if (sourceCollection is null)
            {
                throw new ArgumentNullException(nameof(sourceCollection));
            }
            if (targetCollection is null)
            {
                throw new ArgumentNullException(nameof(targetCollection));
            }

            targetCollection.Clear();
            targetCollection.AddRange(sourceCollection);
        }
示例#31
0
        public void AddRangeTest(ICollection <object> collection)
        {
            var count  = collection?.Count ?? 0;
            var result = collection.AddRange(new object[] { 7, 8, 9 }.ToList());

            if (collection == null)
            {
                result.Should().BeNull();
            }
            else
            {
                result.Count().Should().Be(count + 3);
            }
        }
示例#32
0
        /// <summary>
        /// Determines whether the specified object is valid using the validation context,
        /// validation results collection, and a value that specifies whether to validate
        /// all properties.
        /// </summary>
        /// <param name="instance">The object to validate.</param>
        /// <param name="validationContext">The context that describes the object to validate.</param>
        /// <param name="validationResults">A collection to hold each failed validation.</param>
        /// <param name="validateAllProperties">True to validate all properties; if false, only required attributes are validated.</param>
        /// <returns>True if the object validates; otherwise, false.</returns>
        public virtual bool TryValidateObject( object instance, IValidationContext validationContext, ICollection<IValidationResult> validationResults, bool validateAllProperties )
        {
            Arg.NotNull( instance, nameof( instance ) );
            Arg.NotNull( validationContext, nameof( validationContext ) );

            ValidationContext context;

            if ( !validationContext.TryGetService( out context ) )
                return true;

            var results = new List<ValidationResult>();
            var valid = Validator.TryValidateObject( instance, context, results, validateAllProperties );

            if ( validationResults != null )
                validationResults.AddRange( results.Select( r => new ValidationResultAdapter( r ) ) );

            return valid;
        }
        private async Task GetItems(ICollection<Bookmark> items, int pageNumber, DateTime? dateSince)
        {
            while (true)
            {
                var articles = await _readabilityClient.GetBookmarksAsync(new Conditions { AddedSince = dateSince, Page = pageNumber, PerPage = 50 });
                if (articles == null)
                {
                    return;
                }

                items.AddRange(articles.Bookmarks);

                if (items.Count > Constants.MaxArticleCount)
                {
                    break;
                }

                if (items.Count < articles.Meta.ItemCountTotal)
                {
                    pageNumber = pageNumber + 1;
                    continue;
                }
                break;
            }
        }
示例#34
0
 private void AddEmailAddresses(string addresses, ICollection<EmailAddress> target)
 {
     var arr = addresses.IsEmpty() ? null : addresses.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
     if (arr != null && arr.Length > 0)
     {
         target.AddRange(arr.Where(x => x.Trim().HasValue()).Select(x => new EmailAddress(x)));
     }
 }
示例#35
0
 private void DownloadAssets(ICollection<string> files, string file, MXUIView view)
 {
     view.buttons.ForEach(o => DownloadAssets(files, file, o));
     view.layers.ForEach(o => DownloadAssets(files, file, o));
     view.sliders.ForEach(o => DownloadAssets(files, file, o));
     view.subviews.ForEach(o => DownloadAssets(files, file, o));
     var gallery = view as MXUIGallery;
     if (gallery != null) {
         MXUIView galleryButtonGroup = gallery.subviews.SingleOrDefault(v => v.layerInfo.name == "gallery_button_group");
         if (galleryButtonGroup != null) { // can be null for deleted scene module
             string dir = _context.Config.SecondScreenAssetBase;
             IEnumerable<MXUIButton> galleryInfoButtons = galleryButtonGroup.buttons.Where(b => b.layerInfo.name.Contains("info"));
             IEnumerable<string> infoImageNames = galleryInfoButtons.Select(b => b.layerInfo.name.Split('_').Take(3).JoinString("_"));
             files.AddRange(infoImageNames.Select(name => dir + name + "_info_segment.mxcsi"));
         }
     }
     var flipbook = view as MXUIFlipbook;
     if (flipbook != null) {
         string eventId = new Regex(@"^(IS_\d+)_flipbook$").Match(file).Groups[1].Value;
         for (int i = 0; i < flipbook.sequenceCount; i++)
             files.Add(_context.Config.FlipbookBase + eventId + "_FB_" + i + ".swf");
     }
     var video = view as MXUIVideo;
     if (video != null) {
         files.Add(_context.Config.VideoBase + video.filename);
     }
 }
示例#36
0
 /// <summary>
 /// Score the race.
 /// </summary>
 public virtual void ComputeScore()
 {
     if(IsScored || Results.Count == 0)
     {
         return;
     }
     ScoresCollection = new List<TeamScore>();
     IDictionary<Team, TeamScore> scores = new Dictionary<Team, TeamScore>();
     IEnumerable<Team> teams = (from result in Results.Values
                               where result.Team != null
                               select result.Team).Distinct();
     foreach(Team team in teams)
     {
         scores[team] = new TeamScore(this, team);
     }
     // Add the runners to the school
     // Sort the results
     IEnumerable<Performance> results = Results.Values.Sorted();
     foreach(Performance result in results.Where(r => r.Team != null))
     {
         result.Points = 0;
         scores[result.Team].AddRunner(result);
     }
     //Tag runners on teams with fewer than five as scoreless
     //Tag runner 8 and beyond on each team as scorelss
     foreach(TeamScore score in scores.Values)
     {
         int runnerCount = score.Runners.Count();
         IEnumerable<Performance> scorelessRunners = Enumerable.Empty<Performance>();
         if(runnerCount < 5)
         {
             scorelessRunners = score.Runners;
         }
         else if(runnerCount > 7)
         {
             scorelessRunners = score.Runners.Skip(7);
         }
         foreach(Performance runner in scorelessRunners)
         {
             runner.Points = null;
         }
     }
     // Tag first runner on a complete team with a score as the winner
     Performance firstRunnerOnCompleteTeam = results.FirstOrDefault(r => r.HasPoints);
     if(firstRunnerOnCompleteTeam == default(Performance))
     {
         return;
     }
     firstRunnerOnCompleteTeam.Points = 1;
     // Tag each runner with their points
     results.Where(result => result.HasPoints)
            .ForEachIndexedPair(2, (previous, runner, points) =>
     {
         if(runner.Time != previous.Time)
         {
             runner.Points = points;
         }
         else
         {
             runner.Points = previous.Points;
         }
     });
     // Create the final list
     ScoresCollection.Clear();
     ScoresCollection.AddRange(scores.Values.Sorted());
     IsScored = true;
 }
        /// <summary>
        /// A helper function for sortReplies, adds a hash of (word count -> triggers vector) to the * running sort buffer.
        /// </summary>
        /// <param name="vector"></param>
        /// <param name="hash"></param>
        /// <returns></returns>
        private ICollection<string> addSortedList(ICollection<string> vector, IDictionary<int, ICollection<string>> hash)
        {
            // We've been given a hash where the keys are integers (word counts) and
            // the values are all triggers with that number of words in them (where
            // words are things that aren't wildcards).

            //Sort the hash by its number of words, descendins
            var sortedKeys = Util.SortKeysDesc(hash);

            for (int i = 0; i < sortedKeys.Length; i++)
            {
                var itens = hash[sortedKeys[i]].ToArray();
                vector.AddRange(itens);
            }

            return vector;
        }
 /// <summary>
 /// A helper function for sortReplies, adds a vector of wildcard triggers to the running sort buffer.
 /// </summary>
 /// <param name="vector"></param>
 /// <param name="wc"></param>
 /// <returns></returns>
 private ICollection<string> addSortedList(ICollection<string> vector, ICollection<string> wc)
 {
     var itens = Util.SortByLengthDesc(wc.ToArray());
     vector.AddRange(itens);
     return vector;
 }
示例#39
0
 protected override void HandleRelatedContentChildren(ICollection<IContentSpec<Content>> x) {
     // TODO: Dependencies of dependencies
     x.AddRange(
         Dependencies.Select(d => new ModRepoContentSpec(new ModRepoContent(d.ToLower(), GameId, null))));
 }
示例#40
0
        internal static RouteAttribute GetDefaults(this MethodInfo method, ICollection<OnVerbAttribute> verbs, out bool explicitRoute)
        {
            OnVerbAttribute verb = null;
            verbs.AddRange(method.GetCustomAttributes<OnVerbAttribute>(true) ?? method.DeclaringType.GetInterfaces().Select(@interface => @interface.GetCustomAttribute<OnVerbAttribute>()));
            var route = method.GetCustomAttribute<RouteAttribute>(true) ??
                method.DeclaringType.GetInterfaces().Select(@interface => @interface.GetCustomAttribute<RouteAttribute>()).FirstOrDefault();
            explicitRoute = (route != null);
            if ((route == null) || (!verbs.Any()))
            {
                method.ObtainMethodDetailsFromVerbs(ref route, ref verb);
                if (verb != null)
                {
                    verbs.Add(verb);
                    verb = null;
                }
            }

            if ((route == null) || (!verbs.Any()))
            {
                method.ObtainMethodDetailsFromPopularNames(ref route, ref verb);
                if (verb != null)
                {
                    verbs.Add(verb);
                }
            }

            if (route == null)
            {
                route = new RouteAttribute(method.Name.ToLower());
            }

            if (!verbs.Any())
            {
                verbs.Add(new OnVerbAttribute(Verb.GET));
            }

            return route;
        }
        private async Task ProcessCheck(bool noCheckout, bool skipWhenFileMatches, IReadOnlyCollection<Package> packages,
            ICollection<Package> syncedPackages, Package.ObjectMap[] objectsToFetch) {
            StatusRepo.Reset(RepoStatus.CheckOut, packages.Count);
            var i = 0;
            syncedPackages.AddRange(packages);
            var components = packages.Select(x => new ProgressLeaf(x.MetaData.Name)).ToArray();
            if (!noCheckout) {
                foreach (var package in packages) {
                    var p = components[i++];
                    await p.Do(() => ProcessPackageInternal(package, p)).ConfigureAwait(false);
                }
            }

            if (!noCheckout && skipWhenFileMatches) {
                Repo.DeleteObject(objectsToFetch.Select(x => new ObjectInfo(x.FO.Checksum, x.FO.Checksum)));
                // nasty using checksum for packed checksum or ? not needed here anyway??
            }
        }