Example #1
1
        public Span Handle(IList<Token> tokens, Options options)
        {
            RepeaterMonthName month = null;
            int day = 0;
            IList<Token> remainingTokens = null;
            if (tokens.Count > 3)
            {
                month = tokens[2].GetTag<RepeaterMonthName>();
                day = tokens[3].GetTag<ScalarDay>().Value;
                remainingTokens = tokens.Take(2).ToList();
            }
            else
            {
                month = tokens[1].GetTag<RepeaterMonthName>();
                day = tokens[2].GetTag<ScalarDay>().Value;
                remainingTokens = tokens.Take(1).ToList();
            }

            var now = options.Clock();
            if (Time.IsMonthOverflow(now.Year, (int)month.Value, day))
            {
                return null;
            }
            return Utils.HandleMD(month, day, remainingTokens, options);
        }
Example #2
1
        public static string FindPositionPart(IList<string> parts, int cursorPosition, out int foundPartsIndex, out int cursorInPartPosition)
        {
            cursorInPartPosition = 0;
              var partsComplete = parts.Aggregate(String.Empty, (aggr, s) => aggr + s);
              for (int i = 0; i < parts.Count(); i++) {
            var partsLower = parts.Take(i).Aggregate(String.Empty, (aggr, s) => aggr + s);
            var partsUpper = parts.Take(i + 1).Aggregate(String.Empty, (aggr, s) => aggr + s);

            var b = partsLower.Length;
            var t = partsUpper.Length;

            if ((cursorPosition >= b && cursorPosition < t) || partsUpper == partsComplete) {
              if (parts[i] == WorkDayParser.itemSeparator.ToString() || parts[i] == WorkDayParser.hourProjectInfoSeparator.ToString()) {
            // cursor left of separator
            foundPartsIndex = i - 1;
            var prevPart = parts.ElementAt(foundPartsIndex);
            // find out where in the found part the cursor is, need to use prevpart an its length
            cursorInPartPosition = prevPart.Length;
            return prevPart;
              } else {
            // find out where in the found part the cursor is
            cursorInPartPosition = cursorPosition - b;
            foundPartsIndex = i;
            return parts.ElementAt(i);
              }
            }
              }
              // not found
              foundPartsIndex = -1;
              return String.Empty;
        }
        public static string GetFormation(IList<PlayerGameweekPerformance> performances)
        {
            var defenders = performances.Take(11).Count(p => p.Position == Position.Defender);
            var midfielders = performances.Take(11).Count(p => p.Position == Position.Midfielder);
            var forwards = performances.Take(11).Count(p => p.Position == Position.Forward);

            return string.Format("{0}-{1}-{2}", defenders, midfielders, forwards);
        }
        private static IList<ulong> GetFibLikeSequence(IList<ulong> seedSequence, int length)
        {
            IList<ulong> sequence = new List<ulong>();

            int count = seedSequence.Count();

            if (length <= count)
            {
                sequence = seedSequence.Take((int)length).ToList();
            }
            else
            {
                sequence = seedSequence;

                for (int i = count; i < length; i++)
                {
                    ulong num = 0;

                    for (int j = 0; j < count; j++)
                    {
                        num += sequence[sequence.Count - 1 - j];
                    }

                    sequence.Add(num);
                }
            }

            return sequence;
        }
Example #5
1
 public override MatchResult Match(IList<Pattern> left, IEnumerable<Pattern> collected = null)
 {
     var coll = collected ?? new List<Pattern>();
     var sresult = SingleMatch(left);
     var match = sresult.Match;
     if (match == null)
     {
         return new MatchResult(false, left, coll);
     }
     var left_ = new List<Pattern>();
     left_.AddRange(left.Take(sresult.Position));
     left_.AddRange(left.Skip(sresult.Position + 1));
     var sameName = coll.Where(a => a.Name == Name).ToList();
     if (Value != null && (Value.IsList || Value.IsOfTypeInt))
     {
         var increment = new ValueObject(1);
         if (!Value.IsOfTypeInt)
         {
             increment = match.Value.IsString ? new ValueObject(new [] {match.Value})  : match.Value;
         }
         if (sameName.Count == 0) 
         {
             match.Value = increment;
             var res = new List<Pattern>(coll) {match};
             return new MatchResult(true, left_, res);
         }
         sameName[0].Value.Add(increment);
         return new MatchResult(true, left_, coll);
     }
     var resColl = new List<Pattern>();
     resColl.AddRange(coll);
     resColl.Add(match);
     return new MatchResult(true, left_, resColl);
 }
        public FromImportCompletionAnalysis(IList<ClassificationSpan> tokens, ITrackingSpan span, ITextBuffer textBuffer, CompletionOptions options)
            : base(span, textBuffer, options)
        {
            Debug.Assert(tokens[0].Span.GetText() == "from");

            int beforeImportToken = tokens
                .TakeWhile(tok => !(tok.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Keyword) && tok.Span.GetText() == "import"))
                .Count();

            bool lastIsDot = tokens.Last().ClassificationType.IsOfType(JPredefinedClassificationTypeNames.Dot);
            _modulesOnly = beforeImportToken == tokens.Count;
            _noCompletions = !_modulesOnly && lastIsDot;
            _includeStar = beforeImportToken == tokens.Count - 1;

            if (beforeImportToken >= 2) {
                // If there are at least two tokens ('from' <name>) before the
                // 'import' token, use completions from that package.
                if (beforeImportToken < tokens.Count || lastIsDot) {
                    _namespace = tokens
                        .Take(beforeImportToken)
                        .Where(tok => tok.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Identifier))
                        .Select(tok => tok.Span.GetText())
                        .ToArray();
                } else {
                    _importKeywordOnly = true;
                }
            }
        }
Example #7
1
        /// <summary>
        /// Returns a Faro shuffled list.
        /// The initial list is split in half. A new list is created by alternately adding each item from the half-lists to it.
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static IList<string> FaroShuffle(IList<string> list)
        {
            if (list.Count == 0)
                return list;

            var items = list.Count;

            //First half needs to greater by 1, or equal to the second half for this to work right
            int firstHalfSize;
            if (list.Count % 2 == 0)
                firstHalfSize = list.Count / 2;
            else
                firstHalfSize = list.Count / 2 + 1;

            //Split in two halfs
            IList<string> firstHalf = list.Take(firstHalfSize).ToList();
            IList<string> secondHalf = list.Skip(firstHalfSize).Take(list.Count - firstHalfSize).ToList();

            IList<string> result = new List<string>();

            for (int i = 0, skip = 0; i < items; i = i + 2, skip++)
            {
                var item = firstHalf.Skip(skip).FirstOrDefault();
                if (item != null)
                    result.Add(item);
                item = secondHalf.Skip(skip).FirstOrDefault();
                if (item != null)
                    result.Add(item);
            }

            return result;
        }
 private void ParseRealization(IList<Double> realization)
 {
     Double repeatedValue = realization.Last(); // last value it's the same as cycle start value
     Int32 cycleStartIndex = realization.IndexOf(repeatedValue);
     Appendix = realization.Take(cycleStartIndex).ToList();
     Cycle = realization.Skip(cycleStartIndex).Take(realization.Count - cycleStartIndex - 1).ToList();
 }
        public IEnumerable<PageLinksValidationResult> ValidateLinks(IList<DocumentationPage> pages)
        {
            var results = new ConcurrentBag<PageLinksValidationResult>();

            var p = new List<DocumentationPage>[2];

            var half = pages.Count / 2;
            p[0] = pages.Take(half).ToList();
            p[1] = pages.Skip(half).ToList();

            Parallel.For(
                0,
                2,
                i =>
                {
                    using (var client = new HttpClient())
                    {
                        var pagesToCheck = p[i];
                        foreach (var page in pagesToCheck)
                            results.Add(ValidatePageLinks(client, page, pages));
                    }
                });

            return results;
        }
 private static void UpdateSearchResults(IList<SearchResult> searchResults, XPathWorkbench workbench)
 {
     foreach(var searchResult in searchResults.Take(XPathWorkbench.MaxSearchResultCount))
     {
         workbench.SearchResults.Add(searchResult);
     }
     workbench.UpdateSearchResultText(searchResults);
 }
Example #11
1
        public void Execute(IList<IRecord> records, IList<IWorkItemTarget> targets)
        {
            String body = TemplateEngine.EvaluateTemplate(records, _body);
            String subject = TemplateEngine.EvaluateTemplate(records.Take(1).ToList(), _subject);
            String[] recipient = targets.Select(x => x.Evaluate(records[0])).ToArray();

            ((SmtpDeliverySystem)DeliverySystem).SendEmail(recipient, subject, body);
        }
 private IList<TripleExponentialEntry> BuildFirstSeason(IList<SeasonalIndex> seasonalIndices)
 {
     return seasonalIndices.Take(_periodsPerSeason).Select(i => new TripleExponentialEntry
         {
             Ft = 0,
             Tt = 0,
             St = i.PeriodSeasonalComponent,
             Forecast = 0
         }).ToList();
 }
        private static IEnumerable<double> ForecastSeries(IList<double> series, IEnumerable<IEnumerable<int>> indices, IEnumerable<int> radiuses, int period, int startForecastingFrom)
        {
            var indicesList = indices.Select(x => x.ToList()).ToList();
            var radiusesList = radiuses.ToList();

            var trainingSeries = series.Take(startForecastingFrom).ToList();
            foreach (var value in series.Skip(startForecastingFrom))
            {
                trainingSeries.Add(value);
                yield return Forecast(trainingSeries, indicesList, radiusesList, period);
            }
        }
 private static void ReplaceAnonymousType(
     IList<SymbolDisplayPart> list,
     INamedTypeSymbol anonymousType,
     IEnumerable<SymbolDisplayPart> parts)
 {
     var index = list.IndexOf(p => anonymousType.Equals(p.Symbol));
     if (index >= 0)
     {
         var result = list.Take(index).Concat(parts).Concat(list.Skip(index + 1)).ToList();
         list.Clear();
         list.AddRange(result);
     }
 }
        public Grid Build(IList<IPanelItem> items)
        {
            var grid = new Grid();

            var i = 1;

            while (!items.IsNullOrEmpty())
            {
                grid.Blocks.Add(GenerateBlock(items.Take(i)));

                items = items.Skip(i).ToList();

                if (items.IsNullOrEmpty())
                    break;

                i = i == 1 ? 4 : 1;

                grid.Blocks.Add(GenerateBlock(items.Take(i)));

                items = items.Skip(i).ToList();
            }

            return grid;
        }
Example #16
0
        public override IJsValue Construct(IList<IJsValue> arguments)
        {
            if (arguments.Count == 0)
            {
                return Construct(Environment, "", new string[0], null);
            }

            var script = arguments[arguments.Count - 1].ToString();
            var names = arguments.Take(arguments.Count - 1).Select(a => a.ToString()).ToArray();
            var body = Environment.Context.ParseScript(script);
            return Construct(Environment, "", names, body);
        }
 public DataTable DataManagementPlansToDataTable(IList<Project> projects, string listSeparator = CsvHelper.ListSeparator)
 {
     var dataTable = new DataTable();
     dataTable.AddDmpColumns(projects.Take(1).Single().DataManagementPlan);
     foreach (var project in projects)
     {
         var dataRow = dataTable.NewRow();
         dataRow.AddDmpValues(project.DataManagementPlan, project.Parties, listSeparator);
         dataTable.Rows.Add(dataRow);
     }
     return dataTable;
 }
 public DataTable DataCollectionsToDataTable(IList<DataCollection> dataCollections, string listSeparator = ListSeparator)
 {
     var dataTable = new DataTable();
     dataTable.AddDataCollectionColumns(dataCollections.Take(1).Single());
     foreach (var dataCollection in dataCollections)
     {
         var dataRow = dataTable.NewRow();
         dataRow.AddDataCollectionValues(dataCollection, listSeparator);
         dataTable.Rows.Add(dataRow);
     }
     return dataTable;
 }
        /// <summary>
        /// Creates the foo bars.
        /// </summary>
        /// <param name="foos">The foos.</param>
        /// <param name="bars">The bars.</param>
        /// <returns></returns>
	    public static IList<FooBar> CreateFooBars(IList<Foo> foos, IList<Bar> bars)
	    {
	        var trimmedBars = bars;

            if (bars.Count > foos.Count)
	        {
	            trimmedBars = bars.Take(foos.Count).ToList();
	        }

	        var fooBarDictionary = Enumerable.Range(0, foos.Count).ToDictionary(i => foos[i], i => trimmedBars[i]);

	        return (from pair in fooBarDictionary let foo = pair.Key let bar = pair.Value select new FooBar(foo, bar, RandomValueProvider.RandomString(10, false))).ToList();
	    }
Example #20
0
		public static IReturnType[] InferTypeArguments(IMethod method, IList<IReturnType> arguments, out bool success)
		{
			TypeInference ti = new TypeInference();
			Log("Doing type inference for " + new CSharpAmbience().Convert(method));
			Log(" with arguments = ", arguments);
			ti.typeParameters = method.TypeParameters.Select(tp => new TP(tp)).ToList();
			ti.parameterTypes = method.Parameters.Select(p => p.ReturnType).Take(arguments.Count).ToList();
			ti.arguments = arguments.Take(ti.parameterTypes.Count).ToArray();
			ti.PhaseOne();
			success = ti.PhaseTwo();
			IReturnType[] result = ti.typeParameters.Select(tp => tp.FixedTo).ToArray();
			Log("Type inference for " + method.DotNetName + " " + (success ? "succeeded" : "failed") + ": ", result);
			return result;
		}
 private static IEnumerable<Tuple<int, IList<int>>> GetAllSequences(IList<int> numbers)
 {
     var sequences = new List<Tuple<int, IList<int>>>();
     for (int i = 0; i < numbers.Count; i++)
     {
         IList<int> list = numbers.Skip(i).ToList();
         sequences.Add(Tuple.Create(list.Sum(), list));
     }
     for (int i = numbers.Count - 1; i > 0; i--)
     {
         IList<int> list = numbers.Take(i).ToArray();
         sequences.Add(Tuple.Create(list.Sum(), list));
     }
     return sequences;
 }
        public static void AssertValidDependencies(IList<IAnalyzedSourceFile> dependencies)
        {
            foreach (var index in Enumerable.Range(0, dependencies.Count))
            {
                var source = dependencies[index];
                var previousProvides = GetProvides(dependencies.Take(index));

                foreach (var require in source.Required)
                {
                    Assert.True(previousProvides.Contains(require), 
                        string.Format("Namespace '{0}' is not provided before being required by '{1}': [{2}]", 
                            require, source.Path, string.Join(", ", dependencies.Select(x => x.Path))));
                }
            }
        }
Example #23
0
        private static IEnumerable<KeyValuePair<string, IDictionary<string, IList<IClassGenerationParameters>>>> SortMainNameSpaces(IList<IClassGenerationParameters> classes)
        {
            var mainNamespaces = classes.Select(x => x.MainNamespaceName).Distinct().OrderBy(x => x).ToList();

            var mappings = new Dictionary<string, IDictionary<string, IList<IClassGenerationParameters>>>(mainNamespaces.Count);

            foreach (var mainNamespace in mainNamespaces)
            {
                var ns = mainNamespace;
                var classesInNamespace = classes.Take(x => x.MainNamespaceName.Equals(ns, StringComparison.Ordinal)).ToList();
                var sortedSubNamespaces = SortSubNamespaces(classesInNamespace);

                mappings.Add(mainNamespace, sortedSubNamespaces);
            }

            return mappings;
        }
        public void GenerateInquiriesList()
        {
            Clock.FreezedTime = new DateTime(2012, 7, 19);
            var team = Builder<Team>.CreateNew().Build();

            tags = new List<Tag>
            {
                new Tag
                {
                    Id = 1,
                    Name = "tag1",
                    Owner = team
                },
                new Tag
                {
                    Id = 2,
                    Name = "tag2",
                    Owner = team
                }
            };

            inquiries = Builder<Inquiry>.CreateListOfSize(40)
                .All()
                .With(x => x.Client = Builder<Person>.CreateNew().Build())
                .With(x => x.Assignee = Builder<Person>.CreateNew().Build())
                .With(x => x.Source = Builder<MailMessage>.CreateNew().Build())
                .With(x => x.Tags = new List<Tag>())
                .TheFirst(10)
                .With(x => x.ReferenceDate = null)
                .With(x => x.Tags = tags.Take(1).ToList())
                .TheNext(10)
                .With(x => x.ReferenceDate = GetRandom.DateTime(February.The15th, February.The28th))
                .With(x => x.Tags = tags.Skip(1).Take(1).ToList())
                .TheNext(1)
                .With(x => x.ReferenceDate = new DateTime(Clock.Now.Year, 3, 1))
                .TheNext(9)
                .With(x => x.ReferenceDate = GetRandom.DateTime(March.The1st, March.The31st))
                .TheNext(10)
                .With(x => x.ReferenceDate = GetRandom.DateTime(
                    Clock.Now.GetStartOfBusinessWeek(), Clock.Now.GetEndOfBusinessWeek()))
                .Build();

            tags[0].Inquiries = inquiries.Take(10).ToList();
            tags[1].Inquiries = inquiries.Skip(10).Take(10).ToList();
        }
Example #25
0
        public int find(int itemToFind, IList<int> collection)
        {
            if(!collection.Any())
                return -1;

            var foundIndex = 0;
            switch(itemToFind.CompareTo(collection[collection.Count / 2]))
            {
                case 0:
                    return collection.Count/2;
                case 1:
                    foundIndex = binary_chopper.find(itemToFind, collection.Skip(collection.Count/2 + 1).ToList());
                    return foundIndex != -1 ? foundIndex + collection.Count / 2 + 1 : -1;
                case -1:
                    foundIndex = binary_chopper.find(itemToFind, collection.Take(collection.Count/2).ToList());
                    return foundIndex != -1 ? foundIndex : -1;
            }

            throw new Exception();
        }
Example #26
0
 public void Add(IList<SkinnedVertex> v, bool generateNormals)
 {
     if (v.Count < 3) throw new EngineException("Trying to build a face with less than 3 vertices.");
     if (v.Count >= 4)
     {
         Add(v.Take(3).ToList(), generateNormals);
         Add(v.Skip(2).Concat(new[] {v[0]}).ToList(), generateNormals);
         return;
     }
     for (var i = 0; i < v.Count; i++ )
     {
         var vert = v[i];
         if (generateNormals)
         {
             var temp = (i + v.Count - 1) % v.Count;
             var left = v[temp].Position - v[i].Position;
             var right = v[(i + 1) % v.Count].Position - v[i].Position;
             vert.Normal = Vector3.Normalize(Vector3.Cross(left, right));
         }
         if (!vertindex.ContainsKey(vert.Position)) vertindex.Add(vert.Position, new LinkedList<int>());
         var found = false;
         foreach (var index in vertindex[vert.Position])
         {
             if (Equals(vertices[index], vert))
             {
                 found = true;
                 indices[i] = index;
                 break;
             }
         }
         if (found) continue;
         indices[i] = vertices.Count;
         vertindex[vert.Position].AddLast(vertices.Count);
         vertices.Add(vert);
     }
     submeshes.Last().Count++;
     triangles.Add(new Vector3i(indices));
 }
        public IExpressionTree Build(IList<Token> tokens)
        {
            if (tokens.Count == 0)
                return null;

            if (IsExpressionASingleValue(tokens))
            {
                // ���� ��������� ������� �� ������������� ��������, �� ������������ ���� ������ � ���� ���������.
                return new ExpressionTree(tokens[0], null);
            }

            // ���������� �������� ������������ ��������, �� �������� ��������� ����������� �� ��� �����.
            var index = GetIndexOfOperatorWithLowestPrecedence(tokens);

            if (index != -1)
            {
                var leftchild = Build(tokens.Take(index).ToList());
                var rightchild = Build(tokens.Skip(index + 1).ToList());

                var children = new List<IExpressionTree>();
                if (leftchild != null)
                    children.Add(leftchild);
                if (rightchild != null)
                    children.Add(rightchild);

                return new ExpressionTree(tokens[index], children);
            }

            // ���� �� ��������� � �������, �� ���������� ��������� ��, ��� ������
            if (IsExpressionInBrackets(tokens))
            {

                return Build(tokens.Skip(1).Take(tokens.Count - 2).ToList());
            }

            throw new Exception("Can't parse: " + String.Join("", tokens.Select(t => t.ToString())));
        }
 public Expression Mutate(IList<Expression> operands)
 {
     var bindings = new List<MemberBinding>();
     int operandIndex = MemberInitExpression.NewExpression.Arguments.Count();
     NewExpression newNewExpression;
     if (MemberInitExpression.NewExpression.Constructor != null)
     {
         newNewExpression = Expression.New(MemberInitExpression.NewExpression.Constructor,
                                           operands.Take(operandIndex));
     }
     else
     {
         newNewExpression = Expression.New(MemberInitExpression.NewExpression.Type);
     }
     foreach (var memberBinding in MemberInitExpression.Bindings)
     {
         var memberBindingMutator = MemberBindingMutatorFactory.GetMutator(memberBinding);
         int operandsCount = memberBindingMutator.Operands.Count();
         var subOperands = operands.Skip(operandIndex).Take(operandsCount).ToList();
         bindings.Add(memberBindingMutator.Mutate(subOperands));
         operandIndex += operandsCount;
     }
     return Expression.MemberInit(newNewExpression, bindings);
 }
        private IList<PlayerGameweekPerformance> SelectScoringPerformances(IList<PlayerGameweekPerformance> playerGameweekPerformances)
        {
            //start with the first 11 and replace players where we can if they don't play this gameweek
            var scoringPerformances = playerGameweekPerformances.Take(11).ToList();
            var subs = playerGameweekPerformances.Skip(11).ToList();

            //iterate through players and replace where neccessary)
            for (var i = 0; i < 11; i++)
            {
                var performance = scoringPerformances.ElementAt(i);
                if(performance.MinutesPlayed == 0)
                {
                    var sub = FindSubPerformance(scoringPerformances, subs, performance.Position);
                    if(sub != null)
                    {
                        scoringPerformances.RemoveAt(i);
                        scoringPerformances.Insert(i, sub);
                        subs.Remove(sub);

                        _logger.Log(Tag.Result, string.Concat(sub.PlayerName, " subbed in for ", performance.PlayerName), true);
                    } else
                    {
                        _logger.Log(Tag.Result, string.Concat("No sub found for ", performance.PlayerName), true);
                    }
                }
            }

            return scoringPerformances;
        }
Example #30
0
 private static int GetProb(IList<double> prob)
 {
     int result = 0;
     int n = (int)(prob.Sum() * 1000);
     Random r = new Random();
     double x = (float)r.Next(0, n) / 1000;
     for (int i = 0; i < prob.Count(); i++)
     {
         double pre = prob.Take(i).Sum();
         double next = prob.Take(i + 1).Sum();
         if (x >= pre && x < next)
         {
             result = i;
             break;
         }
     }
     return result;
 }