static string BuildTableSql(IEnumerable<string> tablesToDelete)
 {
     string sql = tablesToDelete.Aggregate(string.Empty, (current, tableName) =>
                 current + string.Format("delete from [{0}];", tableName));
     sql += tablesToDelete.Aggregate(String.Empty, (current, tableName) =>
         current + string.Format("IF EXISTS (SELECT 1 FROM sys.identity_columns WHERE [object_id] = OBJECT_ID(N'{0}', N'U') "
                  + "AND last_value IS NOT NULL) BEGIN DBCC CHECKIDENT('{0}', 'RESEED', 0) END;", tableName));
     return sql;
 }
Example #2
0
File: 3.cs Project: damdud/Lab02
 public int Calculate(Operation op, IEnumerable<int> arguments)
 {
     switch (op)
     {
         case Operation.Sum:
             return arguments.Aggregate(0, (a, b) => a + b);
         case Operation.Product:
             return arguments.Aggregate(1, (a, b) => a * b);
         case Operation.Aseq:
             //return arguments.Aggregate(1, (a, b, c ) => );
         default:
             throw new ArgumentOutOfRangeException(nameof(op), op, "unknown operation");
     }
 }
 public static MvcHtmlString ToMapJson(this HtmlHelper html, IEnumerable<dynamic> contents)
 {
     var json = contents.Aggregate(
         string.Empty,
         (current, content) => current + string.Concat(ToMapJson(html, content, true).ToHtmlString(), ","));
     return new MvcHtmlString(json.TrimEnd(','));
 }
Example #4
0
 protected string GetRowList(IEnumerable<int> rowList)
 {
     if (rowList == null) return string.Empty;
     string val = rowList.Aggregate(string.Empty, (current, row) => current + (row.ToString() + ","));
     if (val.EndsWith(",")) val = val.Remove(val.LastIndexOf(','));
     return "[" + val + "]";
 }
Example #5
0
 private string GetModuleFileName(IEnumerable<string> idSegments)
 {
     var filePath = idSegments.Aggregate(
         this.httpServer.MapPath(this.config.ModuleRootUrl),
         Path.Combine) + ".js";
     return filePath;
 }
Example #6
0
        public override SyntaxNode Visit(SyntaxNode node)
        {
            var processedNode = node;

            if (DefaultHooks != null)
            {
                processedNode = DefaultHooks?.Aggregate(node, (p, f) => f(p));
                if (processedNode != node)
                {
                    return(Visit(processedNode));
                }
            }

            var nodeType = node?.GetType();

            if (Hooks != null)
            {
                processedNode = Hooks[nodeType].Aggregate(node, (p, f) => f(p));
                if (processedNode != node)
                {
                    return(Visit(processedNode));
                }
            }

            return(base.Visit(processedNode));
        }
 public static KeyValue GetKeyValue(this KeyValue This, IEnumerable<string> pars)
     => pars.Aggregate(This, (current, p) => {
         var newC = current[p];
         if (newC == KeyValue.Invalid)
             throw new KeyNotFoundException($"{p} key is not found");
         return newC;
     });
        private static string BuildMessage(IEnumerable<string> names)
        {
            const string MESSAGE = "Missing values for the following mandatory elements: {0}";
            string missingElements = names.Aggregate("", (s, s1) => s + (s.Any() ? ", " : "") + s1);

            return string.Format(MESSAGE, missingElements);
        }
Example #9
0
 /// <summary>
 /// Gets the hash code for the specified collection.
 /// </summary>
 /// <typeparam name="T">
 /// The type of value contained in the collection.
 /// </typeparam>
 /// <param name="values">
 /// The values to retrieve a hash code for.
 /// </param>
 /// <returns>
 /// A hash code based on ORing all the hash codes for the specified values.
 /// </returns>
 public static int GenerateHashCode <T>(IEnumerable <T> values)
 {
     unchecked
     {
         return(values?.Aggregate(0, AggregateHash) ?? 0);
     }
 }
Example #10
0
File: 3.cs Project: Mehrunes/Lab02
 public int Calculate(Operation op, IEnumerable<int> arguments)
 {
     switch (op)
     {
         case Operation.Sum:
             return arguments.Aggregate(0, (a, b) => a + b);
         case Operation.Product:
             return arguments.Aggregate(1, (a, b) => a * b);
         case Operation.Ndec:
             return IsNonDecreasingSequence(arguments);
         case Operation.Aseq:
             return IsArithmeticSequence(arguments);
         default:
             throw new ArgumentOutOfRangeException(nameof(op), op, "unknown operation");
     }
 }
 private static string GetGenericParamString(IEnumerable<string> typeParamString)
 {
     var genericParamString = typeParamString
         .Aggregate("", (s, i) => string.Format("{0}{1},", s, i))
         .TrimEnd(',');
     return genericParamString;
 }
 public string Delimeted(IEnumerable<string> values , string delimeter)
 {
     if (values == null) return String.Empty;
     if (values.Count() == 0 ) return String.Empty;
     
     return values.Aggregate((m, n) => m + delimeter + n);
 }
Example #13
0
        /// <summary>Creates a settings file. Settings files include teams participating in the save, as well as the default import/export folder.</summary>
        /// <param name="activeTeams">The active teams.</param>
        /// <param name="folder">The default import/export folder.</param>
        private static void createSettingsFile(IEnumerable<Dictionary<string, string>> activeTeams, string folder)
        {
            var s1 = "Folder$$" + folder + "\n";
            var s2 = activeTeams.Aggregate("Active$$", (current, team) => current + (team["ID"] + "$%"));
            s2 = s2.Substring(0, s2.Length - 2);
            s2 += "\n";

            var stg = s1 + s2;

            SaveFileDialog sfd = null;
            Tools.AppInvoke(
                () =>
                    {
                        sfd = new SaveFileDialog
                            {
                                Title = "Save Active Teams List",
                                Filter = "Active Teams List (*.red)|*.red",
                                DefaultExt = "red",
                                InitialDirectory = App.AppDocsPath
                            };
                        sfd.ShowDialog();
                    });

            if (String.IsNullOrWhiteSpace(sfd.FileName))
            {
                return;
            }

            var sw = new StreamWriter(sfd.FileName);
            sw.Write(stg);
            sw.Close();
        }
Example #14
0
 private void LogUnresolvedConstructor(IEnumerable<ParameterInfo> unresolvedDependencies, ref StringBuilder unresolvedDependenciesMessage)
 {
     unresolvedDependenciesMessage = unresolvedDependenciesMessage ?? new StringBuilder();
     string message = unresolvedDependencies.Aggregate(string.Empty, (str, pi) => str + pi.ParameterType);
     this.Log.WriteDebug("Ignoring constructor, following dependencies didn't have a registration:" + message);
     unresolvedDependenciesMessage.Append("Constructor: ").AppendLine(message);
 }
Example #15
0
        public static void ModifyFile( string pathToFile, IEnumerable< Mapping > mappings )
        {
            string allText = null;
            Encoding originalEncoding;
            using (var fileStream = File.OpenText(pathToFile))
            {
                originalEncoding = fileStream.CurrentEncoding;
                allText = fileStream.ReadToEnd();
            }

            if ( string.IsNullOrEmpty( allText ) )
            {
                return ;
            }

            if(!anythingNeedsReplacing( allText, mappings ) )
            {
                Console.WriteLine(@"nothing to modify in " + pathToFile);
                return ;
            }

            Console.WriteLine(@"modifying " + pathToFile);

            allText = mappings.Aggregate(
                allText,
                (current, eachMapping) => current.Replace(eachMapping.OldText, eachMapping.NewText));

            File.WriteAllText(pathToFile, allText, originalEncoding);
        }
        public TracingCallTreeConvertor(IEnumerable<TracingCallTree> tracingCallTrees)
        {
            _globalAggregatedValues = new TracingGlobalAggregatedValues();

            var flattenedTreeList = new List<TracingCallTreeElem>();
            foreach (TracingCallTree callTree in tracingCallTrees)
            {
                _globalAggregatedValues.TotalActiveTime += callTree.UserModeDurationHns + callTree.KernelModeDurationHns;
                FlattenCallTree(callTree.RootElem, flattenedTreeList);
            }

            _aggregators = flattenedTreeList.GroupBy(
                elem => elem.MethodMetadata).Select(
                    grouping =>
                        {
                            MethodMetadata methodMetadata = grouping.Key;
                            var aggregator = new TracingMethodAggregator(methodMetadata);
                            aggregator.AggregateRange(grouping);
                            return aggregator;
                        });

            _globalAggregatedValues.TotalCycleTime = _aggregators.Aggregate((ulong) 0,
                                                                            (sum, methodAgr) =>
                                                                            sum + methodAgr.CycleTime);

            CreateMethodByMetadataDictionary();
            // InterconnectMethodCalls(aggregators);
            CreateCriteriaContext();
            PopulateSourceFiles();
        }
        public static string PerformTemplate(string path, string content, Dictionary<string, string> sections, IEnumerable<KeyValuePair<string,string>> template , string repository = "Backend.git", string branch = "template")
        {
            var resultPath = Path.ChangeExtension(path, ".html");

            var data = GetTemplate(resultPath, repository, branch) ?? GetTemplate("default.html", repository, branch);

            if (data == null) return content;

            var sectionTemplate = GetTemplate(Path.GetFileNameWithoutExtension(path) + "_section.html", repository, branch) ??
                                  GetTemplate("_section.html", repository, branch);

            var sectionBuilder = new StringBuilder();

            if (sectionTemplate != null)
            {
                foreach (var section in sections)
                {
                    sectionBuilder.Append(sectionTemplate.Replace("[id]", section.Key).Replace("[name]", section.Value));
                }
            }

            var text = data
                .Replace("[content]", content)
                .Replace("[nav]", sectionBuilder.ToString());

            return template.Aggregate(text, (current, keyValuePair) => current.Replace("[" + keyValuePair.Key + "]", keyValuePair.Value));
        }
Example #18
0
        public IEnumerable<string> AddUniqueConstraint(string tableName, IEnumerable<string> columnNames, string constraintName)
        {
            string columns = columnNames.Aggregate(String.Empty, (current, column) => current + (Escape(column) + ","));
            columns = columns.TrimEnd(',');

            yield return string.Format("CREATE UNIQUE INDEX {0} ({1}) ON {2}", Escape(constraintName), columns, tableName);
        }
Example #19
0
        public static IEnumerable<KeyValuePair<string, string>> SplitWithSeparator(this string str, IEnumerable<string> separator,
			StringComparison comparisonType = StringComparison.CurrentCulture, StringSplitOptions options = StringSplitOptions.None)
        {
            IEnumerable<KeyValuePair<int, string>> indexes = new Dictionary<int, string>();
            indexes = separator.Aggregate(indexes, (current, s) => current.Union(str.IndexOfAll(s, comparisonType).ToDictionaryValue(i => str.Substring(i, s.Length))));
            int lastIndex = 0;
            var list = new List<KeyValuePair<string, string>>();
            foreach (KeyValuePair<int, string> kvp in indexes.OrderBy(a => a.Key))
            {
                string substring = str.Substring(lastIndex, kvp.Key - lastIndex);
                list.Add(new KeyValuePair<string, string>(substring, kvp.Value));
                lastIndex += substring.Length + kvp.Value.Length;
            }
            list.Add(new KeyValuePair<string, string>(str.Substring(lastIndex), null));
            return list.Where(a =>
            {
                switch (options)
                {
                    case StringSplitOptions.None:
                        return true;
                    case StringSplitOptions.RemoveEmptyEntries:
                        return a.Key != "";
                    default:
                        throw new NotSupportedException("unrecognized StringSplitOptions");
                }
            });
        }
Example #20
0
 public static string PrettyPrint(IEnumerable<PositionInText> positions)
 {
     return positions.Aggregate(
                         "positions: ",
                         (res, next) => res + ", " + next.ToString()
                      );
 }
Example #21
0
 public IEnumerable<System.Drawing.Rectangle> ComputeView(IEnumerable<MangaParser.Graphics.IPolygon> polygons)
 {
     // Union over all bits
     return new Rectangle[] { polygons.Aggregate(
         polygons.First().BoundingBox,
         (Rectangle res, IPolygon p2) => Rectangle.Union(res, p2.BoundingBox)) };
 }
Example #22
0
        public Task<IEnumerable<rate>> TakeExchangesAsync(IEnumerable<string> currencies, string baseCurrency, IEnumerable<string> columnsList = null)
        {
            // if there weren't any selections - default parameter
            if (columnsList == null) columnsList = new List<string> {"*"};

            currencies = currencies.Select(x => x += baseCurrency);

            // provides async result in the caller
            var tcs = new TaskCompletionSource<IEnumerable<rate>>();

            var resource = String.Format(@"yql?q=select {3} from yahoo.finance.xchange {0}{1}{2}",
                                          "where pair in (%22" + currencies.Aggregate((a, b) => String.Format("{0}%22,%22{1}", a, b)) + "%22)",
                                          "&format=json",
                                          "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
                                          columnsList.Aggregate((a, b) => a + "," + b))
                .HtmlDecode();

            var request = new RestRequest(resource, Method.GET);

            _client.ExecuteAsync<RootObject>(request, result => tcs.SetResult(result == null
                ? null
                : result.Data.Query.Results.Rate));

            return tcs.Task;
        }
        /// <summary>
        /// Построить скрип авторизации
        /// </summary>
        /// <param name="collection">Колекция контролов</param>
        /// <param name="isEdit"></param>
        /// <param name="menupage">Ид меню</param>
        /// <param name="roles">Ид роли</param>
        public void Constructor(IEnumerable<WebPageBaseViewModel> collection, bool isEdit, int menupage, IEnumerable<int> roles)
        {
            foreach (WebPageBaseViewModel model in collection)
            {
                string description = string.Format("ru-RU:{0};en-EN:{1};", model.RuDescription, model.EnDescription);
                string table = "null";
                if (model is ModalViewModel)
                {
                    ModalViewModel m = model as ModalViewModel;
                    if (!string.IsNullOrEmpty(m.TableName))
                        table = "'" + m.TableName + "'";
                }
                _stringBuilder.AppendFormat("--{0}\n", model.FieldInDb);
                _stringBuilder.AppendFormat(
                        "INSERT INTO [ut_MenuField] (idpage,fld, idparent, fldbd, tabbd, isNotEdited, nam) VALUES ({0}, '{1}', null, '{2}', {3}, 0, '{4}');\n",
                        menupage,
                        isEdit ? model.ControlIdEdit : model.ControlIdView,
                        model.FieldInDb ?? "null",
                        table,
                        description);

                _stringBuilder.AppendFormat("set @id  = scope_identity();\n");
                _stringBuilder.AppendFormat("insert into [ut_RoleField] (idrole, idfld,visability)\nvalues\n");

                string rs = roles.Aggregate("", (s, a) =>
                {
                    s += string.Format("({0},@id,{1}),\n", a, Visability);
                    return s;
                }, (result) => result.TrimEnd(new char[] { ',', '\n' }));
                _stringBuilder.AppendFormat(rs + "\n");
                Constructor(model.Children, isEdit, menupage, roles);
            }
        }
 public static float BerechneErgebnis(IEnumerable<string> eingaben)
 {
     var initialStack = Listen.Empty<float>();
     return eingaben
         .Aggregate(initialStack, EingabeVerarbeiten)
         .Head();
 }
        public static CardViewModel ApplyTransformPipeline(XPathNavigator powerElement,
			IEnumerable<Func<PowerPipelineState, PowerPipelineState>> pipeline, XmlDocument character)
        {
            var state = new PowerPipelineState(powerElement, character.CreateNavigator());
            state = pipeline.Aggregate(state, (current, op) => op(current));
            return state.ViewModel;
        }
Example #26
0
        /// <summary>
        /// Creates a new resource locator which will default to the provided
        /// resource file name.
        /// </summary>
        /// <param name="resourceFileConfigs">All registered implementations for IResourceLocatorConfig</param>
        public ResourceLocator(IEnumerable<IResourceLocatorConfig> resourceFileConfigs)
        {
            var resourceFiles = new string[] { };
            resourceFiles = resourceFileConfigs.Aggregate(resourceFiles, (current, config) => current.Union(config.ResourceFileKeys).ToArray());

            this._defaultResourceFileNames = resourceFiles;
        }
Example #27
0
 public static string GenerateGenreFilter(IEnumerable<string> genres)
 {
     var genreFilter = genres.Aggregate(String.Empty,
         (current, genre) => current + String.Format(SparqlResources.ContainsPattern, genre.ToLower()));
     genreFilter = genreFilter.Substring(0, genreFilter.LastIndexOf("||", StringComparison.Ordinal));
     return genreFilter;
 }
Example #28
0
        private IEnumerable <Models.Location> MapLocations(IEnumerable <Location> locations)
        {
            return(locations?.Aggregate(new List <Models.Location>(), (locs, l) =>
            {
                var existingBox = _dataContext.Boxes.Find(l.BoxNo);
                if (existingBox != null)
                {
                    // Adds to existing box
                    locs.Add(new Models.Location
                    {
                        Box = l.BoxNo,
                        No = l.Qty,
                        Cellarversion = 1,
                    });
                }
                else if (l.BoxNo.HasValue)
                {
                    // Adds to new box, when provided with a box no
                    locs.Add(new Models.Location
                    {
                        BoxNavigation = new Models.Box
                        {
                            Boxno = l.BoxNo.Value
                        },
                        No = l.Qty,
                        Cellarversion = 1
                    });
                }

                return locs;
            }).ToList());
        }
 private static int CombineHashCodes(IEnumerable<object> objs)
 {
     unchecked
     {
         return objs.Aggregate(17, (current, obj) => current * 23 + (obj != null ? obj.GetHashCode() : 0));
     }
 }
        /// <summary>
        ///     Gets the effective global properties for an item that will get passed to <see cref="MSBuild.Projects"/>.
        /// </summary>
        /// <remarks>
        ///     The behavior of this method matches the hardcoded behaviour of the msbuild task
        ///     and the <paramref name="globalPropertyModifiers"/> parameter can contain other mutations done at build time in targets / tasks
        /// </remarks>
        private static PropertyDictionary <ProjectPropertyInstance> GetGlobalPropertiesForItem(
            ProjectItemInstance projectReference,
            PropertyDictionary <ProjectPropertyInstance> requesterGlobalProperties,
            IEnumerable <GlobalPropertiesModifier> globalPropertyModifiers = null)
        {
            ErrorUtilities.VerifyThrowInternalNull(projectReference, nameof(projectReference));
            ErrorUtilities.VerifyThrowArgumentNull(requesterGlobalProperties, nameof(requesterGlobalProperties));

            var properties           = SplitPropertyNameValuePairs(ItemMetadataNames.PropertiesMetadataName, projectReference.GetMetadataValue(ItemMetadataNames.PropertiesMetadataName));
            var additionalProperties = SplitPropertyNameValuePairs(ItemMetadataNames.AdditionalPropertiesMetadataName, projectReference.GetMetadataValue(ItemMetadataNames.AdditionalPropertiesMetadataName));
            var undefineProperties   = SplitPropertyNames(projectReference.GetMetadataValue(ItemMetadataNames.UndefinePropertiesMetadataName));

            var defaultParts = new GlobalPropertyPartsForMSBuildTask(properties.ToImmutableDictionary(), additionalProperties.ToImmutableDictionary(), undefineProperties.ToImmutableList());

            var globalPropertyParts = globalPropertyModifiers?.Aggregate(defaultParts, (currentProperties, modifier) => modifier(currentProperties, projectReference)) ?? defaultParts;

            if (globalPropertyParts.AllEmpty())
            {
                return(requesterGlobalProperties);
            }

            // Make a copy to avoid mutating the requester
            var globalProperties = new PropertyDictionary <ProjectPropertyInstance>(requesterGlobalProperties);

            // Append and remove properties as specified by the various metadata
            MergeIntoPropertyDictionary(globalProperties, globalPropertyParts.Properties);
            MergeIntoPropertyDictionary(globalProperties, globalPropertyParts.AdditionalProperties);
            RemoveFromPropertyDictionary(globalProperties, globalPropertyParts.UndefineProperties);

            return(globalProperties);
        }
 public static string ToCsv <T>(this IEnumerable <T> source, Func <T, string> transformer = null, string separator = ", ")
 {
     if (transformer == null)
     {
         transformer = A => A.ToString();
     }
     return(source?.Aggregate("", (run, cur) => run + (string.IsNullOrEmpty(run) ? "" : separator) + transformer(cur)));
 }
Example #32
0
 private string ReplaceWithKeys(IEnumerable<KeyValuePair<string, string>> keys, string message)
 {
     if (keys == null)
     {
         throw new ArgumentNullException();
     }
     return keys.Aggregate(message, (current, key) => current.Replace(key.Key, key.Value));
 }
Example #33
0
 public static string ColumnsWithAlias(string table, IEnumerable<string> columns)
 {
     return columns.Aggregate(
         new StringBuilder(),
         (sb, s) => sb.AppendFormat(sb.Length == 0 ? "{0}{1}{2}.{0}{3}{2} AS {1}{3}" : "{4}{0}{1}{2}.{0}{3}{2} AS {1}{3}",
             OpenQuote, table, CloseQuote, s, Seperator),
         sb => sb.ToString());
 }
Example #34
0
 public static string Params(IEnumerable<string> columns)
 {
     return columns.Aggregate(
         new StringBuilder(),
         (sb, s) => sb.AppendFormat(sb.Length == 0 ? "@{0}" : "{1}@{0}",
             s, Seperator),
         sb => sb.ToString());
 }
Example #35
0
        public static string JoinValues <TKey, TValue>(this IEnumerable <KeyValuePair <TKey, TValue> > keyValuePairs,
                                                       string delimiter = "/")
        {
            var result = keyValuePairs?.Aggregate(Empty, (current, next) => current + $"{next.Value}{delimiter}") ??
                         Empty;

            return(result == Empty ? result : result.Remove(result.Length - 1));
        }
Example #36
0
 public static string Sets(IEnumerable<string> columns)
 {
     return columns.Aggregate(
         new StringBuilder(),
         (sb, s) => sb.AppendFormat(sb.Length == 0 ? "{0}{1}{2}=@{1}" : "{3}{0}{1}{2}=@{1}",
             OpenQuote, s, CloseQuote, Seperator),
         sb => sb.ToString());
 }
Example #37
0
        public static string JoinKeyValuePairs <TKey, TValue>(this IEnumerable <KeyValuePair <TKey, TValue> > keyValuePairs,
                                                              string seed = "?", string delimiter = "&", string keyValueSeparator = "=")
        {
            var result =
                keyValuePairs?.Aggregate(seed, (current, next) => current + $"{DetermineKeyEmptyOrNull(next.Key, keyValueSeparator)}{next.Value}{delimiter}") ??
                Empty;

            return(result == Empty ? result : result.Remove(result.Length - 1));
        }
Example #38
0
        /// <summary>
        /// Get a list of properties having a custom attribute with their values.
        /// </summary>
        public static IDictionary <string, Tuple <TAttr, object> > GetPropertiesValuesWithAttr <TAttr>(IEnumerable <ReflectionProperty <TAttr> > props, object obj) where TAttr : class
        {
            var dict = new Dictionary <string, Tuple <TAttr, object> >();

            return(props?.Aggregate(dict, (d, p) =>
            {
                d.Add(p.PropertyInfo.Name, new Tuple <TAttr, object>(p.Attribute, p.PropertyInfo.GetValue(obj)));
                return d;
            }));
        }
Example #39
0
        /// <summary>
        /// Get a list of properties having a custom attribute with their values.
        /// </summary>
        public static IDictionary <string, object> GetPropertiesValues(IEnumerable <PropertyInfo> props, object obj)
        {
            var dict = new Dictionary <string, object>();

            return(props?.Aggregate(dict, (d, p) =>
            {
                d.Add(p.Name, p.GetValue(obj));
                return d;
            }));
        }
Example #40
0
 /// <summary>
 ///     Performs a cross join; code is based on this:
 ///     https://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/
 /// </summary>
 /// <typeparam name="T">The type of inner array.</typeparam>
 /// <param name="sequences">The array of arrays.</param>
 /// <returns>An array of all possible combination of passed array items.</returns>
 // ReSharper disable once TooManyDeclarations
 private static IEnumerable <IEnumerable <T> > GetCartesianProduct <T>(this IEnumerable <IEnumerable <T> > sequences)
 {
     return(sequences?.Aggregate(
                new[] { Enumerable.Empty <T>() } as IEnumerable <IEnumerable <T> >,
                (accumulatedSequences, sequence) =>
                accumulatedSequences.SelectMany(
                    accumulatedSequence => sequence,
                    (accumulatedSequence, item) => accumulatedSequence.Concat(new[] { item })
                    )
                ));
 }
Example #41
0
        /// <summary>
        /// Method for calculating collection <paramref name="items"/> hash code
        /// </summary>
        /// <typeparam name="TSource">The type of the elements of sequences</typeparam>
        public static int GetHashCodeWithRespectToOrder <TSource>(
            this IEnumerable <TSource> items,
            Func <TSource, int> hashCodeCalculator = null)
        {
            int GetHashCode(TSource x) => hashCodeCalculator?.Invoke(x) ?? x.GetHashCode();

            unchecked
            {
                return(items?.Aggregate(1, (hash, x) => (hash * 31) ^ GetHashCode(x)) ?? 0);
            }
        }
        public static string ToCsv <T>(this IEnumerable <T> list, string separator = ", ")
        {
            return(list?.Aggregate(string.Empty, (a, b) =>
            {
                if (string.IsNullOrEmpty(a))
                {
                    return b.ToString();
                }

                return string.Concat(a, separator, b);
            }));
        }
Example #43
0
        public static MvcHtmlString AggregatedFieldValues(this HtmlHelper html, IEnumerable <FieldValue> values)
        {
            var sb = new StringBuilder();

            values?.Aggregate(sb, (b, pair) =>
            {
                b.Append(html.Field(pair, true).ToHtmlString());
                return(b);
            });

            return(MvcHtmlString.Create(sb.ToString()));
        }
Example #44
0
 /// <summary>Returns the GCD (Greatest common denominator) for the set of <paramref name="numbers" />.</summary>
 /// <param name="numbers">The set of numbers to run the GCD algorithm against.</param>
 /// <returns>The result of the GCD algorithm or <value>0</value> if the set is empty. This number is always positive.</returns>
 public static long Gcd(IEnumerable <long> numbers)
 {
     try
     {
         return(numbers?.Aggregate(Gcd) ?? 0);
     }
     catch (InvalidOperationException)
     {
         // Sequence contains no elements.
         return(0);
     }
 }
Example #45
0
 public Assembly Compile(string cscToolPath, IEnumerable <ProjectItem> projectItems, IEnumerable <ProjectItem> referenceItems)
 {
     try
     {
         return(CompileInternal(cscToolPath, projectItems, referenceItems));
     }
     catch (Exception ex)
     {
         var files = projectItems?.Aggregate("", (s, i) => $"{s}, {i.Name}");
         LogWarning($"Failed to compile/evaluate {files} - {ex.Message}\r\n{ex.StackTrace}");
     }
     return(null);
 }
Example #46
0
        protected virtual CompilerParameters CreateCompilerOptions(NPath outputDirectory, string outputName, IEnumerable <string> references, IEnumerable <string> defines)
        {
            var outputPath = outputDirectory.Combine(outputName);

            var compilerParameters = new CompilerParameters
            {
                OutputAssembly     = outputPath.ToString(),
                GenerateExecutable = outputName.EndsWith(".exe")
            };

            compilerParameters.CompilerOptions = defines?.Aggregate(string.Empty, (buff, arg) => $"{buff} /define:{arg}");

            compilerParameters.ReferencedAssemblies.AddRange(references.ToArray());

            return(compilerParameters);
        }
Example #47
0
 //combine array to a int type
 internal static int CombineToInt <T>(IEnumerable <T> leftAlign, Func <T, int> fn)
 {
     return(leftAlign?.Aggregate(0, (acc, v) => acc | fn(v))
            ?? ((int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_OkayButton | (int)swPropertyManagerPageOptions_e.swPropertyManagerOptions_CancelButton));
 }
 private static LocalList <IPsiSourceFile> GetPossibleFilesWithScriptUsages(IEnumerable <IPsiSourceFile> files)
 {
     return(files?.Aggregate(new LocalList <IPsiSourceFile>(), AddFile) ?? new LocalList <IPsiSourceFile>());
 }
Example #49
0
 public static string JoinPath(IEnumerable <string?>?parts, DirectorySeparator separator = DirectorySeparator.Universal)
 {
     return(parts?.Aggregate((pathSoFar, nextPart) => JoinPath(pathSoFar, nextPart, separator)) ?? "");
 }
 public static TimeSpan SumOf(IEnumerable <Period> periods) =>
 periods?.Aggregate(new TimeSpan(), (current, period) => current + period.Duration) ?? TimeSpan.Zero;
Example #51
0
 internal static int CombineToInt <T>(IEnumerable <T> leftAlign, Func <T, int> fn)
 {
     return(leftAlign?.Aggregate(0, (acc, v) => acc | fn(v))
            ?? ((int)swAddControlOptions_e.swControlOptions_Enabled | (int)swAddControlOptions_e.swControlOptions_Visible));
 }
Example #52
0
 /// <summary>
 /// Returns a hashcode for an item of type T. Returns 0 if the type is null.
 /// </summary>
 public static int GetHashCodeWithNullSupport <T>(this IEnumerable <T> items)
 {
     return(items?.Aggregate(0, (current, item) => (current * 397) ^ item.GetHashCode()) ?? 0);
 }
Example #53
0
 public static int HashCode <T>(this IEnumerable <T> array) where T : class => array?.Aggregate(1, (current, element) => 31 * current + (element?.GetHashCode() ?? 0)) ?? 0;
Example #54
0
 public static int GetEnumerableHashCode <T>([CanBeNull] this IEnumerable <T> items)
 {
     return(items?.Aggregate(0, (x, o) => (x * 397) ^ o.GetHashCode()) ?? 0);
 }
Example #55
0
 public static string MergeStrings(this IEnumerable <string> items, char separator = ',') =>
 items?.Aggregate((m0, m1) => $"{m0}{separator}{m1}")?.Trim(separator);
Example #56
0
 /// <summary>
 /// Computes the aggregate hash code for <paramref name="values"/>.
 /// </summary>
 /// <typeparam name="TValue">the value type</typeparam>
 /// <param name="values">the enumerable set of values</param>
 /// <returns>the aggregate hash code</returns>
 public static int ComputeHashCode <TValue>(IEnumerable <TValue> values) =>
 values?.Aggregate(
     0, (current, value) => unchecked (current * (int)0xA5555529 + (value?.GetHashCode() ?? 0))
     ) ??
 0;
Example #57
0
 public static int GetValuesHashCode <T>(this IEnumerable <T> ie, Func <T, int> valuesHashCodeFunc = null)
 {
     return(ie?.Aggregate(new StringBuilder(), (b, v) => b.Append(valuesHashCodeFunc?.Invoke(v) ?? v?.ToString().GetHashCode() ?? 0))
            .ToString().GetHashCode()
            ?? 0);
 }
Example #58
0
 public static IQueryable <T> WhereMatchFilters <T>(this IQueryable <T> query, IEnumerable <AdvancedSearchFilter> filters)
     where T : ISongLink
 {
     return(filters?.Aggregate(query, WhereMatchFilter) ?? query);
 }
Example #59
0
 public static IQueryable <Album> WhereMatchFilters(this IQueryable <Album> query, IEnumerable <AdvancedSearchFilter> filters)
 {
     return(filters?.Aggregate(query, WhereMatchFilter) ?? query);
 }
Example #60
0
        /// <summary>
        /// Populates the completion window with data.
        /// </summary>
        /// <param name="items">List of completion data.</param>
        public void Populate(List<ICompletionItem> items)
        {
            completionModel.Clear();

            // Add empty first row.
            completionModel.Append();
            foreach (ICompletionItem item in items)
            {
                IEnumerable<string> descriptionLines = item.Description?.Split(Environment.NewLine.ToCharArray()).Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).Take(2);
                string description = descriptionLines?.Count() < 2 ? descriptionLines.FirstOrDefault() : descriptionLines?.Aggregate((x, y) => x + Environment.NewLine + y);
                completionModel.AppendValues(item.Image, item.DisplayText, item.Units, item.ReturnType, description, item.CompletionText, item.IsMethod);
            }
        }