Example #1
1
        public override dynamic Run(IList<Token> tokens, Context context)
        {
            /*
             1: content to write
             2: file object
             3: item separator
             4: line breack

             3: file mode -> w: write, a: append
             */

             var arguments = ExtractArguments(tokens.Skip(1).ToArray(), context);
             FileObject fileObject;
             string separator = ",", lineBreack = "\r\n";

             var rhs = recurse.Run(tokens.Skip(2).Take(1).ToArray(), context);
             fileObject = recurse.Run(tokens.Skip(4).Take(1).ToArray(), context);

             if (arguments.Count() >= 6)
            separator = arguments[5].Value.ExtractStringValue();
             if (arguments.Count() >= 7)
            lineBreack = arguments[6].Value.ExtractStringValue();

             context.Core.WriteToFile(rhs, fileObject, separator, lineBreack);

             return null;
        }
Example #2
1
		/// <summary>
		///		Creates type list for nested tuples.
		/// </summary>
		/// <param name="itemTypes">The type list of tuple items, in order.</param>
		/// <returns>
		///		The type list for nested tuples.
		///		The order is from outer to inner.
		/// </returns>
		public static List<Type> CreateTupleTypeList( IList<Type> itemTypes )
		{
			var itemTypesStack = new Stack<List<Type>>( itemTypes.Count / 7 + 1 );
			for ( int i = 0; i < itemTypes.Count / 7; i++ )
			{
				itemTypesStack.Push( itemTypes.Skip( i * 7 ).Take( 7 ).ToList() );
			}

			if ( itemTypes.Count % 7 != 0 )
			{
				itemTypesStack.Push( itemTypes.Skip( ( itemTypes.Count / 7 ) * 7 ).Take( itemTypes.Count % 7 ).ToList() );
			}

			var result = new List<Type>( itemTypesStack.Count );
			while ( 0 < itemTypesStack.Count )
			{
				var itemTypesStackEntry = itemTypesStack.Pop();
				if ( 0 < result.Count )
				{
					itemTypesStackEntry.Add( result.Last() );
				}

				var tupleType = Type.GetType( "System.Tuple`" + itemTypesStackEntry.Count, true ).MakeGenericType( itemTypesStackEntry.ToArray() );
				result.Add( tupleType );
			}

			result.Reverse();
			return result;
		}
Example #3
1
        public bool Match(IList<Token> tokens, HandlerRegistry registry)
        {
            var tokenIndex = 0;
            foreach (var pattern in _patterns)
            {
                var isOptional = pattern.IsOptional;
                var isRequired = !isOptional;
                var thereAreNoMoreTokens = tokenIndex == tokens.Count;

                if (pattern is TagPattern)
                {
                    var match = tokenIndex < tokens.Count &&
                        tokens[tokenIndex].IsTaggedAs((pattern as TagPattern).TagType);
                    if (match == false && isRequired)
                    {
                        return false;
                    }
                    if (match)
                    {
                        tokenIndex++;
                    }
                }
                else if (pattern is RepeatPattern)
                {
                    var repetition = pattern as RepeatPattern;
                    int advancement;
                    var match = repetition.Match(tokens.Skip(tokenIndex).ToList(), out advancement);
                    if (match == false && isRequired)
                    {
                        return false;
                    }
                    if (match)
                    {
                        tokenIndex += advancement;
                    }
                }
                else if (pattern is HandlerTypePattern)
                {
                    if (isOptional && thereAreNoMoreTokens)
                    {
                        return true;
                    }
                    var subHandlers = registry.GetHandlers((pattern as HandlerTypePattern).Type);
                    foreach (var handler in subHandlers)
                    {
                        if (handler.Match(tokens.Skip(tokenIndex).ToList(), registry))
                        {
                            return true;
                        }
                    }
                }
            }

            if (tokenIndex != tokens.Count)
            {
                return false;
            }
            return true;
        }
Example #4
1
File: Find.cs Project: zuun/wSQL
        public override dynamic Run(IList<Token> tokens, Context context)
        {
            ExpectTokens(tokens, 4);

              if (tokens[1].Type != TokenType.OpenPar || tokens[3].Type != TokenType.Comma || tokens[5].Type != TokenType.ClosedPar)
            throw new Exception("Invalid syntax.");

              var value = recurse.Run(tokens.Skip(2).Take(1).ToArray(), context);
              var xpath = recurse.Run(tokens.Skip(4).Take(1).ToArray(), context);
              return context.Core.Find(value, xpath);
        }
Example #5
1
        public override dynamic Run(IList<Token> tokens, Context context)
        {
            ExpectTokens(tokens, 1);

             var rhs = recurse.Run(tokens.Skip(2).ToArray(), context);
             var separator = recurse.Run(tokens.Skip(4).ToArray(), context);
             string lineEnd = "";
             if (tokens.Count >= 6)
            lineEnd = recurse.Run(tokens.Skip(6).ToArray(), context);
             context.Core.PrintList(rhs, separator, lineEnd);

             return null;
        }
Example #6
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;
        }
Example #7
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);
 }
 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();
 }
Example #9
1
        public void ExportExcel(IList<dynamic> items, string fileName)
        {
            using (var excelPackage = new ExcelPackage(new FileStream(fileName, FileMode.CreateNew)))
            {
                var currentIndex = 0;
                var sheetIndex = 1;
                do
                {
                    var take = Math.Min(1000000, items.Count - currentIndex);
                    var currentSet = items.Skip(currentIndex).Take(take).ToList();
                    currentIndex += currentSet.Count;

                    var sheet = excelPackage.Workbook.Worksheets.Add("Sheet " + sheetIndex);
                    var arrayData = new List<object[]>();
                    foreach (var item in currentSet)
                    {
                        arrayData.Add(((IDictionary<string, object>)item).Values.ToArray());
                    }

                    sheet.Cells["A1"].LoadFromArrays(arrayData);

                    sheetIndex++;
                    excelPackage.Save();
                }
                while (currentIndex < items.Count);
            }
        }
        public IList<DepthPointEx> Filter(IList<DepthPointEx> points)
        {
            IList<DepthPointEx> result = new List<DepthPointEx>();

            if (points.Count > 0)
            {
                var point = new DepthPointEx(points.First());
                result.Add(point);

                foreach (var currentSourcePoint in points.Skip(1))
                {
                    if (!PointsAreClose(currentSourcePoint, point))
                    {
                        point = new DepthPointEx(currentSourcePoint);
                        result.Add(point);
                    }
                }

                if (result.Count > 1)
                {
                    CheckFirstAndLastPoint(result);
                }
            }

            return result;
        }
 public IEnumerable<Double> FindAllAverages(IList<double> values, int windowSize)
 {
     //Checking for errors
     if(windowSize > values.Count)
         throw new ValueCountLessThanWindowException();
     if (windowSize < 0)
         throw new BadWindowException();
     if (values.Count == 0)
         throw new ValuesCountException();
     var cumulativeAverageArray = new double[values.Count];
     var currentAverage = 0.0;
     for (var i = 0; i < values.Count; i++)
     {
         var convertedIndexToCounterFromIndex = i + 1;
         if (convertedIndexToCounterFromIndex <= windowSize && i != 0) // handles greater than 0, but less than window size
         {
             currentAverage = (((currentAverage * i) + values[i]) / convertedIndexToCounterFromIndex);
         }
         else if (convertedIndexToCounterFromIndex <= windowSize) // handles 0 case
         {
             currentAverage = (((currentAverage * i) + values[i]) / convertedIndexToCounterFromIndex);
         }
         else  // https://en.wikipedia.org/wiki/Moving_average //handles greater than 0 and greater than window size
         {
             currentAverage = ((values.Skip(convertedIndexToCounterFromIndex - windowSize).Take(windowSize).Sum()) / windowSize);
         }
         cumulativeAverageArray[i] = currentAverage;
     }
     return cumulativeAverageArray;
 }
Example #12
1
        public IList<Point> Filter(IList<Point> points)
        {
            IList<Point> result = new List<Point>();
            if (points.Count == 0)
            {
                return result;
            }

            var point = new Point(points.First());
            result.Add(point);

            foreach (var currentSourcePoint in points.Skip(1))
            {
                if (!this.DistanceIsTooSmall(currentSourcePoint, point))
                {
                    point = new Point(currentSourcePoint);
                    result.Add(point);
                }
            }

            if (this.checkBoundary && result.Count > 1)
            {
                CheckFirstAndLastPoint(result);
            }

            return result;
        }
Example #13
1
 public void Call(IList<IValue> args, VM vm, SourceInfo info)
 {
     int argCount = args.Count;
     if (argCount < mParamCount ||
         argCount > mParamCount && !mAllowRest && !mAllowKeys)
     {
         throw new RheaException(
             this.WrongNumberOfArguments(mParamCount, argCount), info
         );
     }
     var dict = new Dictionary<IValue, IValue>();
     if (mAllowKeys)
     {
         foreach (IValue arg in args.Skip(mParamCount))
         {
             ValueArray pair = arg as ValueArray;
             if (pair == null || pair.Value.Count != 2)
             {
                 throw new RheaException(
                     "keyword arguments should occur pairwise", info
                 );
             }
             dict.Add(pair.Value[0], pair.Value[1]);
         }
     }
     var newArgs = new Arguments(args, dict);
     mSubrValue(newArgs, vm, info);
 }
        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 IList<MembershipFunction> mergeFirstTwoFunctions(IList<MembershipFunction> msfs)
 {
     var combined = combine(msfs[0], msfs[1]);
     var newMsfs = new List<MembershipFunction> {combined};
     newMsfs.AddRange(msfs.Skip(2));
     return newMsfs;
 }
 public static QueryExpressionSyntax WithAllClauses(
     this QueryExpressionSyntax query,
     IList<SyntaxNode> allClauses)
 {
     var fromClause = (FromClauseSyntax)allClauses.First();
     return query.WithFromClause(fromClause).WithBody(query.Body.WithAllClauses(allClauses.Skip(1)));
 }
Example #17
0
File: Trim.cs Project: zuun/wSQL
        public override dynamic Run(IList<Token> tokens, Context context)
        {
            var arguments = ExtractArguments(tokens.Skip(1).ToArray(), context);

             string trimValue = "";
             if (arguments.Count >= 4)
            trimValue = arguments[arguments.Count - 1].Value.ExtractStringValue();

             object expression = null;

             if (arguments[0].Type == TokenType.Identifier && arguments[0].Value.ToLower() == "it")
             {
            var expr = arguments.Take(3).ToArray();
            var argName = arguments[0].Value; // do not evaluate this symbol
            //context.Symbols.Set(argName, item);
            expression = recurse.Run(expr, context);
             }
             else
            expression = recurse.Run(arguments, context);

             if (expression is string)
            return TrimString(expression, trimValue);
             else
            if (expression is IEnumerable<string>)
             {
            var list = ((IEnumerable<string>)expression).ToArray();
            for (int index = 0; index < list.Count(); index++)
               list[index] = TrimString(list[index], trimValue);
            return list;
             }

             throw new Exception("Trim expected string values but not foud");
        }
Example #18
0
        protected IList<Token> ExtractArguments(IList<Token> tokens, Context context)
        {
            if (tokens.Count < 3)
            throw new Exception("Invalid subexpression.");

              if (tokens[0].Type != TokenType.OpenPar)
            throw new Exception("Syntax error.");

              // start depth at zero; for each token, increment the depth for "(" and decrement for ")"
              // when the depth reaches zero again, stop and return the explored sublist
              var depth = 0;
              var index = 0;
              while (index < tokens.Count)
              {
            if (tokens[index].Type == TokenType.OpenPar)
              depth++;
            else if (tokens[index].Type == TokenType.ClosedPar)
              depth--;

            if (depth == 0)
              break;

            index++;
              }

              // if the loop has ended and the depth is not zero, the parentheses are unbalanced
              if (depth > 0)
            throw new Exception("Too many open parentheses.");
              // this normally can't happen but just in case
              if (depth < 0)
            throw new Exception("Too many closed parentheses.");

              return tokens.Skip(1).Take(index - 1).ToArray();
        }
Example #19
0
        public void GraphBuildHistory(IList<BuildStatus> buildStatuses)
        {
            if (buildStatuses == null)
            {
                _log.Warn("buildStatuses was null. Unable to build a graph.");
                return;
            }
            if (_buildHistoryZedGraph == null || _buildHistoryZedGraph.GraphPane == null)
            {
                _log.Warn("_buildHistoryZedGraph was null. Unable to build a graph.");
                return;
            }
            GraphPane myPane = _buildHistoryZedGraph.GraphPane;
            myPane.CurveList.Clear();

            IEnumerable<BuildStatus> lastFewBuildStatuses = buildStatuses.Skip(buildStatuses.Count - 8);
            foreach (BuildStatus buildStatus in lastFewBuildStatuses)
            {
                if (buildStatus == null || buildStatus.FinishedTime == null || buildStatus.StartedTime == null) continue;
                var duration = buildStatus.FinishedTime.Value - buildStatus.StartedTime.Value;
                Fill fill = buildStatus.BuildStatusEnum == BuildStatusEnum.Broken ? _failFill : _successFill;
                var bar = myPane.AddBar(null, null, new[] { duration.TotalMinutes }, Color.White);
                bar.Bar.Fill = fill;
                bar.Bar.Border.Color = Color.White;
            }

            _buildHistoryZedGraph.AxisChange();
            _buildHistoryZedGraph.Invalidate();
        }
Example #20
0
        public void ParseAndRun(IList<string> lines, int start, out Range size, out string result)
        {
            string command = null;
            Dictionary<string, string> commandArgs = new Dictionary<string, string>();
            int end = start;

            while(end+1 < lines.Count
                    && lines[end + 1].Contains(":")
                    && lines[end + 1].StartsWith(" "))
                end += 1;

            foreach(var line in lines.Skip(start).Take(1 + end - start)) {
                var arg = line.Split(new char[] { ':' }, 2);

                if(command == null)
                    command = arg[0].Trim();

                commandArgs[arg[0].Trim()] = arg[1].Trim();
            }

            result = Invoke(command, commandArgs);
            if(result != null && !result.EndsWith("\n"))
                result = result + '\n';

            size = new Range(start) {
                EndRow = end,
                EndColumn = lines[end].Length
            };
        }
        public IMvxSourceBinding CreateBinding(object source, IList<MvxPropertyToken> tokens)
        {
            if (tokens == null || tokens.Count == 0)
            {
                throw new MvxException("empty token list passed to CreateBinding");
            }

            var currentToken = tokens[0];
            var remainingTokens = tokens.Skip(1).ToList();
            IMvxSourceBinding extensionResult;
            if (TryCreateBindingFromExtensions(source, currentToken, remainingTokens, out extensionResult))
            {
                return extensionResult;
            }

            if (source != null)
            {
                MvxBindingTrace.Trace(
                    MvxTraceLevel.Warning,
                    "Unable to bind: source property source not found {0} on {1}"
                    , currentToken
                    , source.GetType().Name);
            }

            return new MvxMissingSourceBinding(source);
        }
        public void Execute(IList<string> arguments, IPhonebookRepository repository)
        {
            if (arguments.Count < 2)
            {
                throw new ArgumentException("Invalid number of arguments to add phone number");
            }

            string name = arguments[0];
            var phoneNumbers = arguments.Skip(1).ToList();
            for (int i = 0; i < phoneNumbers.Count; i++)
            {
                phoneNumbers[i] = sanitizer.ConvertPhoneToCanonical(phoneNumbers[i]);
            }

            bool isPhoneNew = repository.AddPhone(name, phoneNumbers);

            if (isPhoneNew)
            {
                Print("Phone entry created");
            }
            else
            {
                Print("Phone entry merged");
            }
        }
Example #23
0
        public static List MakeList(IList<object> elements, Variable tail)
        {
            if (elements.Count == 1)
                return new List(elements[0], tail);

            return new List(elements[0], MakeList(elements.Skip(1).ToList(), tail));
        }
Example #24
0
        public static List MakeList(IList<object> elements, List tail = null)
        {
            if (elements.Count == 0)
                return tail;

            return new List(elements[0], MakeList(elements.Skip(1).ToList(), tail));
        }
Example #25
0
File: Map.cs Project: zuun/wSQL
        public override dynamic Run(IList<Token> tokens, Context context)
        {
            var arguments = ExtractArguments(tokens.Skip(1).ToArray(), context);
              var listName = arguments[0].Value;

              var list = context.Symbols.Get(listName) as IEnumerable;
              if (list == null)
            throw new Exception("Map: first argument is not a list.");

              var lambda = arguments.Skip(2).ToArray();

              var argName = lambda[0].Value; // do not evaluate this symbol
              context.Symbols.Declare(argName);

              var expr = lambda.Skip(2).ToArray();

              var result = new List<object>();
              foreach (var item in list)
              {
            context.Symbols.Set(argName, item);
            result.Add(recurse.Run(expr, context));
              }

              context.Symbols.Undeclare(argName);

              return result;
        }
        public static Document CreateDocument(IList<Person> people)
        {
            var document = Word.Documents.Add();

            document.EmbedTrueTypeFonts = true;

            var range = document.Range();
            range.Font.Name = "Centaur Festive MT Italic";
            range.Font.Size = 14;
            range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            range.PageSetup.LeftMargin = range.PageSetup.RightMargin = 24;
            range.PageSetup.TextColumns.SetCount(ColumnCount);

            var colSize = (int)Math.Ceiling(people.Count / (double)ColumnCount);

            for (int col = 0; col < ColumnCount; col++) {
                range.Text = people.Skip(col * colSize).Take(colSize).Join("\v", p => p.FullName);

                if (col == ColumnCount - 1) break;
                range.Collapse(WdCollapseDirection.wdCollapseEnd);
                range.InsertBreak(WdBreakType.wdColumnBreak);
            }

            document.Activate();
            Word.Activate();
            document.Activate();
            return document;
        }
Example #27
0
 public static IEnumerable<double> MovingAverage(IList<double> list, int period)
 {
     int end = list.Count - period + 1;
     for (int i = 0; i < end; i++)
     {
         yield return list.Skip(i).Take(period).Average();
     }
 }
Example #28
0
 public static Question CreateFromStrings(IList<string> row)
 {
     return new Question
       {
     Picture = row[0],
     CorrectAnswersMask = row.Skip(1).Select(mask => new Regex(MaskToRegex(mask))).ToArray()
       };
 }
 protected static IList<TimePeriod> RemoveEarlyEmptyTimePeriods(PartitionTrendDataDictionaryBuilder dictionaryBuilder,
     IList<TimePeriod> timePeriods)
 {
     int earliestIndexRemoved = dictionaryBuilder.RemoveEarlyEmptyYears();
     return earliestIndexRemoved > -1
         ? timePeriods.Skip(earliestIndexRemoved + 1).ToList()
         : timePeriods;
 }
Example #30
0
 public Response(IList<byte> rawMessage)
 {
     this.code = rawMessage[2];
     this.errorCode = rawMessage[3];
     this.message = rawMessage
         .Skip(4)
         .Take(rawMessage[1] - 2)
         .ToArray(); 
 }