private void AppendFilter(StringBuilder querySb, string clause, ISqlFilter filter, bool parametric,
                           IReadOnlyList <ModifyQueryPartCallback> modificators)
 {
     if (filter != null)
     {
         var sql = parametric ? filter.ParametricSql : filter.RawSql;
         querySb.Append(SEPARATOR).Append(clause)
         .Append(SEPARATOR_WITH_OFFSET)
         .Append(modificators.Aggregate(sql, (result, callback) => callback(result)));
     }
     else if (modificators.Count > 0)
     {
         querySb.Append(modificators.Aggregate(string.Empty, (result, callback) => callback(result)));
     }
 }
Ejemplo n.º 2
0
        private Dictionary <string, string> GetResultAsDictionary(IReadOnlyList <IResultSetValue> row)
        {
            Dictionary <string, string> result = new Dictionary <string, string>();

            row.Aggregate(result, (a, b) => { a.Add(b.ColumnInfo.Name, b.ToString()); return(a); });
            return(result);
        }
Ejemplo n.º 3
0
                public Type CreateGenericType(IStaticScope parent, IOrType <NameKey, ImplicitKey> key, IReadOnlyList <TypeAndConverter> placeholders, IConvertTo <Type, IOrType <WeakTypeDefinition, WeakGenericTypeDefinition, Tac.SyntaxModel.Elements.AtomicTypes.IPrimitiveType> > converter)
                {
                    var res = new Type(
                        this,
                        $"generic-{key}-{placeholders.Aggregate("", (x, y) => x + "-" + y)}",
                        Possibly.Is(key),
                        converter,
                        Possibly.IsNot <Guid>(),
                        Possibly.IsNot <IInterfaceType>());

                    IsChildOf(parent, res);
                    HasType(parent, key.SwitchReturns <IKey>(x => x, x => x), res);
                    var i = 0;

                    foreach (var placeholder in placeholders)
                    {
                        var placeholderType = new TypeProblem2.GenericTypeParameter(this, $"generic-parameter-{placeholder.key}", i++, Prototypist.Toolbox.OrType.Make <MethodType, Type, Method, InferredType>(res));
                        //var placeholderType = new Type(
                        //    this,
                        //    $"generic-parameter-{placeholder.key}",
                        //    Possibly.Is(placeholder.key),
                        //    placeholder.converter,
                        //    Possibly.IsNot<Guid>(),
                        //    Possibly.IsNot<IInterfaceType>());
                        HasGenericType(Prototypist.Toolbox.OrType.Make <MethodType, Type, Method>(res), placeholder.key, placeholderType);
                    }
                    return(res);
                }
Ejemplo n.º 4
0
        public SimpleReadOnlySequenceSegment(IReadOnlyList <ReadOnlyMemory <T> > segments)
        {
            var runningIndex = segments.Aggregate((long)0, (v, s) => v + s.Length);

            SimpleReadOnlySequenceSegment <T>?nextSegment = null;

            for (int i = segments.Count - 1; i > 0; i--)
            {
                var segment = segments[i];
                runningIndex -= segment.Length;
                nextSegment   = new SimpleReadOnlySequenceSegment <T>(segment, runningIndex, nextSegment);
            }

            if (segments.Count > 0)
            {
                var firstSegment = segments[0];
                runningIndex -= firstSegment.Length;

                Memory = firstSegment;
            }

            Debug.Assert(runningIndex == 0);
            RunningIndex = runningIndex;
            Next         = nextSegment;
            _lastSegment = nextSegment?.LastSegment;
        }
Ejemplo n.º 5
0
        public void TestMethod2()
        {
            const int keyCount = 13;

            for (var numKeyPairs = 4; numKeyPairs < 30; numKeyPairs += 2)
            {
                for (var numSwitchables = 10; numSwitchables < 100; numSwitchables += 10)
                {
                    var rando = Rando.Fast(numSwitchables + 377);
                    IReadOnlyList <IKeyPair> sorterStage = KeyPairRepository.RandomKeyPairs(13, numKeyPairs, rando.NextInt()).ToList();
                    for (var rep = 0; rep < 10; rep++)
                    {
                        var reducedSorterStage =
                            sorterStage.ToReducedSorterStage(
                                rando.Spawn().ToSwitchableGroup <uint>(Guid.NewGuid(), keyCount, numSwitchables)
                                );
                        //if (reducedSorterStage.KeyPairs.Count > 6)
                        //{
                        //    System.Diagnostics.Debug.WriteLine(sorterStage.Aggregate("\n", (o, n) => o + " [" + n.LowKey + "," + n.HiKey + "]"));
                        //    System.Diagnostics.Debug.WriteLine(reducedSorterStage.KeyPairs.Aggregate(String.Empty, (o,n)=> o + " [" + n.LowKey + "," + n.HiKey + "]" ));
                        //}
                        System.Diagnostics.Debug.WriteLine(String.Format("{0}\t{1}\t{2}\t{3}\t{4}",
                                                                         numKeyPairs,
                                                                         numSwitchables,
                                                                         reducedSorterStage.KeyPairs.Count,
                                                                         sorterStage.Aggregate("", (o, n) => o + " [" + n.LowKey + "," + n.HiKey + "]"),
                                                                         reducedSorterStage.KeyPairs.Aggregate(String.Empty, (o, n) => o + " [" + n.LowKey + "," + n.HiKey + "]")
                                                                         ));
                    }
                }
            }
        }
Ejemplo n.º 6
0
 private static int CalculateHashCode(IReadOnlyList <string> values)
 {
     unchecked
     {
         return(values.Aggregate(1, (current, t) => current ^ (t.GetHashCode() * 397)));
     }
 }
        private void BuildRow(IReadOnlyList <int> columnWidths, IReadOnlyList <string> rowValues)
        {
            var row = string.Empty;

            if (rowValues.Count > 0)
            {
                for (var i = 0; i < columnWidths.Count; i++)
                {
                    row += settings.FieldDelimiter
                           + rowValues[i].PadRight(columnWidths[i])
                           + string.Empty.PadRight(settings.Padding, ' ');

                    if (i == rowValues.Count - 1)
                    {
                        row += settings.FieldDelimiter;
                    }
                }
            }
            else
            {
                row = columnWidths.Aggregate(row, (current, t) => current
                                             + char.ToString(settings.RowDelimiter).PadRight(t + settings.Padding * 2, settings.RowDelimiter)
                                             + char.ToString(settings.RowDelimiter));
            }
            table.AppendLine(row);
        }
        private async Task ListIssuesResume(IDialogContext context, IAwaitable <string> repo)
        {
            _lastRepo = await repo;

            string token = await ValidateLoggedInAsync(context);

            if (!string.IsNullOrEmpty(token))
            {
                IReadOnlyList <Issue> issues = await GitHubCommands.GetIssueList(token, _lastRepo, _lastDate);

                string msg;

                if (issues == null)
                {
                    msg = "That repo doesn't exist or you don't have access to it. Try another one?";
                }
                else if (!issues.Any())
                {
                    msg = $"There are no issues assigned to you in the **{_lastRepo}** repo.";
                }
                else
                {
                    msg = issues.Aggregate($"These issues from the **{_lastRepo}** repo are assigned to you:", (current, issue) => current + Environment.NewLine + $"* [{issue.Number}]({issue.HtmlUrl}): {issue.Title}");
                }

                await context.PostAsync(msg);
            }

            _lastDate = null;
            context.Wait(MessageReceived);
        }
        public async Task <EnvironmentCost> GetCost(RenderingEnvironment env, QueryTimePeriod period)
        {
            var client = await _clientAccessor.GetClient();

            var usageRequest = CreateUsageRequest(env, period);

            IReadOnlyList <Cost> costs =
                await Task.WhenAll(env.ExtractResourceGroupNames().Select(
                                       async rgName =>
            {
                var result = await client.GetUsageForResourceGroup(env.SubscriptionId, rgName, usageRequest);

                if (result.Properties == null)
                {
                    return(null);
                }
                else
                {
                    return(new Cost(usageRequest.TimePeriod, result));
                }
            }));

            costs = costs.Where(x => x != null).ToList();

            if (!costs.Any())
            {
                return(new EnvironmentCost(env.Name, null));
            }

            return(new EnvironmentCost(env.Name, costs.Aggregate(Cost.Aggregate)));
        }
        private IEnumerable <KeyValuePair <BattleProcess.ShipHpStatus, TriState> > CalcMvpStatus(IReadOnlyList <BattleProcess.ShipHpStatus> EndShips)
        {
            if (EndShips == null)
            {
                yield break;
            }

            var mvpRange = EndShips.Aggregate(new FuzzyInt(), (range, ship) => FuzzyInt.UpperRange(range, ship.DeliveredDamage));
            var fuzzy    = EndShips.Select(x => x.DeliveredDamage).Where(x => x.LowerBound != x.UpperBound);

            if (fuzzy.Count() != 0)
            {
                mvpRange.LowerBound = Math.Max(mvpRange.LowerBound, fuzzy.Max(x => x.UpperBound) / fuzzy.Count());
            }

            var inRangeState = EndShips.Count(x => (x.DeliveredDamage >= mvpRange) != TriState.No) == 1 ? TriState.Yes : TriState.DK;

            if (mvpRange.UpperBound == mvpRange.LowerBound)
            {
                inRangeState = TriState.Yes;
            }
            foreach (var ship in EndShips)
            {
                yield return(new KeyValuePair <BattleProcess.ShipHpStatus, TriState>(ship, (ship.DeliveredDamage >= mvpRange) != TriState.No ? inRangeState : TriState.No));

                if (mvpRange.UpperBound == mvpRange.LowerBound && ship.DeliveredDamage.LowerBound == mvpRange.LowerBound)
                {
                    inRangeState = TriState.No;
                }
            }
        }
 public static IScpWorkflowBuilder Update
 (
     IScpWorkflowBuilder builder,
     IReadOnlyList <int> seeds,
     bool mergeWithPrev
 )
 {
     return(new ScpWorkflowBuilderImpl(
                guid: builder.Guid.Add(seeds),
                inputEntities: InputEntityOptions(builder, mergeWithPrev),
                entity: seeds.Aggregate
                (
                    builder.Entity,
                    (current, seed) =>
     {
         var newWorkflow = Entity.Make(
             guid: builder.Guid.Add(seed),
             val: current.Value.Step(seed)
             );
         return newWorkflow;
     }
                ),
                seeds: mergeWithPrev?builder.Seeds.Concat(seeds).ToList() : seeds.ToList()
                ));
 }
Ejemplo n.º 12
0
        public async Task ListRepos(IDialogContext context, LuisResult result)
        {
            string token = await ValidateLoggedInAsync(context);

            if (!string.IsNullOrEmpty(token))
            {
                EntityRecommendation eScope;
                result.TryFindEntity("ScopeType::Scope", out eScope);

                IReadOnlyList <Repository> repos = await GitHubCommands.GetRepoList(token, eScope?.Entity);

                string msg;
                if (!repos.Any())
                {
                    msg = "You don't own any repos on GitHub.";
                }
                else
                {
                    msg = repos.Aggregate($"You own the following {eScope?.Entity} repos: ", (current, repo) => current + Environment.NewLine + $"* [{repo.Name}]({repo.HtmlUrl})");
                }
                await context.PostAsync(msg);
            }

            context.Wait(MessageReceived);
        }
Ejemplo n.º 13
0
        public void Flatten_Aggregated_List_Combined_With_Selector_Argument()
        {
            var result = _generator.SelectMany(i => _list.Aggregate((s, s1) => s + s1) + i);

            Assert.AreEqual('F', result.Generate());
            Assert.AreEqual('o', result.Generate());
            Assert.AreEqual('o', result.Generate());
            Assert.AreEqual('B', result.Generate());
            Assert.AreEqual('a', result.Generate());
            Assert.AreEqual('r', result.Generate());
            Assert.AreEqual('0', result.Generate());

            Assert.AreEqual('F', result.Generate());
            Assert.AreEqual('o', result.Generate());
            Assert.AreEqual('o', result.Generate());
            Assert.AreEqual('B', result.Generate());
            Assert.AreEqual('a', result.Generate());
            Assert.AreEqual('r', result.Generate());
            Assert.AreEqual('1', result.Generate());

            Assert.AreEqual('F', result.Generate());
            Assert.AreEqual('o', result.Generate());
            Assert.AreEqual('o', result.Generate());
            Assert.AreEqual('B', result.Generate());
            Assert.AreEqual('a', result.Generate());
            Assert.AreEqual('r', result.Generate());
            Assert.AreEqual('2', result.Generate());
        }
Ejemplo n.º 14
0
        public void Register(Identifier name, IReadOnlyList <IBlockProperty> properties, IReadOnlyList <dynamic> defaultValues)
        {
            var blockId = _blockStates.Count;
            var block   = new Block(blockId, name, properties, defaultValues);

            _blocks[name] = block;

            Logger.Debug("Registering block {0}: {1}", blockId, block);
            var stateCount = properties.Aggregate(1, (current, property) => current * property.ValueCount);

            for (var blockData = 0; blockData < stateCount; blockData++)
            {
                var propertyCount = properties.Count;

                var tmp   = blockData;
                var props = new dynamic[propertyCount];
                for (var j = propertyCount - 1; j >= 0; j--)
                {
                    var property = properties[j];

                    var propertySize = property.ValueCount;
                    var valueIndex   = tmp % propertySize;
                    tmp /= propertySize;

                    var value = property.GetValue(valueIndex);
                    props[j] = value;
                }

                var stateId = blockId + blockData;
                _blockStates[stateId] = new BlockState(stateId, block, props);
                Logger.Debug("Registering block state {0}: {1}", stateId, _blockStates[stateId]);
            }
        }
Ejemplo n.º 15
0
    static public Result <string, IImmutableDictionary <IImmutableList <string>, IReadOnlyList <byte> > > LoadFromAssemblyManifestResourceStreamContents(
        IReadOnlyList <IReadOnlyList <string> > filePaths,
        string resourceNameCommonPrefix,
        Assembly assembly)
    {
        var seed =
            Result <string, IImmutableDictionary <IImmutableList <string>, IReadOnlyList <byte> > > .ok(
                ImmutableDictionary <IImmutableList <string>, IReadOnlyList <byte> > .Empty
                .WithComparers(EnumerableExtension.EqualityComparer <IImmutableList <string> >()));

        return
            (filePaths
             .Aggregate(
                 seed: seed,
                 func: (aggregate, filePath) =>
        {
            if (aggregate.Ok == null)
            {
                return aggregate;
            }

            var resourceName = resourceNameCommonPrefix + string.Join(".", filePath);

            var fileContent = GetManifestResourceStreamContentAsListOfBytes(assembly, resourceName);

            if (fileContent == null)
            {
                return Result <string, IImmutableDictionary <IImmutableList <string>, IReadOnlyList <byte> > > .err("Failed to get content for resource: " + resourceName);
            }

            return
            aggregate.map(dict => dict.SetItem(filePath.ToImmutableList(), fileContent));
        }));
    }
Ejemplo n.º 16
0
        public override IReadOnlyList <Vector2> Apply(Func <double> random, INamedDataCollection metadata, IReadOnlyList <Vector2> footprint, IReadOnlyList <Vector2> basis, IReadOnlyList <Vector2> lot)
        {
            var center  = footprint.Aggregate((a, b) => a + b) / footprint.Count;
            var radians = _angle.SelectFloatValue(random, metadata).ToRadians();

            return(footprint.Select(a => Vector3.Transform((a - center).X_Y(0), Quaternion.CreateFromAxisAngle(Vector3.UnitY, radians)).XZ() + center).ToArray());
        }
Ejemplo n.º 17
0
 public override int GetHashCode()
 {
     if (_typeArgs != null)
     {
         return(_typeArgs.Aggregate(_typeName.GetHashCode(), (h, s) => h + 37 * ObjectComparer.Instance.GetHashCode(s)));
     }
     return(_typeName.GetHashCode());
 }
Ejemplo n.º 18
0
 private IOrderItem DecoratePromotions(IOrderItem orderItem, IReadOnlyList <PromotionInfo> promotions)
 {
     if (promotions == null || promotions.Count == 0)
     {
         return(orderItem);
     }
     return(promotions.Aggregate(orderItem, ToPromotionDecorator));
 }
Ejemplo n.º 19
0
        private static IEnumerable <string> Transpose(IReadOnlyList <string> array)
        {
            var messageLength = array.First().Length;

            for (var i = 0; i < messageLength; i++)
            {
                yield return(array.Aggregate("", (current, t) => current + t[i]));
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Returns the hash code of the current <see cref="ArrayNode"/>.
        /// </summary>
        public override int GetHashCode()
        {
            unchecked
            {
                var nameHash = Name != null?Comparers.NodeName.GetHashCode(Name) : 0;

                return(nameHash * 397 ^ children.Aggregate(children.Count, (current, element) => current * 397 ^ (element?.GetHashCode() ?? 0)));
            }
        }
Ejemplo n.º 21
0
        private static void PrintBasicStatistics(History history, IReadOnlyList <Message> textMessages, string[] words)
        {
            // First and last message
            var startDate = textMessages[0].SendDate;
            var endDate   = textMessages.Last().SendDate;

            var basicStatsTable = new ConsoleTable("First message", startDate.ToString(CultureInfo.CurrentCulture))
                                  .AddRow("Last Message", endDate);

            // History timespan
            var totalMonths = (endDate.Year - startDate.Year) * 12 + endDate.Month - startDate.Month;

            totalMonths += endDate.Day < startDate.Day ? -1 : 0;

            var years    = totalMonths / 12;
            var months   = totalMonths % 12;
            var days     = endDate.Subtract(startDate.AddMonths(totalMonths)).Days;
            var timeSpan = $"{years} year(s) {months} month(s) {days} day(s)";

            basicStatsTable.AddRow("Timespan", timeSpan);

            // Message statistics
            var emptyDayCount    = history.MissingDates.Aggregate(0, (sum, date) => sum + (date.To - date.From).Days);
            var totalDayCount    = (endDate - startDate).Days;
            var percentageString = ((double)emptyDayCount / totalDayCount * 100).ToString("N2") + "%";

            var emptyDayText = $"{emptyDayCount} (out of {totalDayCount} days) ({percentageString})";

            // Message types
            var messageTypeCounts = history.Messages.GroupBy(message => message.Type)
                                    .Select(typeGroup => (typeGroup.Key, typeGroup.Count()))
                                    .ToDictionary(countTuple => countTuple.Key, countTuple => countTuple.Item2);

            basicStatsTable.AddRow("Number of days without activity", emptyDayText)
            .AddRow("Number of text messages", messageTypeCounts[MessageTypes.Text].ToString("N0"))
            .AddRow("Number of removed messages", messageTypeCounts[MessageTypes.Removed].ToString("N0"))
            .AddRow("Number of status messages", messageTypeCounts[MessageTypes.Status].ToString("N0"))
            .AddRow("Number of files sent", messageTypeCounts[MessageTypes.File].ToString("N0"))
            .AddRow("Number of calls", messageTypeCounts[MessageTypes.Call].ToString("N0"));

            // Average number of messages
            basicStatsTable.AddRow("Average number of messages a day",
                                   ((double)textMessages.Count / totalDayCount).ToString("N2"));

            // Word and character statistics
            basicStatsTable.AddRow("Number of words", words.Length.ToString("N0"));

            var characterCount = textMessages.Aggregate(0, (current, message) => current + message.Value.Length);

            basicStatsTable.AddRow("Number of characters", characterCount.ToString("N0"));

            basicStatsTable.AddRow("Average message length",
                                   $"{(double) words.Length / textMessages.Count:N2} words")
            .AddRow("Average word length", $"{(double) characterCount / words.Length:N2} characters");

            basicStatsTable.Write(Format.Alternative);
        }
Ejemplo n.º 22
0
 private static string MultipleMatchingErrorMessage(string name, IReadOnlyList <string> candidates, string assemblyName)
 {
     return
         (string.Format(
              "Multiple matches for name '{0}' were found in the assembly '{2}'. \n\nFound resources: {1}",
              name,
              candidates.Aggregate("", (accu, s) => accu + "\n" + s),
              assemblyName));
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Marks <see cref="Ship"/> as destroyed
        /// </summary>
        public void Destroy()
        {
            if (isDestroyed)
            {
                throw new InvalidOperationException($"Ship positioned on cells: {cells.Aggregate("", (p, n) => p + " " + n.ToString())} was already destroyed");
            }

            isDestroyed = true;
        }
        static string ToList(IReadOnlyList <object> items)
        {
            if (items == null)
            {
                return(string.Empty);
            }

            return(items.Aggregate(string.Empty,
                                   (s, o) => s + (s.Length == 0 ? "" : ", ") + ((CollectionViewGalleryTestItem)o).Caption));
        }
Ejemplo n.º 25
0
 private static string ResourceNotFoundErrorMessage(string name, IReadOnlyList <string> candidates, string assemblyName)
 {
     return
         (string.Format(
              "The resource with name '{0}' that matches the given namesspace could not be found in the assembly '{2}'. "
              + "Did you set the 'Build Action' property to 'Embedded Resource'? \n\nFound resources: {1}",
              name,
              candidates.Aggregate("", (accu, s) => accu + "\n" + s),
              assemblyName));
 }
        public LambdaExpression ConstructResult()
        {
            var composed = resolvers.Reverse().Aggregate(
                Identity(GetCurrentReturnType()),
                (current, prev) => new PreambleReplacement(current).Replace(prev)
                );
            var finalResult = constructionVisitors.Aggregate(composed, (prev, next) => next.VisitAndConvert(prev, nameof(ConstructResult)));

            return(finalResult);
        }
Ejemplo n.º 27
0
        // Getting SVG path element string from a traced path
        internal static StringBuilder AppendSegments(StringBuilder stringBuilder, IReadOnlyList <Segment> segments, ColorReference color)
        {
            // Path
            stringBuilder.Append($"<path {color.ToSvgString()}d=\"M {segments.First().Start.X} {segments.First().Start.Y} ");
            //http://stackoverflow.com/a/217814/294804
            segments.Aggregate(stringBuilder, (sb, segment) => sb.Append(segment.ToPathString())).Append("Z\" />");

            // Rendering control points
            return(segments.Where(s => s.Radius > 0).Aggregate(stringBuilder, (sb, segment) => sb.Append(segment.ToControlPointString())));
        }
Ejemplo n.º 28
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (int)TwoGramCount;
         hashCode = (hashCode * 397) ^ (int)N1PlusStarww;
         hashCode = (hashCode * 397) ^ NwwStarCount.GetHashCode();
         hashCode = ThreeGramCounts?.Aggregate(hashCode, (current, threeGram) => (int)((((current * 397) ^ threeGram.Key) * 397) ^ threeGram.Value)) ?? hashCode;
         hashCode = MostLikelies?.Aggregate(hashCode, (current, count) => (current * 397) ^ count) ?? hashCode;
         return(hashCode);
     }
 }
Ejemplo n.º 29
0
        public CompilationUnitSyntax Generate(CompilationUnitSyntax compilationUnitSyntax, ClassToGenerate classToGenerate)
        {
            var classDeclarationSyntax = _syntaxGeneratorFacade.GetClassSyntax(classToGenerate.ClassName);

            classDeclarationSyntax = _classDeclarationGenerators
                                     .Aggregate(classDeclarationSyntax, (current, classDeclarationGenerator) => classDeclarationGenerator.Generate(current, classToGenerate));

            var @namespace = _syntaxGeneratorFacade.GetNamespace(_namespace);

            @namespace = @namespace.AddMembers(classDeclarationSyntax);
            return(compilationUnitSyntax.AddMembers(@namespace));
        }
Ejemplo n.º 30
0
 public IValue Serialize()
 {
     return(List.Empty
            .Add(NameWithHash.Serialize())
            .Add(CharacterId.Serialize())
            .Add(Level.Serialize())
            .Add(HairIndex.Serialize())
            .Add(LensIndex.Serialize())
            .Add(EarIndex.Serialize())
            .Add(TailIndex.Serialize())
            .Add(Costumes.Aggregate(List.Empty, (current, costume) => current.Add(costume.Serialize())))
            .Add(Equipments.Aggregate(List.Empty, (current, equipment) => current.Add(equipment.Serialize()))));
 }
Ejemplo n.º 31
0
 public static ExprType GetType(ExprType base_type, IReadOnlyList<Int32> indices) =>
     indices.Aggregate(base_type, GetType);