internal void SetEvidence( IDictionary<string, Tuple<FObservation, FRandomVariable[]>> evidences, IDictionary<string, string> abbreviations) { var evidencesSorted = evidences.OrderBy(kvp => kvp.Key); xEvidenceList.Children.Clear(); foreach (var kvp in evidencesSorted) { // Scenario label. TextBlock scenarioLabel = new TextBlock(); scenarioLabel.Text = kvp.Key; xEvidenceList.Children.Add(scenarioLabel); // Observation values. Observation.Observation obsControl = new Observation.Observation(); var observation = kvp.Value.Item1; var observationVariables = kvp.Value.Item2; obsControl.SetData(observation, observationVariables, abbreviations); xEvidenceList.Children.Add(obsControl); obsControl.Margin = new Thickness(0, 0, 0, 12); } }
public string Sign(string consumerSecret, string url, IDictionary<string, string> data, string httpMethod = "POST") { var orderedFormData = data.OrderBy(kvp => kvp.Key); var normalizedData = NormalizeFormData(orderedFormData); return Sign(consumerSecret, url, normalizedData, httpMethod); }
private static void PrintResultToConsole(IDictionary<string, int> counterOfWords) { foreach (var word in counterOfWords.OrderBy(x => x.Value)) { Console.WriteLine("{0} -> {1}", word.Key, word.Value); } }
public NuGetPackageInfo(string packageId, IDictionary <FrameworkName, string> supportedVersions, string assemblyInfo = null) { PackageId = packageId ?? throw new ArgumentNullException(nameof(packageId)); if (string.IsNullOrWhiteSpace(PackageId)) { throw new ArgumentException(nameof(packageId)); } SupportedVersions = supportedVersions?.OrderBy(x => x.Key.FullName).ToImmutableDictionary() ?? ImmutableDictionary.Create <FrameworkName, string>(); AssemblyInfo = assemblyInfo; }
public ViewBooksViewModel(IEnumerable<BookListView> books, IDictionary<string, string> genres, string selectedGenre, IEnumerable<BookListView> wishlistBooks) { Books = books.OrderByDescending(b => b.Rating); Genres = genres.OrderBy(g => g.Value).ToDictionary(x => x.Key, x => x.Value); WishlistBooks = wishlistBooks; if (!string.IsNullOrWhiteSpace(selectedGenre) && genres.Keys.Contains(selectedGenre)) { SelectedGenre = genres[selectedGenre]; } }
protected string MakeAuthedUrl(string method, IDictionary<string, string> urlParams) { var paramsList = urlParams.OrderBy(e => e.Key) .Select(e => string.Join("=", e.Key, e.Value)) .ToList(); var encryptor = new HashHelper(); var enctyptedTokenAndKey = encryptor.GetMD5Hash(AccessToken + AppSecretKey); var sig = encryptor.GetMD5Hash(string.Concat(paramsList) + enctyptedTokenAndKey); return string.Format("http://api.ok.ru/api/{0}?{1}&access_token={2}&sig={3}", method, string.Join("&", paramsList), AccessToken, sig); }
public static string BuildSig(string secretKey, string method, IDictionary<string, string> parameters) { parameters.Add("method", method); var temp = parameters.OrderBy(x => x.Key); var s = new StringBuilder(); foreach (var p in temp) { s.Append(p.Key); s.Append(p.Value); } s.Append(secretKey); return Md5(s.ToString()); }
public void Set(string path, IDictionary<string, string> routeValues, string source, bool isManaged) { if (path == null) { throw new ArgumentNullException("path"); } var aliasRecord = _aliasRepository.Fetch(r => r.Path == path, o => o.Asc(r => r.Id), 0, 1).FirstOrDefault(); aliasRecord = aliasRecord ?? new AliasRecord { Path = path }; string areaName = null; string controllerName = null; string actionName = null; var values = new XElement("v"); foreach (var routeValue in routeValues.OrderBy(kv => kv.Key, StringComparer.InvariantCultureIgnoreCase)) { if (string.Equals(routeValue.Key, "area", StringComparison.InvariantCultureIgnoreCase) || string.Equals(routeValue.Key, "area-", StringComparison.InvariantCultureIgnoreCase)) { areaName = routeValue.Value; } else if (string.Equals(routeValue.Key, "controller", StringComparison.InvariantCultureIgnoreCase)) { controllerName = routeValue.Value; } else if (string.Equals(routeValue.Key, "action", StringComparison.InvariantCultureIgnoreCase)) { actionName = routeValue.Value; } else { values.SetAttributeValue(routeValue.Key, routeValue.Value); } } aliasRecord.Action = _actionRepository.Fetch( r => r.Area == areaName && r.Controller == controllerName && r.Action == actionName, o => o.Asc(r => r.Id), 0, 1).FirstOrDefault(); aliasRecord.Action = aliasRecord.Action ?? new ActionRecord { Area = areaName, Controller = controllerName, Action = actionName }; aliasRecord.RouteValues = values.ToString(); aliasRecord.Source = source; aliasRecord.IsManaged = isManaged; if (aliasRecord.Action.Id == 0 || aliasRecord.Id == 0) { if (aliasRecord.Action.Id == 0) { _actionRepository.Create(aliasRecord.Action); } if (aliasRecord.Id == 0) { _aliasRepository.Create(aliasRecord); } // Bulk updates might go wrong if we don't flush _aliasRepository.Flush(); } // Transform and push into AliasHolder var dict = ToDictionary(aliasRecord); _aliasHolder.SetAlias(new AliasInfo { Path = dict.Item1, Area = dict.Item2, RouteValues = dict.Item3, IsManaged = dict.Item6 }); }
/// <summary> /// 生成POST的xml数据字符串 /// </summary> /// <param name="postdataDict">>参与生成的参数列表</param> /// <param name="sign">签名</param> /// <returns></returns> public static string GeneralPostdata(IDictionary<string, string> postdataDict, string sign) { var sb2 = new StringBuilder(); sb2.Append("<xml>"); foreach (var sA in postdataDict.OrderBy(x => x.Key))//参数名ASCII码从小到大排序(字典序); { sb2.Append("<" + sA.Key + ">") .Append(Util.Transfer(sA.Value))//参数值用XML转义即可,CDATA标签用于说明数据不被XML解析器解析。 .Append("</" + sA.Key + ">"); } sb2.Append("<sign>").Append(sign).Append("</sign>"); sb2.Append("</xml>"); return sb2.ToString(); }
public static string FormatFromDictionary(this string formatString, IDictionary<string, string> valueDict) { int i = 0; StringBuilder newFormatString = new StringBuilder(formatString); IDictionary<string, int> keyToInt = new Dictionary<string, int>(); foreach (var tuple in valueDict) { newFormatString = newFormatString.Replace("{" + tuple.Key + "}", "{" + i.ToString() + "}"); keyToInt.Add(tuple.Key, i); i++; } // ReSharper disable once CoVariantArrayConversion return string.Format(newFormatString.ToString(), valueDict.OrderBy(x => keyToInt[x.Key]).Select(x => x.Value).ToArray()); }
private string GenerateCacheKey(IDictionary<string, object> parameters, params object[] extraInput) { // generate a cache key for just the parameters List<object> parameterCacheKeyInputs = new List<object>(parameters.Count * 2); foreach (var entry in parameters.OrderBy(o => o.Key, StringComparer.OrdinalIgnoreCase)) { parameterCacheKeyInputs.Add(entry.Key); parameterCacheKeyInputs.Add(entry.Value); } string parametersKey = CacheKeyUtil.GenerateCacheKey(parameterCacheKeyInputs.ToArray()); object[] combinedInputs = new object[] { Duration, Key, parametersKey } .Concat(extraInput).ToArray(); return _cacheKeyPrefix + CacheKeyUtil.GenerateCacheKey(combinedInputs); }
public static int DictionaryHashCode <TKey, TValue>(this IDictionary <TKey, TValue> dictionary, IEqualityComparer <TKey> keyComparer, IEqualityComparer <TValue> valueComparer) { var hashCode = 17; foreach (var kvp in dictionary.OrderBy(x => x.Key)) { hashCode = (hashCode * 23) + keyComparer.GetHashCode(kvp.Key); if (!Equals(kvp.Value, null)) { hashCode = (hashCode * 23) + valueComparer.GetHashCode(kvp.Value); } } return(hashCode); }
private static string GetTempFile(string projectFile, IDictionary <string, string> globalProperties, string toolsVersion) { var stringBuilder = new StringBuilder(); stringBuilder.AppendLine(projectFile); stringBuilder.AppendLine(toolsVersion); foreach (var property in globalProperties.OrderBy(x => x.Key)) { stringBuilder.AppendLine(property.Key); stringBuilder.AppendLine(property.Value); } var hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(stringBuilder.ToString())); return(string.Join(string.Empty, hash.Select(b => b.ToString("x2")).ToArray())); }
private static DependencyContext GetDependencyContext(IDictionary <string, string[]> libraries) { var compileLibraries = new List <CompilationLibrary>(); var runtimeLibraries = new List <RuntimeLibrary>(); foreach (var kvp in libraries.OrderBy(kvp => kvp.Key, StringComparer.Ordinal)) { var compileLibrary = GetCompileLibrary(kvp.Key, kvp.Value); compileLibraries.Add(compileLibrary); var runtimeLibrary = GetRuntimeLibrary(kvp.Key, kvp.Value); runtimeLibraries.Add(runtimeLibrary); } return(GetDependencyContext(compileLibraries, runtimeLibraries)); }
private string BuildUrl(string method, IDictionary <string, string> parameters = null) { var builder = new StringBuilder($"http://ws.audioscrobbler.com/2.0?method={ method }"); if (parameters != null) { parameters.Add("api_key", this._apiKey.Key); foreach (var kv in parameters.OrderBy(kv => kv.Key, StringComparer.Ordinal)) { builder.Append($"&{kv.Key}={kv.Value }"); } var signature = GenerateMethodSignature(method, parameters); builder.Append($"&api_sig={ signature } "); } return(builder.ToString()); }
/// <summary> /// 字典型数据转换为URL参数字符串 /// </summary> /// <param name="this">字典数据源</param> /// <param name="seed">起点初始字符串,默认为空字符串</param> /// <param name="isAsciiSort">是否ASCII排序,默认升序排序</param> /// <param name="isRemoveNull">是否移除空值,默认移除</param> /// <returns>string</returns> public static string ToUrl <T, S>(this IDictionary <T, S> @this, string seed = "", bool isAsciiSort = true, bool isRemoveNull = true) { //移除所有空值参数 if (isRemoveNull) { @this = @this.Where(o => o.Value?.ToString().IsNullOrEmpty() == false).ToDictionary(o => o.Key, o => o.Value); } //对参数键值对进行ASCII升序排序 if (isAsciiSort) { //C#默认的不是ASCII排序,正确的ASCII排序规则:数字、大写字母、小写字母的顺序 @this = @this.OrderBy(o => o.Key, new OrdinalComparer()).ToDictionary(o => o.Key, o => o.Value); } //拼接url return(@this.Aggregate(seed, _ => $"{_.Key}={_.Value?.ToString()}&", "&")); }
private static void SetDictionaryValues(IObjectWriter writer, string name, IDictionary <string, IEnumerable <string> > values) { if (values != null && values.Any()) { writer.WriteObjectStart(name); var sortedValues = values.OrderBy(pair => pair.Key, StringComparer.Ordinal); foreach (var pair in sortedValues) { writer.WriteNameArray(pair.Key, pair.Value); } writer.WriteObjectEnd(); } }
public override string ToString() { var sb = new StringBuilder(); sb.Append(Header); foreach (var problem in _problems.OrderBy(x => x.Key.Type).ThenBy(x => Problem.GetProblemNumber(x.Value.ProblemId))) { var comments = string.IsNullOrWhiteSpace(problem.Value.Comments) ? "" : WebUtility.HtmlEncode(problem.Value.Comments).Replace("\r\n", "<br />").Replace("\n", "<br />"); sb.AppendFormat(Body, problem.Value.ProblemId, problem.Key.Description, problem.Value.Points, problem.Key.TotalPoints > 0 ? problem.Key.TotalPoints.ToString() : "", comments); } sb.AppendFormat(Footer, Total, MaxPoints > 0 ? MaxPoints.ToString() : ""); return(sb.ToString()); }
public FixedSortedList(IDictionary <TKey, TValue> src) { var size = src.Count; _keys = new TKey[size]; Values = new TValue[size]; var offset = 0; foreach (var kvp in src.OrderBy(x => x.Key)) { _keys[offset] = kvp.Key; Values[offset++] = kvp.Value; } }
/// <summary> /// 生成签名 /// 签名在线验证工具: /// http://mch.weixin.qq.com/wiki/tools/signverify/ /// </summary> /// <param name="stringADict">参与签名生成的参数列表</param> /// <param name="partnerKey">商家私钥</param> /// <returns></returns> public static string Sign(IDictionary<string, string> stringADict, string partnerKey) { var sb = new StringBuilder(); foreach (var sA in stringADict.OrderBy(x => x.Key))//参数名ASCII码从小到大排序(字典序); { if (string.IsNullOrEmpty(sA.Value)) continue;//参数的值为空不参与签名; if (string.Compare(sA.Key, "sign", true) == 0) continue; // 参数中为签名的项,不参加计算 sb.Append(sA.Key).Append("=").Append(sA.Value).Append("&"); } var string1 = sb.ToString(); string1 = string1.Remove(string1.Length - 1, 1); sb.Append("key=").Append(partnerKey);//在stringA最后拼接上key=(API密钥的值)得到stringSignTemp字符串 var stringSignTemp = sb.ToString(); var sign = Util.MD5(stringSignTemp, "UTF-8").ToUpper();//对stringSignTemp进行MD5运算,再将得到的字符串所有字符转换为大写,得到sign值signValue。 return sign; }
/// <summary> /// Generates id of the aggregator serving time series specified in the parameters. /// </summary> /// <param name="name">Metric name.</param> /// <param name="dimensions">Optional metric dimensions.</param> /// <returns>Aggregator id that can be used to get aggregator.</returns> private static string GetAggregatorId(string name, IDictionary <string, string> dimensions = null) { StringBuilder aggregatorIdBuilder = new StringBuilder(name ?? "n/a"); if (dimensions != null) { var sortedDimensions = dimensions.OrderBy((pair) => { return(pair.Key); }); foreach (KeyValuePair <string, string> pair in sortedDimensions) { aggregatorIdBuilder.AppendFormat(CultureInfo.InvariantCulture, "\n{0}\t{1}", pair.Key ?? string.Empty, pair.Value ?? string.Empty); } } return(aggregatorIdBuilder.ToString()); }
ExitCode ShowHelp() { var help = new StringBuilder(); help.AppendLine(""); help.AppendLine("mulder, a simple static site generator written in C#"); help.AppendLine(""); help.AppendLine("usage: mulder [options] <command> [<args>]"); help.AppendLine(""); help.AppendLine("commands:"); help.AppendLine(""); foreach (var keyPair in commands.OrderBy(c => c.Key)) { help.AppendFormat(" {0} {1}{2}", keyPair.Key, keyPair.Value.Summary, Environment.NewLine); } help.AppendLine(""); help.AppendLine(" See 'mulder help <command>' for more information on a specific command."); help.AppendLine(""); help.AppendLine("options:"); help.AppendLine(""); foreach (Option option in options) { help.Append(" "); for (int i = 0; i < option.Names.Length; i++) { if (i != 0) { help.Append(" "); } help.Append(option.Names[i].Length == 1 ? "-" : "--"); help.Append(option.Names[i]); } help.AppendFormat(" {0}{1}", option.Description, Environment.NewLine); } log.InfoMessage(help.ToString()); return(ExitCode.Success); }
private string ConstructCanonicalQueryString(IDictionary <string, string> request) { if (request.Count == 0) { return(string.Empty); } var sb = new StringBuilder(); foreach (var kvp in request.OrderBy(o => o.Key, StringComparer.Ordinal)) { sb.Append(this.EscapeUriDataStringRfc3986(kvp.Key)); sb.Append("="); sb.Append(this.EscapeUriDataStringRfc3986(kvp.Value)); sb.Append("&"); } return(sb.ToString().TrimEnd('&')); }
/// <remarks> /// Article structure: /// root directory /// - ArticleKey/ArticleKey.json => meta /// - ArticleKey/ArticleKey.content => content /// - ArticleKey/AssetKeys => assets /// </remarks> private async Task LoadArticleMetaData() { var allBlogDirectories = Directory.GetDirectories(_config.BlogContentPath); if (allBlogDirectories.Length == 0) { return; } foreach (var articleDir in allBlogDirectories) { var blogFiles = Directory.GetFiles(articleDir); var fileKey = GenerateFileKey(articleDir); foreach (var jsonFile in blogFiles.Where(f => f.EndsWith(".json", StringComparison.Ordinal))) { // skip duplicates if (_cachedMeta.ContainsKey(fileKey)) { continue; } // skip articles that don't have correlated content file if (!blogFiles.Contains($"{_config.BlogContentPath}/{fileKey}/{fileKey}{ContentFileExtension}")) { continue; } try { var rawFileContents = await File.ReadAllTextAsync(jsonFile); var meta = JsonConvert.DeserializeObject <ArticleMeta>(rawFileContents); meta.FileKey = fileKey; _cachedMeta.Add(fileKey, meta); } catch (Exception e) { throw new Exception($"Error reading and deserializing blog article '{jsonFile}'", e); } } } _cachedMeta.OrderBy(m => m.Value.PublishDate); _loadingArticleMeta = false; }
public AllFeeEstimate(EstimateSmartFeeMode type, IDictionary <int, int> estimations) { Type = type; Guard.NotNullOrEmpty(nameof(estimations), estimations); Estimations = new Dictionary <int, int>(); var valueSet = new HashSet <decimal>(); // Make sure values are unique and in the correct order. foreach (KeyValuePair <int, int> estimation in estimations.OrderBy(x => x.Key)) { if (valueSet.Add(estimation.Value)) { Estimations.TryAdd(estimation.Key, estimation.Value); } } _hashCode = null; }
private static void RemoveOldBitmaps(IDictionary <object, BitmapInfo> tileCache, int numberToRemove) { var counter = 0; var orderedKeys = tileCache.OrderBy(kvp => kvp.Value.IterationUsed).Select(kvp => kvp.Key).ToList(); foreach (var key in orderedKeys) { if (counter >= numberToRemove) { break; } var textureInfo = tileCache[key]; tileCache.Remove(key); textureInfo.Bitmap.Dispose(); counter++; } }
public static void EmitRegisters(IProcessorArchitecture arch, string caption, Dictionary <RegisterStorage, uint> grfFlags, IDictionary <Storage, BitRange> regRanges, TextWriter sb) { sb.Write(caption); var sGrf = string.Join(" ", grfFlags .Where(f => f.Value != 0) .Select(f => arch.GetFlagGroup(f.Key, f.Value) !) .OrderBy(f => f.Name)); if (sGrf.Length > 0) { sb.Write(" {0}", sGrf); } foreach (var de in regRanges.OrderBy(de => de.Key.Name)) { sb.Write(" {0}:{1}", de.Key, de.Value); } }
/**** ** General log output ****/ /// <summary>Log the initial header with general SMAPI and system details.</summary> /// <param name="modsPath">The path from which mods will be loaded.</param> /// <param name="customSettings">The custom SMAPI settings.</param> public void LogIntro(string modsPath, IDictionary <string, object> customSettings) { // init logging this.Monitor.Log($"SMAPI {Constants.ApiVersion} with Stardew Valley {Constants.GameVersion} on {EnvironmentUtility.GetFriendlyPlatformName(Constants.Platform)}", LogLevel.Info); this.Monitor.Log($"Mods go here: {modsPath}", LogLevel.Info); if (modsPath != Constants.DefaultModsPath) { this.Monitor.Log("(Using custom --mods-path argument.)"); } this.Monitor.Log($"Log started at {DateTime.UtcNow:s} UTC"); // log custom settings if (customSettings.Any()) { this.Monitor.Log($"Loaded with custom settings: {string.Join(", ", customSettings.OrderBy(p => p.Key).Select(p => $"{p.Key}: {p.Value}"))}"); } }
public static IEnumerable <KeyValuePair <Problem, Comment> > GetDisplayedProblems(IDictionary <Problem, Comment> problems, bool showAllGrades) { var displayedProblems = problems .OrderBy(x => x.Value.Problem.IsNote()) .ThenBy(x => x.Value.Problem.IsMixed ? "" : x.Value.Problem.Type) .ThenBy(x => x.Value.Problem.Number) .Where( x => x.Value.Problem.Visible && ((!(x.Value.Problem.TotalPoints == 0m && x.Value.Points == 0m) && !(x.Value.Problem.IsMultiplier() && x.Value.Points == 0m) && (showAllGrades || x.Value.Points != x.Value.Problem.TotalPoints)) || !String.IsNullOrWhiteSpace(x.Value.Comments))); return(displayedProblems); }
private void Create(EstimateSmartFeeMode type, IDictionary <int, int> estimations, bool isAccurate) { Type = type; IsAccurate = isAccurate; Guard.NotNullOrEmpty(nameof(estimations), estimations); Estimations = new Dictionary <int, int>(); var valueSet = new HashSet <decimal>(); // Make sure values are unique and in the correct order. foreach (KeyValuePair <int, int> estimation in estimations.OrderBy(x => x.Key)) { if (valueSet.Add(estimation.Value)) { Estimations.TryAdd(estimation.Key, estimation.Value); } } }
public async Task <IEnumerable <ProductData> > GetByFacets(IDictionary <string, string> query) { var path = new List <string>(); foreach (var kvp in query.OrderBy(x => x.Key)) { path.Add(kvp.Key); path.Add(kvp.Value); } var targetUri = new Uri(baseUri, string.Join('/', path) + ".json"); var body = await client.GetStringAsync(targetUri.ToString()); var json = JObject.Parse(body); var products = json["products"].ToObject <List <ProductData> >(); return(products); }
private void ShowOutputWindow(IDictionary <string, IEnumerable <IEnumerable <string> > > outputdata) { Application.Current.Dispatcher.Invoke((Action) delegate { StringBuilder text = new StringBuilder(); statusWindow = new StatusWindow((_SelectedFiles != null) ? _SelectedFiles.Count : 0) { Owner = this, }; statusWindow.Start(() => { int line = 0; MaxStatusWindow(outputdata.Sum(x => x.Value.Count())); UpdateStatusWindow(line, string.Format("Start Generating Output")); foreach (var kvp in outputdata.OrderBy(x => x.Key)) { foreach (var row in kvp.Value) { text.AppendLine("\"" + kvp.Key.Replace(fisrtLineKeyConst, "Key") + "\";" + string.Join(";", row.Select(x => "\"" + x + "\""))); if ((line + 1) % 1000 == 0) { UpdateStatusWindow(line + 1, string.Format("Generating Output")); } line++; } } UpdateStatusWindow(line, string.Format("Loading Output")); }, () => { if (Dispatcher.CheckAccess()) { buttonGenerate.IsEnabled = true; InitOutputWindow(text.ToString()); } else { Dispatcher.BeginInvoke(new Action(() => { buttonGenerate.IsEnabled = true; InitOutputWindow(text.ToString()); })); } }); }); }
public static void Main(params string[] args) { if (args.Length != 0) { BMultiMap <string, string> options = new BMultiMap <string, string>(); IDictionary <string, Pair <string, string> > KnownOptions = LeMP.Compiler.KnownOptions; var argList = args.ToList(); UG.ProcessCommandLineArguments(argList, options, "", LeMP.Compiler.ShortOptions, LeMP.Compiler.TwoArgOptions); if (!options.ContainsKey("nologo")) { Console.WriteLine("LLLPG/LeMP macro compiler (alpha)"); } string _; if (options.TryGetValue("help", out _) || options.TryGetValue("?", out _)) { LeMP.Compiler.ShowHelp(KnownOptions.OrderBy(p => p.Key)); return; } Severity minSeverity = Severity.Note; #if DEBUG minSeverity = Severity.Debug; #endif var filter = new SeverityMessageFilter(MessageSink.Console, minSeverity); LeMP.Compiler c = LeMP.Compiler.ProcessArguments(argList, options, filter, typeof(LeMP.Prelude.Les.Macros)); LeMP.Compiler.WarnAboutUnknownOptions(options, MessageSink.Console, KnownOptions); if (c != null) { c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("LeMP.Prelude")); c.MacroProcessor.PreOpenedNamespaces.Add(GSymbol.Get("Loyc.LLParserGenerator")); c.AddMacros(Assembly.GetExecutingAssembly()); c.AddMacros(typeof(LeMP.Prelude.Macros).Assembly); using (LNode.PushPrinter(Ecs.EcsNodePrinter.PrintPlainCSharp)) c.Run(); } } else { Tests(); Ecs.Program.Main(args); // do EC# tests } }
/// <summary> /// Sorts a dictionary /// </summary> /// <typeparam name="T1">Key type</typeparam> /// <typeparam name="T2">Value type</typeparam> /// <typeparam name="T3">Order by type</typeparam> /// <param name="dictionary">Dictionary to sort</param> /// <param name="orderBy">Function used to order the dictionary</param> /// <param name="comparer">Comparer used to sort (defaults to GenericComparer)</param> /// <returns>The sorted dictionary</returns> public static IDictionary <T1, T2> Sort <T1, T2, T3>(this IDictionary <T1, T2> dictionary, Func <KeyValuePair <T1, T2>, T3> orderBy, IComparer <T3>?comparer = null) where T3 : IComparable { if (dictionary is null) { return(new Dictionary <T1, T2>()); } if (orderBy is null) { return(dictionary); } comparer ??= GenericComparer <T3> .Comparer; return(dictionary.OrderBy(orderBy, comparer).ToDictionary(x => x.Key, x => x.Value)); }
public static int DictionaryHashCode <TKey, TValue>(this IDictionary <TKey, TValue> dictionary, IEqualityComparer <TValue> comparer) { Guard.NotNull(comparer, nameof(comparer)); var hashCode = 17; foreach (var kvp in dictionary.OrderBy(x => x.Key)) { hashCode = hashCode * 23 + kvp.Key.GetHashCode(); if (kvp.Value != null) { hashCode = hashCode * 23 + comparer.GetHashCode(kvp.Value); } } return(hashCode); }
public JsonMappings( IDictionary <Type, Type> mappingsByType, IDictionary <PropertyInfo, Type> mappingsByProperty) { _mappingsByType = mappingsByType; _mappingsByProperty = mappingsByProperty; _mappings = mappingsByType.OrderBy(x => x.Key.FullName) .Select(item => new Tuple <MemberInfo, Type>(item.Key, item.Value)) .Concat(mappingsByProperty.OrderBy(DeclaringTypeAndPropertyName) .Select(item => new Tuple <MemberInfo, Type>(item.Key, item.Value))).ToList(); _hashCode = unchecked (_mappings.Aggregate( typeof(JsonMappings).GetHashCode(), (currentHashCode, item) => (currentHashCode * 397) ^ item.GetHashCode())); }
//NEW //first line: start with <<, after that the version, after that has the raw directory path //next lines: start with >, after that destination path //every line after that is an image file name, and results, seperated by ':'. a - means the image has not been processed //OLD, also supported //encoding: //first line: start with ::, after that has the raw directory path //start a dest with <, continue with dest path (on new line) //everything after dest path is of format name>res. name of image and dialog result (in decimal int form) private IEnumerable <string> encode(IComparer <KeyValuePair <string, DialogResult?[]> > sortImages = null) { yield return("<<2" + rawdir); foreach (var dest in _dests.OrderBy(a => a.Value.Item1).Select(a => a.Key)) { var rel = AbsolutePathToRelative(rawdir, dest); yield return(">" + rel); } var im = sortImages == null ? (IEnumerable <KeyValuePair <string, DialogResult?[]> >)_images : _images.OrderBy(sortImages); foreach (KeyValuePair <string, DialogResult?[]> image in im) { StringBuilder line = new StringBuilder(image.Key + ":", image.Key.Length + _dests.Count * 2); line.Append(image.Value.Select(a => a.HasValue ? ((int)a).ToString() : "-").StrConcat(":")); yield return(line.ToString()); } }
// TODO: Maybe a post message method if any place need. private void EnumerateAliveProcessors(Action <Action <T>, KeyValuePair <ListeningPriority, List <Action <T> > > > action) { foreach (var groupProcessors in processors.OrderBy(p => p.Key)) { // ToList to make a copy of processors in case of adding new processor foreach (var reference in groupProcessors.Value.ToList()) { try { action(reference, groupProcessors); } catch (Exception e) { Trace.TraceError(e.ToString()); } } } }
public JsonMappings( IDictionary<Type, Type> mappingsByType, IDictionary<PropertyInfo, Type> mappingsByProperty) { _mappingsByType = mappingsByType; _mappingsByProperty = mappingsByProperty; _mappings = mappingsByType.OrderBy(x => x.Key.FullName) .Select(item => new Tuple<MemberInfo, Type>(item.Key, item.Value)) .Concat(mappingsByProperty.OrderBy(DeclaringTypeAndPropertyName) .Select(item => new Tuple<MemberInfo, Type>(item.Key, item.Value))).ToList(); _hashCode = unchecked(_mappings.Aggregate( typeof(JsonMappings).GetHashCode(), (currentHashCode, item) => (currentHashCode * 397) ^ item.GetHashCode())); }
internal void Draw(GameState state) { using (var screenGraphics = System.Drawing.Graphics.FromImage(screenImage)) { screenGraphics.Clear(Color.Black); screenGraphics.DrawImage(tileImage, Point.Empty); foreach (var pair in gameObjectMap.OrderBy(pair => pair.Value.ZIndex)) { if (pair.Value.Visible) { GameObject obj = pair.Key; Point location = obj.ScreenPosition(GameArea); screenGraphics.DrawImage(pair.Value.Image, location); } } } GameArea.Render(screenImage); }
public string ShowAdoptedAnimals() { var sb = new StringBuilder(); foreach (var owner in addoptedAnimals.OrderBy(x => x.Key)) { sb.AppendLine($"--Owner: {owner.Key}"); sb.Append($" - Adopted animals: "); foreach (var animal in owner.Value) { sb.Append($"{animal.Name} "); } sb.AppendLine(); } return(sb.ToString().Trim()); }
public CurrentChain(BehaviorChain top, IDictionary<string, object> data) { _chains.Push(top); _originalChain = top; _routeData = data; _resourceHash = new Lazy<string>(() => { var dict = new Dictionary<string, string>{ {"Pattern", top.ToString()} }; data.OrderBy(x => x.Key).Each( pair => { dict.Add(pair.Key, pair.Value == null ? string.Empty : pair.Value.ToString()); }); return dict.Select(x => "{0}={1}".ToFormat(x.Key, x.Value)).Join(";").ToHash(); }); }
public EntityTagHeaderValue CreateETag(IDictionary<string, object> properties) { if (properties == null) { throw Error.ArgumentNull("properties"); } if (properties.Count == 0) { return null; } StringBuilder builder = new StringBuilder(); builder.Append('\"'); bool firstProperty = true; foreach (object propertyValue in properties.OrderBy(p => p.Key).Select(p => p.Value)) { if (firstProperty) { firstProperty = false; } else { builder.Append(Separator); } string str = propertyValue == null ? NullLiteralInETag : ConventionsHelpers.GetUriRepresentationForValue(propertyValue); // base64 encode byte[] bytes = Encoding.UTF8.GetBytes(str); string etagValueText = Convert.ToBase64String(bytes); builder.Append(etagValueText); } builder.Append('\"'); string tag = builder.ToString(); return new EntityTagHeaderValue(tag, isWeak: true); }
protected CacheKey(IDictionary<string, object> key, Type type, string operation, OperationReturnType returnType, bool sorted, HashAlgorithmName hashAlgorithm = HashAlgorithmName.Default) { var reflectedType = Reflector.GetReflectedType(type); var typeName = reflectedType.IsBusinessObject && reflectedType.InterfaceTypeName != null ? reflectedType.InterfaceTypeName : reflectedType.FullTypeName; _hashAlgorithm = hashAlgorithm == HashAlgorithmName.Default ? ObjectFactory.Configuration.DefaultHashAlgorithm : hashAlgorithm; if (_hashAlgorithm == HashAlgorithmName.Native || _hashAlgorithm == HashAlgorithmName.None) { var keyValue = (sorted ? key.Select(k => string.Format("{0}={1}", k.Key, Uri.EscapeDataString(Convert.ToString(k.Value)))) : key.OrderBy(k => k.Key).Select(k => string.Format("{0}={1}", k.Key, Uri.EscapeDataString(Convert.ToString(k.Value))))).ToDelimitedString("&"); if (!string.IsNullOrEmpty(operation)) { _value = string.Concat(typeName, "->", operation, "[", returnType, "]", "::", keyValue); } else { _value = string.Concat(typeName, "::", keyValue); } _data = _value.ToByteArray(); } else { Func<KeyValuePair<string, object>, IEnumerable<byte>> func = k => BitConverter.GetBytes(k.Key.GetHashCode()).Append((byte)'=').Concat(BitConverter.GetBytes(k.Value.GetHashCode())).Append((byte)'&'); var keyValue = (sorted ? key.Select(func) : key.OrderBy(k => k.Key).Select(func)).Flatten().ToArray(); if (!string.IsNullOrEmpty(operation)) { _data = new byte[4 + 4 + 1 + keyValue.Length]; Buffer.BlockCopy(BitConverter.GetBytes(typeName.GetHashCode()), 0, _data, 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(operation.GetHashCode()), 0, _data, 4, 4); Buffer.BlockCopy(new[] { (byte)returnType }, 0, _data, 8, 1); Buffer.BlockCopy(keyValue, 0, _data, 9, keyValue.Length); } else { _data = new byte[4 + keyValue.Length]; Buffer.BlockCopy(BitConverter.GetBytes(typeName.GetHashCode()), 0, _data, 0 , 4); Buffer.BlockCopy(keyValue, 0, _data, 4 , keyValue.Length); } } }
private IList<TransportOrderRoute> PrepareTransportOrderRoute(string orderNo, TransportMode transportMode, IDictionary<int, string> shipAddressDic) { IList<TransportOrderRoute> transportOrderRouteList = new List<TransportOrderRoute>(); TransportOrderRoute prevTransportOrderRoute = null; IList<Address> addressList = null; if (shipAddressDic != null && shipAddressDic.Count > 0) { StringBuilder selectHql = null; IList<object> parms = new List<object>(); foreach (var shipAddress in shipAddressDic) { if (selectHql == null) { selectHql = new StringBuilder("from Address where Code in (?"); } else { selectHql.Append(", ?"); } parms.Add(shipAddress.Value); } selectHql.Append(")"); addressList = genericMgr.FindAll<Address>(selectHql.ToString(), parms.ToArray()); } foreach (var shipAddress in shipAddressDic.OrderBy(s => s.Key)) { Address address = addressList.Where(a => a.Code == shipAddress.Value).SingleOrDefault(); if (address == null) { throw new BusinessException("站点{0}不存在。", shipAddress.Value); } TransportOrderRoute transportOrderRoute = new TransportOrderRoute(); transportOrderRoute.OrderNo = orderNo; transportOrderRoute.Sequence = shipAddress.Key; transportOrderRoute.ShipAddress = address.Code; transportOrderRoute.ShipAddressDescription = address.CodeAddressContent; transportOrderRoute.Distance = prevTransportOrderRoute != null ? CalculateShipDistance(prevTransportOrderRoute.ShipAddress, transportOrderRoute.ShipAddress, transportMode) : 0; transportOrderRouteList.Add(transportOrderRoute); prevTransportOrderRoute = transportOrderRoute; } return transportOrderRouteList; }
private async Task GatherInfo() { IList<CloudTable> tables = await _srcClient.ListTablesAsync(_token); _timestamps = await LoadTimestampsFromMetatable(tables); if (_token.IsCancellationRequested) return; Console.WriteLine("destination status"); foreach (var kv in _timestamps.OrderBy(x => x.Key.Name)) { Console.WriteLine("{0,-40}{1}", kv.Key.Name, kv.Value); } }
protected virtual string FormatPointTags(IDictionary<string, object> tags) { // NOTE: from InfluxDB documentation - "Tags should be sorted by key before being sent for best performance." return String.Join(",", tags.OrderBy(p => p.Key).Select(p => FormatPointTag(p.Key, p.Value))); }
public static string Normalize(IDictionary<string, string> parameters) { return String.Join("&", parameters.OrderBy(param => param.Key).Select(param => String.Format("{0}={1}", UrlEncode(param.Key), UrlEncode(param.Value))).ToArray()); }
private IOrderedEnumerable<KeyValuePair<RosterPosition, Queue<Player>>> Sort( IDictionary<RosterPosition, Queue<Player>> assignments) { return assignments.OrderBy(kv => kv.Value.Count - kv.Key.Count); }
/// <summary> /// Functions like string.Format, only with a dictionary of values /// /// From: http://stackoverflow.com/questions/1010123/named-string-format-is-it-possible-c /// </summary> /// <param name="str">String to form</param> /// <param name="dict">Dictionary to retrieve values from</param> /// <returns></returns> public static string FormatFromDictionary(this string str, IDictionary<string, string> dict) { int i = 0; var newstr = new StringBuilder(str); var keyToInt = new Dictionary<string, int>(); foreach (var tuple in dict) { newstr = newstr.Replace("{" + tuple.Key + "}", "{" + i.ToString() + "}"); keyToInt.Add(tuple.Key, i); i++; } return String.Format(newstr.ToString(), dict.OrderBy(x => keyToInt[x.Key]) .Select(x => x.Value).ToArray()); }
static void ErrorPage(IDictionary<string, object> env, Exception ex, Action<string> write) { // XXX test this more thoroughly on mono, it shouldn't throw NullRef, // but rather, branch gracefully if something comes up null try { var request = new Request(env); var path = request.PathBase + request.Path; var frames = StackFrames(ex); var first = frames.FirstOrDefault(); var location = ""; if (ex.TargetSite != null && ex.TargetSite.DeclaringType != null) { location = ex.TargetSite.DeclaringType.FullName + "." + ex.TargetSite.Name; } else if (first != null) { location = first.Function; } // adapted from Django <djangoproject.com> // Copyright (c) 2005, the Lawrence Journal-World // Used under the modified BSD license: // http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5 write(@" <!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/html4/loose.dtd""> <html lang=""en""> <head> <meta http-equiv=""content-type"" content=""text/html; charset=utf-8"" /> <meta name=""robots"" content=""NONE,NOARCHIVE"" /> <title>"); write(h(ex.GetType().Name)); write(@" at "); write(h(path)); write(@"</title> <style type=""text/css""> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; } h2 { margin-bottom:.8em; } h2 span { font-size:80%; color:#666; font-weight:normal; } h3 { margin:1em 0 .5em 0; } h4 { margin:0 0 .5em 0; font-weight: normal; } table { border:1px solid #ccc; border-collapse: collapse; background:white; } tbody td, tbody th { vertical-align:top; padding:2px 3px; } thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; } tbody th { text-align:right; color:#666; padding-right:.5em; } table.vars { margin:5px 0 2px 40px; } table.vars td, table.req td { font-family:monospace; } table td.code { width:100%;} table td.code div { overflow:hidden; } table.source th { color:#666; } table.source td { font-family:monospace; white-space:pre; border-bottom:1px solid #eee; } ul.traceback { list-style-type:none; } ul.traceback li.frame { margin-bottom:1em; } div.context { margin: 10px 0; } div.context ol { padding-left:30px; margin:0 10px; list-style-position: inside; } div.context ol li { font-family:monospace; white-space:pre; color:#666; cursor:pointer; } div.context ol.context-line li { color:black; background-color:#ccc; } div.context ol.context-line li span { float: right; } div.commands { margin-left: 40px; } div.commands a { color:black; text-decoration:none; } #summary { background: #ffc; } #summary h2 { font-weight: normal; color: #666; } #summary ul#quicklinks { list-style-type: none; margin-bottom: 2em; } #summary ul#quicklinks li { float: left; padding: 0 1em; } #summary ul#quicklinks>li+li { border-left: 1px #666 solid; } #explanation { background:#eee; } #template, #template-not-exist { background:#f6f6f6; } #template-not-exist ul { margin: 0 0 0 20px; } #traceback { background:#eee; } #requestinfo { background:#f6f6f6; padding-left:120px; } #summary table { border:none; background:transparent; } #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; } #requestinfo h3 { margin-bottom:-1em; } .error { background: #ffc; } .specific { color:#cc3300; font-weight:bold; } </style> <script type=""text/javascript""> //<!-- function getElementsByClassName(oElm, strTagName, strClassName){ // Written by Jonathan Snook, http://www.snook.ca/jon; // Add-ons by Robert Nyman, http://www.robertnyman.com var arrElements = (strTagName == ""*"" && document.all)? document.all : oElm.getElementsByTagName(strTagName); var arrReturnElements = new Array(); strClassName = strClassName.replace(/\-/g, ""\\-""); var oRegExp = new RegExp(""(^|\\s)"" + strClassName + ""(\\s|$$)""); var oElement; for(var i=0; i<arrElements.length; i++){ oElement = arrElements[i]; if(oRegExp.test(oElement.className)){ arrReturnElements.push(oElement); } } return (arrReturnElements) } function hideAll(elems) { for (var e = 0; e < elems.length; e++) { elems[e].style.display = 'none'; } } window.onload = function() { hideAll(getElementsByClassName(document, 'table', 'vars')); hideAll(getElementsByClassName(document, 'ol', 'pre-context')); hideAll(getElementsByClassName(document, 'ol', 'post-context')); } function toggle() { for (var i = 0; i < arguments.length; i++) { var e = document.getElementById(arguments[i]); if (e) { e.style.display = e.style.display == 'none' ? 'block' : 'none'; } } return false; } function varToggle(link, id) { toggle('v' + id); var s = link.getElementsByTagName('span')[0]; var uarr = String.fromCharCode(0x25b6); var darr = String.fromCharCode(0x25bc); s.innerHTML = s.innerHTML == uarr ? darr : uarr; return false; } //--> </script> </head> <body> <div id=""summary""> <h1>"); write(h(ex.GetType().Name)); write(@" at "); write(h(path)); write(@"</h1> <h2>"); write(h(ex.Message)); write(@"</h2> <table><tr> <th>.NET</th> <td> "); if (!string.IsNullOrEmpty(location) && !string.IsNullOrEmpty(first.File)) { write(@" <code>"); write(h(location)); write(@"</code>: in <code>"); write(h(first.File)); write(@"</code>, line "); write(h(first.Line)); write(@" "); } else if (!string.IsNullOrEmpty(location)) { write(@" <code>"); write(h(location)); write(@"</code> "); } else { write(@" unknown location "); } write(@" </td> </tr><tr> <th>Web</th> <td><code>"); write(h(request.Method)); write(@" "); write(h(request.Host + path)); write(@" </code></td> </tr></table> <h3>Jump to:</h3> <ul id=""quicklinks""> <li><a href=""#get-info"">GET</a></li> <li><a href=""#post-info"">POST</a></li> <li><a href=""#cookie-info"">Cookies</a></li> <li><a href=""#header-info"">Headers</a></li> <li><a href=""#env-info"">ENV</a></li> </ul> </div> <div id=""traceback""> <h2>Traceback <span>(innermost first)</span></h2> <ul class=""traceback""> "); foreach (var frameIndex in frames.Select((frame, index) => Tuple.Create(frame, index))) { var frame = frameIndex.Item1; var index = frameIndex.Item2; write(@" <li class=""frame""> <code>"); write(h(frame.File)); write(@"</code>: in <code>"); write(h(frame.Function)); write(@"</code> "); if (frame.ContextCode != null) { write(@" <div class=""context"" id=""c{%=h frame.object_id %}""> "); if (frame.PreContextCode != null) { write(@" <ol start="""); write(h(frame.PreContextLine + 1)); write(@""" class=""pre-context"" id=""pre"); write(h(index)); write(@"""> "); foreach (var line in frame.PreContextCode) { write(@" <li onclick=""toggle('pre"); write(h(index)); write(@"', 'post"); write(h(index)); write(@"')"">"); write(h(line)); write(@"</li> "); } write(@" </ol> "); } write(@" <ol start="""); write(h(frame.Line)); write(@""" class=""context-line""> <li onclick=""toggle('pre"); write(h(index)); write(@"', 'post"); write(h(index)); write(@"')"">"); write(h(frame.ContextCode)); write(@"<span>...</span></li></ol> "); if (frame.PostContextCode != null) { write(@" <ol start='"); write(h(frame.Line + 1)); write(@"' class=""post-context"" id=""post"); write(h(index)); write(@"""> "); foreach (var line in frame.PostContextCode) { write(@" <li onclick=""toggle('pre"); write(h(index)); write(@"', 'post"); write(h(index)); write(@"')"">"); write(h(line)); write(@"</li> "); } write(@" </ol> "); } write(@" </div> "); } write(@" </li> "); } write(@" </ul> </div> <div id=""requestinfo""> <h2>Request information</h2> <h3 id=""get-info"">GET</h3> "); if (request.Query.Any()) { write(@" <table class=""req""> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> "); foreach (var kv in request.Query.OrderBy(kv => kv.Key)) { write(@" <tr> <td>"); write(h(kv.Key)); write(@"</td> <td class=""code""><div>"); write(h(kv.Value)); write(@"</div></td> </tr> "); } write(@" </tbody> </table> "); } else { write(@" <p>No GET data.</p> "); } write(@" <h3 id=""post-info"">POST</h3> "); var form = request.ReadForm(); if (form.Any()) { write(@" <table class=""req""> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> "); foreach (var kv in form.OrderBy(kv => kv.Key)) { write(@" <tr> <td>"); write(h(kv.Key)); write(@"</td> <td class=""code""><div>"); write(h(kv.Value)); write(@"</div></td> </tr> "); } write(@" </tbody> </table> "); } else { write(@" <p>No POST data.</p> "); } write(@" <h3 id=""cookie-info"">COOKIES</h3> "); if (request.Cookies.Any()) { write(@" <table class=""req""> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> "); foreach (var kv in request.Cookies.OrderBy(kv => kv.Key)) { write(@" <tr> <td>"); write(h(kv.Key)); write(@"</td> <td class=""code""><div>"); write(h(kv.Value)); write(@"</div></td> </tr> "); } write(@" </tbody> </table> "); } else { write(@" <p>No cookie data.</p> "); } write(@" <h3 id=""cookie-info"">HEADERS</h3> "); if (request.Headers.Any()) { write(@" <table class=""req""> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> "); foreach (var kv in request.Headers.OrderBy(kv => kv.Key)) { write(@" <tr> <td nowrap=""nowrap"">"); write(h(kv.Key)); write(@"</td> <td class=""code""><div>"); foreach (var v in kv.Value) { write(h(v)); write(@"<br/>"); } write(@"</div></td> </tr> "); } write(@" </tbody> </table> "); } else { write(@" <p>No header data.</p> "); } write(@" <h3 id=""env-info"">OWIN ENV</h3> <table class=""req""> <thead> <tr> <th>Variable</th> <th>Value</th> </tr> </thead> <tbody> "); foreach (var kv in env.OrderBy(kv => kv.Key)) { write(@" <tr> <td>"); write(h(kv.Key)); write(@"</td> <td class=""code""><div>"); write(h(kv.Value)); write(@"</div></td> </tr> "); } write(@" </tbody> </table> </div> <div id=""explanation""> <p> You're seeing this error because you use <code>Gate.Helpers.ShowExceptions</code>. </p> </div> </body> </html> "); } catch { return; } }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { words2pos = new Dictionary<string, long>(); wordsOrder = new List<string>(); outputValues = new Dictionary<string, long>(); totalRows = 0; Invoke(new MethodInvoker( delegate { button1.Enabled = false; tabControl1.Enabled = false; } )); Tuple<string, string> arg = (Tuple<string, string>)e.Argument; OleDbConnection myOleDbConnection = null; OleDbCommand myOleDbCommand = null; OleDbDataReader myOleDbDataReader = null; StreamWriter outputFile = null; StreamWriter dictOutputFile = null; StreamWriter catOutputFile = null; try { string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;data source=" + arg.Item1; myOleDbConnection = new OleDbConnection(connectionString); myOleDbCommand = myOleDbConnection.CreateCommand(); // TOP 100 myOleDbCommand.CommandText = "SELECT TOP " + (int)numericUpDown3.Value + " Recept, Content, ReceptDescription,DishType FROM tblMain"; myOleDbConnection.Open(); myOleDbDataReader = myOleDbCommand.ExecuteReader(); int i = 0; while (myOleDbDataReader.Read()) { i++; prepareTrainingData((string)myOleDbDataReader["Content"], (string)myOleDbDataReader["DishType"], 1, null); if (i % 541 == 0) { report("First pass: "******"SELECT TOP " + (int)numericUpDown3.Value + " Recept, Content, ReceptDescription,DishType FROM tblMain"; myOleDbDataReader = myOleDbCommand.ExecuteReader(); outputFile = new StreamWriter(File.OpenWrite(arg.Item2)); outputFile.WriteLine(totalRows + " " + wordsOrder.Count + " " + outputValues.Count); i = 0; while (myOleDbDataReader.Read()) { i++; prepareTrainingData((string)myOleDbDataReader["Content"], (string)myOleDbDataReader["DishType"], 2, outputFile); if (i % 541 == 0) { report("Second pass: "******"Dict and cat dump"); dictOutputFile = new StreamWriter(File.OpenWrite(arg.Item2 + ".words.dict")); foreach (string word in wordsOrder) { dictOutputFile.WriteLine(word); } catOutputFile = new StreamWriter(File.OpenWrite(arg.Item2 + ".words.cat")); foreach (string val in outputValues.OrderBy(x => x.Value).Select(x => x.Key)) { catOutputFile.WriteLine(val); } report("Creating network"); NeuralNet net = new NeuralNet(); net.SetActivationFunctionHidden(ActivationFunction.SigmoidSymmetric); net.Callback += new NeuralNet.CallbackType(fannProgress); uint[] layers = textBox5.Text.Split(new char[] { ',' }).Select(x => UInt32.Parse(x.Trim())).ToArray(); net.CreateStandardArray(layers); TrainingData data = new TrainingData(); outputFile.Close(); report("Reading data"); data.ReadTrainFromFile(arg.Item2); report("Doing training"); net.TrainOnData(data, (uint)numericUpDown1.Value, 10, (float)numericUpDown2.Value); net.Save(arg.Item2 + ".ann"); report("Done training. Saved."); } finally { if (myOleDbDataReader != null) myOleDbDataReader.Close(); if (myOleDbCommand != null) myOleDbCommand.Cancel(); if (myOleDbConnection != null) myOleDbConnection.Close(); if (outputFile != null) outputFile.Close(); if (dictOutputFile != null) dictOutputFile.Close(); if (catOutputFile != null) catOutputFile.Close(); } }
/// <summary> /// Ends the test module. /// </summary> /// <param name="testModule">The test module.</param> /// <param name="result">The result.</param> /// <param name="exception">The exception.</param> /// <param name="statisticsByPriority">The statistics for the module, broken down by priority.</param> /// <param name="globalStatistics">The global statistics for the module.</param> public void EndTestModule(TestModuleData testModule, TestResult result, ExceptionDetails exception, IDictionary<int, RunStatistics> statisticsByPriority, RunStatistics globalStatistics) { TestModuleData currentTestModule = this.testItemStack.Pop() as TestModuleData; ExceptionUtilities.Assert(currentTestModule == testModule, "Invalid test module on stack."); this.WriteResult(result, exception); this.writer.WriteEndElement(); this.writer.WriteStartElement("Summary"); this.OutputCounts(globalStatistics); foreach (var kvp in statisticsByPriority.OrderBy(c => c.Key)) { this.writer.WriteStartElement("Property"); this.OutputCounts(kvp.Value); this.writer.WriteAttributeString("Name", "Pri"); this.writer.WriteAttributeString("Value", XmlConvert.ToString(kvp.Key)); this.writer.WriteEndElement(); } this.writer.WriteEndElement(); this.writer.Flush(); }
protected string GetChecksum( IDictionary<string, string> inputFields, string apiKey ) { string result = String.Join( " ", inputFields.OrderBy( c => c.Key ).Select( c => c.Value ).ToArray() ); return GetChecksum( result, apiKey ); }
internal static string OAuthCalculateSignature(string method, string url, IDictionary<string, string> parameters, string tokenSecret) { var key = Secrets.apiSecret + "&" + tokenSecret; var keyBytes = Encoding.UTF8.GetBytes(key); var sb = new StringBuilder(); foreach (var pair in parameters.OrderBy(p => p.Key)) { sb.Append(pair.Key); sb.Append("="); sb.Append(UtilityMethods.EscapeOAuthString(pair.Value)); sb.Append("&"); } sb.Remove(sb.Length - 1, 1); var baseString = method + "&" + UtilityMethods.EscapeOAuthString(url) + "&" + UtilityMethods.EscapeOAuthString(sb.ToString()); var hash = Sha1Hash(keyBytes, baseString); return hash; }
public void PlotExercisePoints(string exerciseName, IDictionary<DateTime, ISet> sets) { ExerciseChart.Series[2].Points.Clear(); ExerciseChart.Series[2].Name = exerciseName; foreach(var weightedSet in sets .OrderBy(x => x.Key) .Select(kv => kv.Value) .OfType<IWeightedSet>().Select(set => set)) { ExerciseChart.Series[2].Points.AddXY(weightedSet.Date, weightedSet.Weight); } }
public void PlotDataPoints(IDictionary<DateTime, IDataPoint> highActivityDataPoints, IDictionary<DateTime, IDataPoint> lowActivityDataPoints) { if(highActivityDataPoints == null || lowActivityDataPoints == null) return; // plot high activity heart rate data. ExerciseChart.Series[0].Points.Clear(); foreach(var point in highActivityDataPoints .OrderBy(x => x.Key) .Select(kv => kv.Value) .Smooth(GetChunkSize(ViewModel.HighActivityDataPoints.Count))) { ExerciseChart.Series[0].Points.AddXY(point.Date.ToOADate(), point.HeartRate); } // plot low activity heart rate data. ExerciseChart.Series[1].Points.Clear(); foreach(var point in lowActivityDataPoints .OrderBy(x => x.Key) .Select(kv => kv.Value) .Smooth(GetChunkSize(ViewModel.LowActivityDataPoints.Count))) { ExerciseChart.Series[1].Points.AddXY(point.Date.ToOADate(), point.HeartRate); } }
private static List<Team[]> GenerateUrns(IDictionary<Team, int> teamRanks, int numberOfUrns) { var urns = new List<Team[]>(); var sortedTeamRanks = teamRanks.OrderBy(team => team.Value); int numberOfTeams = GCD(teamRanks.Count, numberOfUrns); var usedTeams = new HashSet<Team>(); while (urns.Count < numberOfUrns) { var teams = new Team[numberOfTeams]; int index = 0; foreach (var team in sortedTeamRanks) { if (teams.Count(x => x != null) == numberOfTeams) { break; } if (!usedTeams.Contains(team.Key) && teams.Count(x => x != null) < numberOfTeams) { teams[index] = team.Key; index++; usedTeams.Add(team.Key); } } Random rnd = new Random(); Team[] shuffledTeams = teams.OrderBy(x => rnd.Next()).ToArray(); urns.Add(shuffledTeams); } return urns; }
private static string GetTypeKey(IDictionary<string, Type> fields) { return fields.OrderBy(x => x.Key, StringComparer.Ordinal).Aggregate(string.Empty, (current, field) => current + (field.Key + ";" + field.Value.Name + ";")); }