public void WriteFileStream_AsParallel_AutoBuffered_ExplicitDisposed() => Dictionary .AsParallel() .WithExecutionMode(ParallelExecutionMode.ForceParallelism) .WithMergeOptions(ParallelMergeOptions.AutoBuffered) .ForAll(async file => { var(stream, task) = WriteFileAsStream(file); await task; stream.Close(); });
private async void button5_Click(object sender, EventArgs e) { //remove from group var selected_indicies = listBox1.SelectedIndices.Cast <int>().ToArray(); if (is_filtered) { var tmp = sub_displayed_group_users.AsParallel().Select((x, index) => new { x, index }).Where(y => selected_indicies.Contains(y.index)).Select(z => z.x.Key); selected_indicies = displayed_group_users.AsParallel().Select((x, index) => new { x, index }) .Where(y => tmp.Contains(y.x.Key)).Select(z => z.index).ToArray(); } textBox1.Clear(); is_filtered = false; await Task.Run(() => { var selected_users = displayed_group_users.AsParallel().Select((x, index) => new { x, index }) .Where(y => selected_indicies.Contains(y.index)) .Select(z => z.x) .ToDictionary(k => k.Key, k => k.Value); foreach (var user in selected_users) { displayed_group_users.Remove(user.Key); displayed_unassociated_users.Add(user.Key, user.Value); } displayed_group_users = displayed_group_users.AsParallel().OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value); displayed_unassociated_users = displayed_unassociated_users.AsParallel().OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value); Invoke((MethodInvoker)(() => { listBox1.DataSource = displayed_group_users.Values.ToList(); listBox2.DataSource = displayed_unassociated_users.Values.ToList(); })); var indicies_containing_selected_users = displayed_unassociated_users.AsParallel().Select((y, index) => new { y, index }) .Where(z => selected_users.Keys.Contains(z.y.Key)) .Select(m => m.index); Invoke((MethodInvoker)(() => { listBox2.ClearSelected(); foreach (var index in indicies_containing_selected_users) { listBox2.SetSelected(index, true); } })); }); }
private void OddCombinationControls(HashSet <int> oddCombIds) { oddCombResultCounts = new Dictionary <string, Dictionary <int, int> >(); Dictionary <int, HashSet <string> > temp = oddCombinationIdResults.AsParallel().Where(x => oddCombIds.Contains(x.Key)).ToDictionary(x => x.Key, x => x.Value); object myLock = new object(); foreach (var oddCombItem in temp) { string oddCombVal = oddCombTest[oddCombItem.Key]; SortedSet <int> tempFullOddIds = oddCombFullOddIds[oddCombItem.Key]; HashSet <string> sadas = new HashSet <string>(fullOddTest.Where(x => tempFullOddIds.Contains(x.Key)).Select(x => x.Value)); if (tempFullOddIds.Count < analyseLimitMap["oddCombFullOddCount"].textValues["Max"] && tempFullOddIds.Count > analyseLimitMap["oddCombFullOddCount"].textValues["Min"]) { foreach (var result in oddCombItem.Value) { if (!oddCombResultCounts.ContainsKey(result)) { oddCombResultCounts.Add(result, new Dictionary <int, int>()); } foreach (var tempFullOddId in tempFullOddIds) { if (!oddCombResultCounts[result].ContainsKey(tempFullOddId)) { oddCombResultCounts[result].Add(tempFullOddId, fullOddMatchCount[tempFullOddId]); } } } } } }
private RuleBuilder InitEnvironment(Dictionary <String, EnvironmentDetails> environment) { RuleBuilder rb = new RuleBuilder(_iptables, "/var/x4b/bin/bpf/nfbpf_compile", _ruleSets); var mappings = environment.AsParallel().Select((e) => { if (e.Value.Language == "bash") { e.Value.Command = rb.ExecuteBash(e.Value.Command); } else if (e.Value.Language == "bpf") { e.Value.Command = rb.CompileBpf("RAW", e.Value.Command); } else if (e.Value.Language == "bpfl4") { e.Value.Command = rb.CompileBpf("RAW_TRANSPORT", e.Value.Command); } else if (e.Value.Language != "text") { throw new Exception("Invalid language: " + e.Value.Language); } return(e); }); foreach (var e in mappings) { rb.DefineMapping(e.Key, e.Value.Command, e.Value.Default); } return(rb); }
public override void Render() { base.Render(); if (!holdKey && WinApi.IsKeyDown(Keys.F10)) { holdKey = true; Settings.Enable.Value = !Settings.Enable.Value; } else if (holdKey && !WinApi.IsKeyDown(Keys.F10)) { holdKey = false; } if (Settings.Enable) { Vector2 playerPos = GameController.Player.GetComponent <Positioned>().GridPos; Vector2 position = StartDrawPointFunc(); const int BOTTOM_MARGIN = 2; bool shouldUpdate = false; if (Settings.BorderSettings.Enable) { Dictionary <EntityWrapper, AlertDrawStyle> tempCopy = new Dictionary <EntityWrapper, AlertDrawStyle>(currentAlerts); var keyValuePairs = tempCopy.AsParallel().Where(x => x.Key.IsValid).ToList(); foreach (var kv in keyValuePairs) { if (DrawBorder(kv.Key.Address) && !shouldUpdate) { shouldUpdate = true; } } } foreach (KeyValuePair <EntityWrapper, AlertDrawStyle> kv in currentAlerts.Where(x => x.Key.IsValid)) { string text = GetItemName(kv); if (text == null) { continue; } ItemsOnGroundLabelElement entityLabel; if (!currentLabels.TryGetValue(kv.Key.Address, out entityLabel)) { shouldUpdate = true; } else if (Settings.ShowText & (!Settings.HideOthers | entityLabel.CanPickUp)) { position = DrawText(playerPos, position, BOTTOM_MARGIN, kv, text); } } Size = new Size2F(0, position.Y); //bug absent width if (shouldUpdate) { currentLabels = GameController.Game.IngameState.IngameUi.ItemsOnGroundLabels.GroupBy(y => y.ItemOnGround.Address).ToDictionary(y => y.Key, y => y.First()); } } }
static void PopulatePrimeFactors() { primeMap = new Dictionary<int, SortedSet<int>>(); var primes = MathUtils.ESieve(3200); for (int i = 2; i < 10000000; i++) { primeMap.Add(i, new SortedSet<int>()); } primeMap.AsParallel().ForAll(x => { for (int j = 0; j < primes.Length; j++) { if (primes[j] * primes[j] > x.Key) break; if (x.Key % primes[j] == 0) { x.Value.Add(primes[j]); var i = x.Key/primes[j]; if(MathUtils.IsPrime(i)) { x.Value.Add(i); } } } }); }
/// <summary></summary> /// <param name="config"></param> internal static async Task ExtensionAsync(Config config) { if (config is null) { throw new ArgumentNullException(nameof(config)); } var name = $"{config.GetValue("name")}"; Delete(name); Resources.AsParallel().ForAll(async resource => { var res = GetResource(resource.Key); res = ChangeResource(config, res); await SaveResourceAsync($"{name}\\{resource.Value}", res).ConfigureAwait(false); }); Images.AsParallel().ForAll(image => { using var res = GetImage(image.Key); SaveImage($"{name}\\{image.Value}", res); }); _ = bool.TryParse($"{config.GetValue("delete_artifactory")}", out bool isDeleteArtifactory); await CreateAsync(name, isDeleteArtifactory).ConfigureAwait(false); }
private PartitionScore SplitOnAxis(CategoricalAxis axis, List <Episode> episodes, double[] totalWeights) { // Calculate categories Dictionary <Enum, HashSet <Episode> > episodesByCategory = episodes .AsParallel() .Select(episode => EvaluateCategories(axis, episode)) .SelectMany(x => x.Categories.Select(category => new { Category = category, Episode = x.Episode, })) .GroupBy(g => g.Category) .ToDictionary(g => g.Key, g => new HashSet <Episode>(g.Select(x => x.Episode))); List <PartitionScore> partitions = new List <PartitionScore>(); HashSet <Episode> leftEpisodes = new HashSet <Episode>(episodes); List <Episode> rightEpisodes = new List <Episode>(); HashSet <Enum> rightCategories = new HashSet <Enum>(); double[] rightWeights = new double[TacticEntropy.NumTactics]; while (leftEpisodes.Count > 0) { List <AdditionalCategory> additionalCategories = episodesByCategory .AsParallel() .Select(kvp => EvaluateAdditionalCategory(kvp.Key, kvp.Value, totalWeights, rightWeights)) .ToList(); AdditionalCategory bestAdditionalCategory = additionalCategories.MinByOrDefault(x => x.Entropy); if (bestAdditionalCategory == null) { // Everything left belongs to no categories - nothing to move break; } // Update left and right rightCategories.Add(bestAdditionalCategory.Category); leftEpisodes.ExceptWith(bestAdditionalCategory.AdditionalEpisodes); rightEpisodes.AddRange(bestAdditionalCategory.AdditionalEpisodes); rightWeights = bestAdditionalCategory.NewRightWeights; // Create snapshot of partition partitions.Add(new PartitionScore { Partitioner = new CategoricalPartitioner(axis, rightCategories.ToArray()), LeftEpisodes = leftEpisodes.ToList(), RightEpisodes = rightEpisodes.ToList(), Entropy = bestAdditionalCategory.Entropy, }); // Remove additional episodes from other categories so we don't re-add them episodesByCategory.Remove(bestAdditionalCategory.Category); foreach (HashSet <Episode> otherEpisodes in episodesByCategory.Values) { otherEpisodes.ExceptWith(bestAdditionalCategory.AdditionalEpisodes); } } return(partitions.MinByOrDefault(p => p.Entropy)); }
private RuleBuilder InitEnvironment(Dictionary<String, EnvironmentDetails> environment) { RuleBuilder rb = new RuleBuilder(_iptables, "/var/x4b/bin/bpf/nfbpf_compile", _ruleSets); var mappings = environment.AsParallel().Select((e) => { if (e.Value.Language == "bash") { e.Value.Command = rb.ExecuteBash(e.Value.Command); } else if (e.Value.Language == "bpf") { e.Value.Command = rb.CompileBpf("RAW", e.Value.Command); } else if (e.Value.Language == "bpfl4") { e.Value.Command = rb.CompileBpf("RAW_TRANSPORT", e.Value.Command); } else if (e.Value.Language != "text") { throw new Exception("Invalid language: " + e.Value.Language); } return e; }); foreach (var e in mappings) { rb.DefineMapping(e.Key, e.Value.Command, e.Value.Default); } return rb; }
public List <ItemData> GetItemDataListWithLevel(int fromLevel, int toLevel) { List <ItemData> retItemIdList = new List <ItemData>(); var itemList = itemLevelDic.AsParallel().Where(pair => { return(pair.Key >= fromLevel && pair.Key <= toLevel); }); foreach (var itemsListPair in itemList) { foreach (var itemId in itemsListPair.Value) { retItemIdList.Add(getItemDataById <ItemData>(itemId)); } } return(retItemIdList); }
public IEnumerable <Node> NodeContainment(Dictionary <Relation, Polygon[]> relationsDict, IEnumerable <Node> nodeStreamer) { // prebuild polygons to reduce contention foreach (var node in nodeStreamer) { var containingRelations = relationsDict.AsParallel().Where(kvp => { var target = kvp.Key; var polygons = kvp.Value; foreach (var polygon in polygons) { if (PolygonContainment.Contains(polygon, node)) { return(true); } foreach (var polyNodes in polygon.Nodes) { if (polyNodes.Id == node.Id) { return(true); } } } return(false); }).Select(x => x.Key.Id); node.Relations.AddRange(containingRelations); yield return(node); } }
private async Task OnMessageReceived(SocketMessage arg) { var message = arg as SocketUserMessage; if (message == null) { return; } CommandList.AsParallel().ForAll(async kv => { var pos = 0; var command = (message.HasStringPrefix(kv.Key, ref pos) || message.HasMentionPrefix(Discord.CurrentUser, ref pos)) ? Regex.Replace(message.Content.Substring(pos), @"\p{Zs}", " ") : string.Empty; if (command == string.Empty) { return; } var context = new CommandContext(Discord, message); var result = await kv.Value.ExecuteAsync(context, command, ServiceProvider); var type = result.IsSuccess ? "Success" : "Failure"; Logger.WriteLine($"DiscordBot: {type}: #{message.Channel.Name} [{message.Author.Username}#{message.Author.Discriminator}] `{command}` {result.ErrorReason}"); }); }
public Dictionary <Store, decimal> DoGetTotalsByWeekPerStores(Date date) { // ConcurrentDictionary<Date,Date > dates2 = new ConcurrentDictionary<Date,Date>(dates); ConcurrentDictionary <Store, decimal> resultP = new ConcurrentDictionary <Store, decimal>(); //foreach (var entry in dates) stores.AsParallel().ForAll(entry => { resultP.TryAdd(entry.Value, queryTotals(entry.Key, date.Year, date.Week, null, null)); }); Dictionary <Store, decimal> result = new Dictionary <Store, decimal>(resultP); return(result); }
static void Test() { Dictionary <string, Func <List <string> > > methods = new Dictionary <string, Func <List <string> > > { #if false { "CallSqlBrowser", GetLocalSqlServerInstancesByCallingSqlBrowser }, { "CallSqlWmi32", GetLocalSqlServerInstancesByCallingSqlWmi32 }, { "CallSqlWmi64", GetLocalSqlServerInstancesByCallingSqlWmi64 }, #endif { "ReadRegInstalledInstances", GetLocalSqlServerInstancesByReadingRegInstalledInstances }, { "ReadRegInstanceNames", GetLocalSqlServerInstancesByReadingRegInstanceNames }, { "CallSqlCmd", GetLocalSqlServerInstancesByCallingSqlCmd }, }; Dictionary <string, List <string> > dictionary = methods .AsParallel() .ToDictionary(v => v.Key, v => v.Value().OrderBy(n => n, StringComparer.OrdinalIgnoreCase).ToList()); foreach (KeyValuePair <string, List <string> > pair in dictionary) { Console.WriteLine(string.Format("~~{0}~~", pair.Key)); pair.Value.ForEach(v => Console.WriteLine(" " + v)); } Console.WriteLine("Press any key to continue."); Console.ReadKey(); }
public static void Main(string[] args) { Dictionary<Address, UInt64> balances = new Dictionary<Address, UInt64>(); UnspentTxOutList utxo = new UnspentTxOutList(); Hash lastBlockHash; using (FileStream fs = new FileStream(@"D:\utxo.dat", FileMode.Open)) { BinaryReader br = new BinaryReader(fs); lastBlockHash = br.ReadBytes(32); utxo = UnspentTxOutList.FromStream(fs); } foreach (KeyValuePair<TxOutId, TxOut> txo in utxo) { Address a = Address.FromScript(txo.Value.scriptPubKey); if (a == null) continue; if (!balances.ContainsKey(a)) balances.Add(a, 0); balances[a] += txo.Value.value; } foreach (KeyValuePair<Address, UInt64> bal in balances.AsParallel().OrderByDescending(x=>x.Value)) { Console.WriteLine(bal.Key + "\t" + bal.Value); } }
public static void Main(string[] args) { Dictionary <Address, UInt64> balances = new Dictionary <Address, UInt64>(); UnspentTxOutList utxo = new UnspentTxOutList(); Hash lastBlockHash; using (FileStream fs = new FileStream(@"D:\utxo.dat", FileMode.Open)) { BinaryReader br = new BinaryReader(fs); lastBlockHash = br.ReadBytes(32); utxo = UnspentTxOutList.FromStream(fs); } foreach (KeyValuePair <OutPoint, TxOut> txo in utxo) { Address a = Address.FromScript(txo.Value.scriptPubKey); if (a == null) { continue; } if (!balances.ContainsKey(a)) { balances.Add(a, 0); } balances[a] += txo.Value.value; } foreach (KeyValuePair <Address, UInt64> bal in balances.AsParallel().OrderByDescending(x => x.Value)) { Console.WriteLine(bal.Key + "\t" + bal.Value); } }
public Notification Reserve(Rect workArea) { byte slotIndex; lock (_lock) { var freeSlots = Slots.AsParallel().Where(slot => !slot.Value).OrderBy(slot => slot.Key).ToList(); slotIndex = freeSlots.Any() ? freeSlots.First().Key : (byte)Slots.Count; if (freeSlots.Any()) { Slots[slotIndex] = true; } else { Slots.Add(slotIndex, true); } } var offset = slotIndex * (_marginCache.Top + _sizeCache.Height + _marginCache.Bottom); var left = _horizontalPlacementCache == HorizontalPlacement.Left ? _marginCache.Left : workArea.Right - _sizeCache.Width - _marginCache.Right; var top = _verticalPlacementCache == VerticalPlacement.Top ? _marginCache.Top + offset : workArea.Bottom - _sizeCache.Height - _marginCache.Bottom - offset; var hiddenPosition = _horizontalPlacementCache == HorizontalPlacement.Left ? -_sizeCache.Width : workArea.Right; return(new Notification(slotIndex, _lifetimeCache, _animationCache, new Point(hiddenPosition, top), new Point(left, top), new Size(_sizeCache.Width, _sizeCache.Height))); }
/// <summary> /// Extend interval for request after initial block synchronization. /// </summary> public void UpdateRequestInterval() { _clientToParentChain?.UpdateRequestInterval(ConsensusConfig.Instance.DPoSMiningInterval); _clientsToSideChains.AsParallel().ForEach(kv => { kv.Value.UpdateRequestInterval(ConsensusConfig.Instance.DPoSMiningInterval); }); }
public async Task <List <string> > SearchFileAsync(string searchName, float range, int max, CancellationToken cancelToken) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Restart(); List <string> Result = new List <string>(max); if (searchName != string.Empty) { string searchNameLower = searchName.ToLower(); await Task.Run(() => { Algorithms.LevenshteinDistance levenshteinDistance = new LevenshteinDistance(); var Contains = _IndexDictionary .AsParallel() .WithCancellation(cancelToken) .Where(x => x.Key.Contains(searchNameLower)) .OrderBy(x => 1.0 - levenshteinDistance.CalculateNormalizedDistance(searchNameLower, x.Key)) .SelectMany(x => x.Value.ToArray()); Result.AddRange(Contains.Take(max)); if (Result.Count >= max) { return; } if (cancelToken.IsCancellationRequested) { return; } var NotContains = _IndexDictionary .AsParallel() .WithCancellation(cancelToken) .Where(x => !x.Key.Contains(searchNameLower) && (1.0 - levenshteinDistance.CalculateNormalizedDistance(searchName, x.Key)) <= range) .OrderBy(x => 1.0 - levenshteinDistance.CalculateNormalizedDistance(searchNameLower, x.Key)) .SelectMany(x => x.Value.ToArray()); int RemainCapacity = max - Result.Count; Result.AddRange(NotContains.Take(RemainCapacity)); if (cancelToken.IsCancellationRequested) { return; } }); } stopwatch.Stop(); LogStatics.Debug(string.Format("search at {0:F3} s", (float)stopwatch.Elapsed.TotalSeconds)); return(Result); }
/// <summary> /// Searches for duplicates or similar images and groups them into a DuplicateImage-Instance. /// </summary> /// <param name="path">The directory to search through.</param> protected override IEnumerable<DuplicateImages> FindDuplicates(Dictionary<FileInfo, ulong> images) { //Find identical images //todo: AsParallel() safe to use here? var __groups = images.AsParallel().GroupBy(i => i.Value).Where(grp => grp.Count() > 1).ToList(); return __groups.Select(group => new DuplicateImages(group.Select(e => new DuplicateImage(e.Key, e.Value)))); }
public static void CreateXmlUP_x32to64(string ksppath, string vel, Label label) { Dictionary <int, string> vel_en_x64 = LoadDict(vel + @"\en_x64.xml"); Dictionary <int, string> vel_en = LoadDict(vel + @"\en.xml"); Dictionary <int, string> vel_zh = LoadDict(vel + @"\zh_up.xml"); StringBuilder en_up = new StringBuilder(); StringBuilder zh_up = new StringBuilder(); string temp = @"<string id=""{0}""><![CDATA[{1}]]></string>"; en_up.AppendLine("<en>"); zh_up.AppendLine("<zh>"); StringBuilder en_lose = new StringBuilder(); StringBuilder zh_lose = new StringBuilder(); en_lose.AppendLine("<en>"); zh_lose.AppendLine("<zh>"); int i = 0; int count = vel_zh.Count; foreach (var item in vel_zh) { i++; label.Text = i.ToString() + "/" + count.ToString(); Application.DoEvents(); var en = vel_en.AsParallel().First(x => x.Key == item.Key); var en_x64s = vel_en_x64.AsParallel().Where(x => x.Value == en.Value); if (en_x64s.Count() == 1) {//找到条目 var en_x64 = en_x64s.First(); en_up.AppendLine(string.Format(temp, en_x64.Key, en_x64.Value)); zh_up.AppendLine(string.Format(temp, en_x64.Key, item.Value)); } else {//找不到条目 en_lose.AppendLine(string.Format(temp, item.Key, en.Value)); zh_lose.AppendLine(string.Format(temp, item.Key, item.Value)); } } en_up.AppendLine("</en>"); zh_up.AppendLine("</zh>"); en_lose.AppendLine("</en>"); zh_lose.AppendLine("</zh>"); File.WriteAllText(Application.StartupPath + "\\" + vel + @"\en_up_x64.xml", en_up.ToString()); File.WriteAllText(Application.StartupPath + "\\" + vel + @"\zh_up_x64.xml", zh_up.ToString()); File.WriteAllText(Application.StartupPath + "\\" + vel + @"\en_lose_x64.xml", en_lose.ToString()); File.WriteAllText(Application.StartupPath + "\\" + vel + @"\zh_lose_x64.xml", zh_lose.ToString()); }
/// <summary> /// Spills the In-Memory store to the disk if needed. /// The spill condition is dependant on the combine store's content volume and maximum intermediate pairs to spill. /// </summary> /// <param name="final_spill">is this the final spill? means data must be spilled even if there is a little data</param> /// <param name="thread_num">number of threads to use for soritng. The default is to use all cores.</param> /// <returns>a string containing the name of resulted file.</returns> public string doSpillIfNeeded(bool final_spill = false, int thread_num = -1) { if (combinedDictionary.Count > 0 && (intermediatePairCount + combinedDictionary.Count > maxIntermediatePairsToSpill || final_spill)) { Stopwatch watch = new Stopwatch(); watch.Restart(); KeyValuePair <InterKey, List <InterValue> >[] sorted_pairs; if (thread_num <= 0) { sorted_pairs = combinedDictionary.AsParallel().OrderBy(t => t.Key).ToArray(); } else { sorted_pairs = combinedDictionary.AsParallel().WithDegreeOfParallelism(thread_num).OrderBy(t => t.Key).ToArray(); } combinedDictionary.Clear(); intermediatePairCount = 0; mapperInfo.SpilledRecords += sorted_pairs.Count(); watch.Stop(); logger.Debug("Sorted {0} records in {1}.", StringFormatter.DigitGrouped(sorted_pairs.Count()), watch.Elapsed); IntermediateFile <InterKey, InterValue> inter_file = new IntermediateFile <InterKey, InterValue>(tempDirectory, mapperID); long written_bytes = 0; written_bytes = inter_file.WriteRecords(sorted_pairs); mapperInfo.SpilledBytes += written_bytes; inter_file.Close(); if (!final_spill && written_bytes > 0) { if (written_bytes < maxIntermediateFileSize) { maxIntermediatePairsToSpill = (int)(maxIntermediatePairsToSpill * (double)(maxIntermediateFileSize) / written_bytes); logger.Debug("maxIntermediatePairsToSpill was set to {0} records.", StringFormatter.DigitGrouped(maxIntermediatePairsToSpill)); } if (written_bytes > 1.5 * maxIntermediateFileSize) { maxIntermediatePairsToSpill /= 2; logger.Debug("maxIntermediatePairsToSpill was set to {0} records.", StringFormatter.DigitGrouped(maxIntermediatePairsToSpill)); } } return(inter_file.Path); } return(null); }
private static DataObject[] GetObjects( long startId, Dictionary <long, string> result) { return(result .AsParallel() .Select(observation => GetNewObject(startId, observation)) .ToArray()); }
/// <summary> /// Проверка точки на "занятость" другим обьектом /// </summary> /// <param name="imagePoints"></param> /// <returns></returns> private bool HasAvailableSpace(List <Point> imagePoints) { if (freeSqreenSpace.AsParallel().Join(imagePoints.AsParallel(), x => x.Key, y => y, (x, y) => x.Value).Contains(false)) { return(false); } return(true); }
public static string Serialize(Dictionary<string, string> data) { var xdoc = new XDocument(new XElement("data")); data.AsParallel().ForAll(a => { xdoc.Root.Add(new XAttribute(a.Key, a.Value)); }); return xdoc.ToString(); }
private void ReadMetadataObjects() { Configuration configurationPart = (Configuration)PackagePart; Dictionary <Type, Collection> parts = new Dictionary <Type, Collection>(); //Common parts.Add(typeof(Role), configurationPart.Roles); parts.Add(typeof(CommonTemplate), configurationPart.CommonTemplates); parts.Add(typeof(CommonModule), configurationPart.CommonModules); parts.Add(typeof(ScheduledJob), configurationPart.ScheduledJobs); parts.Add(typeof(SharedAttribute), configurationPart.SharedAttributes); parts.Add(typeof(SessionParameter), configurationPart.SessionParameters); parts.Add(typeof(FunctionalOptionsParameter), configurationPart.FunctionalOptionsParameters); parts.Add(typeof(Subsystem), configurationPart.Subsystems); parts.Add(typeof(Interface), configurationPart.Interfaces); parts.Add(typeof(Style), configurationPart.Styles); parts.Add(typeof(Filter), configurationPart.Filters); parts.Add(typeof(SettingStorage), configurationPart.SettingStorages); parts.Add(typeof(EventSubscription), configurationPart.EventSubscriptions); parts.Add(typeof(StyleElement), configurationPart.StyleElements); parts.Add(typeof(CommonPicture), configurationPart.CommonPictures); parts.Add(typeof(ExchangePlan), configurationPart.ExchangePlans); parts.Add(typeof(WebService), configurationPart.WebServices); parts.Add(typeof(Language), configurationPart.Languages); parts.Add(typeof(FunctionalOption), configurationPart.FunctionalOptions); parts.Add(typeof(XdtoPackage), configurationPart.XdtoPackages); parts.Add(typeof(WsReference), configurationPart.WsReferences); //End Common parts.Add(typeof(Constant), configurationPart.Constants); parts.Add(typeof(Document), configurationPart.Documents); parts.Add(typeof(CommonForm), configurationPart.CommonForms); parts.Add(typeof(InformationRegister), configurationPart.InformationRegisters); parts.Add(typeof(CommandGroup), configurationPart.CommandGroups); parts.Add(typeof(CommonCommand), configurationPart.CommonCommands); parts.Add(typeof(DocumentNumerator), configurationPart.DocumentNumerators); parts.Add(typeof(DocumentJournal), configurationPart.DocumentJournals); parts.Add(typeof(Report), configurationPart.Reports); parts.Add(typeof(ChartOfCharacteristicTypes), configurationPart.ChartsOfCharacteristicTypes); parts.Add(typeof(AccumulationRegister), configurationPart.AccumulationRegisters); parts.Add(typeof(Sequence), configurationPart.Sequences); parts.Add(typeof(DataProcessor), configurationPart.DataProcessors); parts.Add(typeof(Catalog), configurationPart.Catalogs); parts.Add(typeof(Enum), configurationPart.Enums); parts.Add(typeof(ChartOfAccounts), configurationPart.ChartsOfAccounts); parts.Add(typeof(AccountingRegister), configurationPart.AccountingRegisters); parts.AsParallel().ForAll(i => ReadMetadataObjects(i.Key, i.Value)); //Add unknown objects AddUnknownObjects(); }
protected override void Solve(out string answer) { NumberDivisor numberDivisor = new NumberDivisor(); long n = 220; long f = numberDivisor.CalculateSumOfProperDivisors(n); Answer = f.ToString(); Dictionary <long, long> mapOfNumbersToDivisors = new Dictionary <long, long>(); // Identify the list of all d() functions under 10000. foreach (int number in Enumerable.Range(1, 10000)) { long dFunction = numberDivisor.CalculateSumOfProperDivisors(number); mapOfNumbersToDivisors.Add(number, dFunction); } //mapOfNumbersToDivisors.Add(220, d(220)); //mapOfNumbersToDivisors.Add(284, d(284)); List <long> amicableNumbers = new List <long>(); // Find the amicable numbers mapOfNumbersToDivisors.AsParallel().ForAll(mapEntry => { long key = mapEntry.Key; if (amicableNumbers.Contains(key)) { return; // Make sure we do not count the same amicable number twice. } long value = mapEntry.Value; try { long reverseKey = mapOfNumbersToDivisors[value]; if (key == reverseKey) //Key and value are the two amicable numbers. Add them to the list to remember. { if (key != value) //amicability requires that d(a) = b and d(b) = a, where a != b { amicableNumbers.Add(key); amicableNumbers.Add(value); } } } catch (KeyNotFoundException e) { //There is no reverse value in the collection, so no chance of amicability. string m = e.Message; } }); var sumOfAmicableNumbers = amicableNumbers.Sum(); answer = string.Format("The sum of all the amicable numbers under 10000 is {0}.", sumOfAmicableNumbers); }
HashSet <int> GetOddCombIds() { Dictionary <HashSet <string>, int> rangedOddCombs = oddCombHashIds .AsParallel() .Where(x => x.Key > analyseLimitMap["oddCombMatchCount"].textValues["Min"] && x.Key < analyseLimitMap["oddCombMatchCount"].textValues["Max"]).SelectMany(x => x.Value) .ToDictionary(x => x.Key, y => y.Value); HashSet <int> oddCombIds = new HashSet <int>(); if (fullOddValueOddCombIds.ContainsKey(currentAnalysedMatch.FullOdd)) { oddCombIds = new HashSet <int>(rangedOddCombs.AsParallel().Where(x => fullOddValueOddCombIds[currentAnalysedMatch.FullOdd].Contains(x.Value)).Select(x => x.Value)); } else { HashSet <string> hashCurrentFullOdd = new HashSet <string>(currentAnalysedMatch.FullOdd.Split('|')); oddCombIds = new HashSet <int>(rangedOddCombs.AsParallel().Where(x => x.Key.IsSubsetOf(hashCurrentFullOdd)).Select(x => x.Value)); } return(oddCombIds); }
public IEnumerable <Shabd> TopWords(int top) { return(from word in occuranceOfAWord.AsParallel().OrderByDescending(kp => kp.Value) .Select(kp => kp.Key) .ToList().Take(top) select new Shabd { Word = word, Occurance = occuranceOfAWord[word], Definition = _textOperation.GetDefinition(word) }); }
private void UpdateFakeRates() { foreach (var fake in fakeDataProviders.AsParallel()) { var randValue = rand.NextDouble(); decimal onNextValue = randValue > 0.5 ? fakeDataProviderBaseValues[fake.Key] * 1.01m : fakeDataProviderBaseValues[fake.Key] * 0.99m; fake.Value.OnNext(onNextValue); } }
public void initDisplays() { Console.WriteLine("init displays...."); // if (!hardwareEnabled) return; StoreProvider = new JsonStoreProvider(_configuration); StoreProvider.SetStoreName("segDisplays"); List <SevenSegmentDevice> p = StoreProvider.LoadStore <SevenSegmentDevice>(); segDisplays.Add("red1", new SevenSegmentDevice() { DeviceAddress = 0x72 }); segDisplays.Add("green1", new SevenSegmentDevice() { DeviceAddress = 0x70 }); segDisplays.Add("red2", new SevenSegmentDevice() { DeviceAddress = 0x73 }); segDisplays.Add("green2", new SevenSegmentDevice() { DeviceAddress = 0x71 }); // segDisplays.Add("rogue1", new SevenSegmentDevice() { DeviceAddress = 0x74 }); segDisplays.AsParallel().ForAll(disp => { disp.Value.SetupDisplay(); }); foreach (SevenSegmentDevice dev in segDisplays.Values) { //teehee Console.WriteLine("writing stupid things on: " + dev.DeviceAddress); dev.WriteString("bEEr", false); } //CurrentCountDownParams // connection.InvokeAsync<Dictionary<string, double>>("TempReadings", readings); //CountDown c = await connection.InvokeAsync("CurrentCountDownParams"); //connection.InvokeAsync }
public void Explode(DirectoryInfo source, Dictionary <string, List <Drawing> > drawings) { if (drawings == null || drawings.Count == 0) { logger.Logging("Список чертежей для деления не может быть пустым или иметь значение Null"); return; } string name = "Папка деления"; DirectoryInfo folder = new DirectoryInfo(Path.Combine(source.FullName, name)); while (folder.Exists) { string path = Path.Combine(source.FullName, name.GetRandomPrefix()); folder = new DirectoryInfo(path); } if (!folder.Exists) { folder.Create(); } // Сортировка по формату Dictionary <string, List <Drawing> > groups = new Dictionary <string, List <Drawing> >(); drawings.AsParallel().ForAll(pair => { foreach (Drawing drawing in pair.Value) { if (groups.ContainsKey(drawing.Format)) { groups[drawing.Format].Add(drawing); } else { groups.Add(drawing.Format, new List <Drawing> { drawing }); } } }); groups.AsParallel().ForAll(pair => { string subfolder = Path.Combine(folder.FullName, pair.Key); folder.CreateSubdirectory(pair.Key); pair.Value.ForEach(d => CopyDrawing(subfolder, d)); logger.Logging($"Формат чертежей [ {pair.Key} ] успешно копирован в директорию [ {subfolder} ]"); }); }
//read file with json //public void RetrieveCurrent() //{ // var data = new StreamReader("Repo.txt", Encoding.UTF8).ReadLine(); // var list = JsonConvert.DeserializeObject<List<RateModel>>(data); // repo.AddRates(list); //} private static List <RateModel> ResponseToModel(Dictionary <string, Positions> data, DateTime date) { return(data.AsParallel().Select(pair => new RateModel { CurrencyName = pair.Key, BuyRate = (pair.Value.interbankRateValues ?? pair.Value.nbuRateValues).Buy, SellRate = (pair.Value.interbankRateValues ?? pair.Value.nbuRateValues).Sell, SellTrend = null, BuyTrend = null, TradeDate = date }) .ToList()); }
public IEnumerable <TfidfResult> GetResult() { if (idfDic == null) { CreateIDFdic(); } var all = docDic.SelectMany(n => n.Value.WordDic.Values).Sum(n => n.Count); return(docDic.AsParallel().SelectMany(n => n.Value.WordDic.Values).GroupBy(n => n.Word).Select(n => new TfidfResult() { Word = n.Key, TF = n.Sum(m => m.Count) / (double)all, IDF = idfDic.GetValueOrDefault(n.Key).Value }).OrderByDescending(n => n.TFIDF)); }
/// <summary> /// 请求数据 /// </summary> /// <param name="BaseUrl">请求根地址</param> /// <param name="Params">请求参数</param> /// <param name="Cookie">设置的Cookie</param> /// <param name="Header">设置的Header</param> /// <param name="Method">请求方式</param> /// <param name="ContentType">设置请求的ContentType</param> /// <param name="TimeOut">设置超时时间,默认10分钟</param> /// <param name="Encoding">设置请求编码</param> /// <param name="Accept">设置请求Accept</param> /// <param name="AllowReadStreamBuffering">设置是否缓存结果</param> /// <param name="Proxy">设置请求代理</param> /// <returns></returns> public async Task<HttpWebResponse> HttpRequestUrl(string BaseUrl, Dictionary<string, string> Params, Dictionary<string, string> Cookie = null, Dictionary<string, string> Header = null, string Method = "", string ContentType = "", int TimeOut = 60000, Encoding Encoding = null, string Accept = "", bool AllowReadStreamBuffering = false, IWebProxy Proxy = null) { try { Lazy<List<string>> paramsList = new Lazy<List<string>>(); BaseUrl = BaseUrl.ToUpperInvariant().Contains("HTTP|HTTPS") ? BaseUrl : "http://" + BaseUrl; string param = string.Empty; if (Params != null && Params.Count > 0) { Params.AsParallel().ForAll(p => paramsList.Value.Add("" + p.Key + "=" + p.Value)); param = string.Join("&", paramsList.Value); } if (Method != "POST") { BaseUrl += "?" + param; } HttpWebRequest request = WebRequest.CreateHttp(BaseUrl); request.Method = Method; request.ContentType = ContentType; request.ContinueTimeout = TimeOut; request.Accept = Accept; request.AllowReadStreamBuffering = AllowReadStreamBuffering; if (Cookie != null && Cookie.Count > 0) { Cookie.AsParallel().ForAll(p => request.CookieContainer.Add(new Uri(BaseUrl), new System.Net.Cookie(p.Key, p.Value))); } request.Proxy = Proxy; if (Header != null && Header.Count > 0) { Header.AsParallel().ForAll(p => request.Headers[p.Key] = p.Value); } if (request.Method.ToUpperInvariant() == "POST") { byte[] requestBytes = Encoding == null ? System.Text.Encoding.ASCII.GetBytes(param) : Encoding.GetBytes(param); Stream requestStream = await request.GetRequestStreamAsync(); requestStream.Write(requestBytes, 0, requestBytes.Length); requestStream.Dispose(); } HttpWebResponse respose = (HttpWebResponse)await request.GetResponseAsync(); return respose; } catch (Exception) { return null; } }
private void ProcessingCompactByYear() { this.Invoke((MethodInvoker)delegate { this.Cursor = Cursors.WaitCursor; }); var sw = Stopwatch.StartNew(); DirectoryInfo dInfo = new DirectoryInfo(Path.GetFullPath(txtFolder.Text)); fileArticles = dInfo.GetFiles(txtArticlesPrefix.Text + "*", SearchOption.TopDirectoryOnly).ToList(); fileInproceedings = dInfo.GetFiles(txtInproceedingsPrefix.Text + "*", SearchOption.TopDirectoryOnly).ToList(); fileProceedings = dInfo.GetFiles(txtProceedingsPrefix.Text + "*", SearchOption.TopDirectoryOnly).ToList(); filePhdthesis = dInfo.GetFiles(txtPhdThesisPrefix.Text + "*", SearchOption.TopDirectoryOnly).ToList(); fileAuthors = dInfo.GetFiles(txtAuthorPrefix.Text + "*", SearchOption.TopDirectoryOnly).ToList(); fileConferences = dInfo.GetFiles(txtConferencePrefix.Text + "*", SearchOption.TopDirectoryOnly).ToList(); GC.Collect(); GC.WaitForPendingFinalizers(); ParseCompactAuthors(); ParseCompactInproceedings(Convert.ToInt32(txtYearTo.Text)); ParseConferences(); Dictionary<int, compactInproceedingsDBLP> inproCals = diccompactInproceedings.Where( x => x.Value.Year <= Convert.ToInt32(txtYearTo.Text)).ToDictionary(x => x.Key, x => x.Value); diccompactInproceedings.Clear(); Dictionary<int, compactAuthorDBLP> authorCals = new Dictionary<int, compactAuthorDBLP>(); Dictionary<string, ConferenceDBLP> confCals = new Dictionary<string, ConferenceDBLP>(); Parallel.ForEach(inproCals, inproceeding => { Parallel.ForEach(inproceeding.Value.Authors, ai => { compactAuthorDBLP authorDblp = diccompactAuthors[ai]; lock (lock_acal) { if (!authorCals.Keys.Contains(ai)) { authorCals.Add(ai, diccompactAuthors[ai]); authorCals[ai].Count = 1; authorCals[ai].Papers.Clear(); authorCals[ai].Papers.Add(inproceeding.Key); authorCals[ai].CurrentValue = 1000; authorCals[ai].OldValue = 1000; } else { authorCals[ai].Count++; authorCals[ai].Papers.Add(inproceeding.Key); } } }); lock (lock_ccal) { if (!confCals.Keys.Contains(inproceeding.Value.Conference)) { confCals.Add(inproceeding.Value.Conference, dicStringConferences[inproceeding.Value.Conference]); confCals[inproceeding.Value.Conference].CountInproceedings = 1; confCals[inproceeding.Value.Conference].InproceedingsID = inproceeding.Value.Key.ToString(); } else { confCals[inproceeding.Value.Conference].CountInproceedings++; confCals[inproceeding.Value.Conference].InproceedingsID += "|" + inproceeding.Value.Key.ToString(); } } }); dicAuthors.Clear(); dicStringConferences.Clear(); dicConferences.Clear(); this.Invoke((MethodInvoker)delegate { txtMsgLog.Text = "Begin..."; Cursor = Cursors.WaitCursor; }); double sumAs1 = 0, sumIs1 = 0, sumCs = 0, sumIs2 = 0, sumAs2 = 0, min, ratio, max, max_old = 0, sum0; max = 1000; ratio = 1; sum0 = authorCals.AsParallel().Sum(x => x.Value.CurrentValue); while (max > Convert.ToDouble(txtMinDelta.Text)) { sw.Start(); sumAs1 = authorCals.AsParallel().Sum(x => x.Value.CurrentValue); inproCals.AsParallel().ForAll(x => x.Value.SetValueFromAuthors(authorCals)); sumIs1 = inproCals.AsParallel().Sum(x => x.Value.CurrentValue); confCals.AsParallel().ForAll(x => x.Value.SetValueFromInproceedings(inproCals)); sumCs = confCals.AsParallel().Sum(x => x.Value.CurrentValue); inproCals.AsParallel().ForAll(x => x.Value.SetValueFromConferences(confCals)); sumIs2 = inproCals.AsParallel().Sum(x => x.Value.CurrentValue); authorCals.AsParallel().ForAll(x => x.Value.SetValueFromInproceedings(inproCals)); sumAs2 = authorCals.AsParallel().Sum(x => x.Value.CurrentValue); ratio = sum0 / sumAs2; min = authorCals.AsParallel().Min(x => Math.Abs(x.Value.CurrentValue - x.Value.OldValue)); max = authorCals.AsParallel().Max(x => Math.Abs(x.Value.CurrentValue - x.Value.OldValue)); if (Math.Abs(ratio - 1) > 0.009) { authorCals.AsParallel().ForAll(x => x.Value.OldValue = x.Value.CurrentValue); //authorCals.AsParallel().ForAll(x => x.Value.CurrentValue = x.Value.CurrentValue * ratio); authorCals.AsParallel().ForAll(x => x.Value.CurrentValue = x.Value.CurrentValue * ratio * 0.8 + 200); } if (Math.Abs(max_old - max) > 50) { max_old = max; WriteResultToFile(max, txtResultPrefix.Text, authorCals, inproCals, confCals); } sw.Stop(); if (this.IsHandleCreated) { this.Invoke((MethodInvoker)delegate { txtMsgLog.Text += string.Format("Total: {0}:{1}:{2} Max={3} Ratio={12}(Sum AS1:{4}-SumIS1:{5}-sumCs:{6}-sumIs2:{7}- sumAs2{8} (A:{9}-P:{10}-C{11})\r\n", sw.Elapsed.Hours, sw.Elapsed.Minutes, sw.Elapsed.Seconds, max, sumAs1, sumIs1, sumCs, sumIs2, sumAs2, authorCals.Count, inproCals.Count, confCals.Count, ratio); txtMsgLog.SelectionStart = txtMsgLog.Text.Length; txtMsgLog.ScrollToCaret(); }); } else { Thread.CurrentThread.Abort(); } } WriteResultToFile(max, txtResultPrefix.Text, authorCals, inproCals, confCals); File.WriteAllText(Path.GetFullPath(txtFolder.Text + "\\" + txtResultPrefix.Text + "=" + txtYearTo.Text + "-" + ((int)max).ToString() + "-log.csv"), txtMsgLog.Text); this.Invoke((MethodInvoker)delegate { txtMsgLog.Text += "Done!!!"; this.Cursor = Cursors.Default; }); }
private void ProcessingByYear() { Dictionary<int, InproceedingsDBLP> inproCals = dicInproceedings.Where( x => { int year; if (int.TryParse(x.Value.Year, out year)) return Convert.ToInt32(x.Value.Year) <= Convert.ToInt32(txtYearTo.Text) && Convert.ToInt32(x.Value.Year) >= Convert.ToInt32(txtYearFrom.Text); else return false; }).ToDictionary(x => x.Key, x => x.Value); dicInproceedings.Clear(); Dictionary<int, AuthorDBLP> authorCals = new Dictionary<int, AuthorDBLP>(); Dictionary<string, ConferenceDBLP> confCals = new Dictionary<string, ConferenceDBLP>(); Parallel.ForEach(inproCals, inproceeding => { string[] AuthorsIDs = inproceeding.Value.AuthorsID.Split('|'); Parallel.For(0, AuthorsIDs.Length, ai => { int akey = 0; if (int.TryParse(AuthorsIDs[ai], out akey)) { AuthorDBLP authorDblp = dicAuthors[akey]; lock (lock_acal) { if (!authorCals.Keys.Contains(akey)) { authorCals.Add(akey, dicAuthors[akey]); authorCals[akey].CountInproceedings = 1; authorCals[akey].InproceedingsID = inproceeding.Value.Id.ToString(); authorCals[akey].CurrentValue = 1000; authorCals[akey].OldValue = 1000; } else { authorCals[akey].CountInproceedings++; authorCals[akey].InproceedingsID += "|" + inproceeding.Value.Id.ToString(); } } } }); lock (lock_ccal) { string[] keys = inproceeding.Value.Key.Split('/'); string conf_key = keys.Length > 1 ? keys[1] : keys[0]; if (!confCals.Keys.Contains(conf_key)) { confCals.Add(conf_key, dicStringConferences[conf_key]); confCals[conf_key].CountInproceedings = 1; confCals[conf_key].InproceedingsID = inproceeding.Value.Id.ToString(); } else { confCals[conf_key].CountInproceedings++; confCals[conf_key].InproceedingsID += "|" + inproceeding.Value.Id.ToString(); } } }); dicAuthors.Clear(); dicStringConferences.Clear(); dicConferences.Clear(); this.Invoke((MethodInvoker)delegate { txtMsgLog.Text = "Begin..."; Cursor = Cursors.WaitCursor; }); double sumAs1 = 0, sumIs1 = 0, sumCs = 0, sumIs2 = 0, sumAs2 = 0, min, ratio, max, max_old = 0, sum0; max = 1000; var sw = Stopwatch.StartNew(); ratio = 1; sum0 = authorCals.AsParallel().Sum(x => x.Value.CurrentValue); while (max > Convert.ToDouble(txtMinDelta.Text)) { sw.Start(); sumAs1 = authorCals.AsParallel().Sum(x => x.Value.CurrentValue); inproCals.AsParallel().ForAll(x => x.Value.SetValueFromAuthors(authorCals)); sumIs1 = inproCals.AsParallel().Sum(x => x.Value.CurrentValue); confCals.AsParallel().ForAll(x => x.Value.SetValueFromInproceedings(inproCals)); sumCs = confCals.AsParallel().Sum(x => x.Value.CurrentValue); inproCals.AsParallel().ForAll(x => x.Value.SetValueFromConferences(confCals)); sumIs2 = inproCals.AsParallel().Sum(x => x.Value.CurrentValue); authorCals.AsParallel().ForAll(x => x.Value.SetValueFromInproceedings(inproCals)); sumAs2 = authorCals.AsParallel().Sum(x => x.Value.CurrentValue); ratio = sum0 / sumAs2; min = authorCals.AsParallel().Min(x => Math.Abs(x.Value.CurrentValue - x.Value.OldValue)); max = authorCals.AsParallel().Max(x => Math.Abs(x.Value.CurrentValue - x.Value.OldValue)); if ((ratio - 1) > 0.009) { authorCals.AsParallel().ForAll(x => x.Value.OldValue = x.Value.CurrentValue); authorCals.AsParallel().ForAll(x => x.Value.CurrentValue = x.Value.CurrentValue * ratio); // authorCals.AsParallel().ForAll(x => x.Value.CurrentValue = x.Value.CurrentValue * ratio * 0.8 + 200); } if (Math.Abs(max_old - max) > 50) { max_old = max; WriteResultToFile(max, txtResultPrefix.Text, authorCals, inproCals, confCals); } sw.Stop(); this.Invoke((MethodInvoker)delegate { txtMsgLog.Text += string.Format("Total: {0}:{1}:{2} Max={3} Ratio={12}(Sum AS1:{4}-SumIS1:{5}-sumCs:{6}-sumIs2:{7}- sumAs2{8} (A:{9}-P:{10}-C{11})\r\n", sw.Elapsed.Hours, sw.Elapsed.Minutes, sw.Elapsed.Seconds, max, sumAs1, sumIs1, sumCs, sumIs2, sumAs2, authorCals.Count, inproCals.Count, confCals.Count, ratio); txtMsgLog.SelectionStart = txtMsgLog.Text.Length; txtMsgLog.ScrollToCaret(); }); } WriteResultToFile(max, txtResultPrefix.Text, authorCals, inproCals, confCals); File.WriteAllText(Path.GetFullPath(txtFolder.Text + "\\" + txtResultPrefix.Text + "=" + txtYearTo.Text + "-" + ((int)max).ToString() + "-log.csv"), txtMsgLog.Text); this.Invoke((MethodInvoker)delegate { txtMsgLog.Text += "Done!!!"; this.Cursor = Cursors.Default; }); }
public static string GenerateCanonicalizedResource(Uri uri) { StringBuilder sb = new StringBuilder("/"); sb.AppendFormat("{0:S}", GetAccountNameFromUri(uri)); string[] tokens = uri.AbsolutePath.Split(new char[] { '/' }); bool fAdded = false; for (int i = 0; i < tokens.Length; i++) { if (!string.IsNullOrEmpty(tokens[i])) { sb.AppendFormat("/{0:S}", tokens[i]); fAdded = true; } } if (!fAdded) sb.Append("/"); Dictionary<string, List<string>> dParams = new Dictionary<string, List<string>>(); if (!string.IsNullOrEmpty(uri.Query)) { foreach (string sParam in uri.Query.Substring(1).Split(new char[] { '&' })) { int idx = sParam.IndexOf('='); string sKey = Uri.UnescapeDataString(sParam.Substring(0, idx)).ToLowerInvariant(); string sValue = Uri.UnescapeDataString(sParam.Substring(idx + 1, sParam.Length - idx - 1)); if (!dParams.ContainsKey(sKey)) { if ((sKey == "nextpartitionkey") || (sKey == "nextrowkey")) continue; dParams[sKey] = new List<string>(); } dParams[sKey].Add(sValue); } } KeyValuePair<string, List<string>>[] kvpairs = dParams.AsParallel().OrderBy(item => item.Key).ToArray(); if (kvpairs.Length > 0) sb.Append("\n"); for (int iPair = 0; iPair < kvpairs.Length; iPair++) { StringBuilder sbParam = new StringBuilder(); sbParam.AppendFormat("{0:S}:", kvpairs[iPair].Key); string[] vals = kvpairs[iPair].Value.AsParallel().OrderBy(item => item).ToArray(); for (int i = 0; i < vals.Length; i++) { sbParam.Append(vals[i]); if (i + 1 < vals.Length) sbParam.Append(","); } if ((iPair + 1) < kvpairs.Length) sbParam.Append("\n"); sb.Append(sbParam); } //System.Diagnostics.Trace.TraceInformation("GenerateCanonicalizedResource: Generated string: " + sb.ToString()); return sb.ToString();//.Replace("%82", new string(new char[] { (char)0xEF, (char)0xBF, (char)0xBD })); }
/// <summary> /// Make a step in the game /// </summary> private void GameStep(ref List<PointULong> alive) { var aliveNeighbors = new Dictionary<PointULong, int>(); foreach (var i in _aliveCells.Concat(_aroundAliveCells).AsParallel()) { var nearMeCells = 0; foreach (var aliveCell in _aliveCells.AsParallel()) { if (i.Value.IsNearMe(aliveCell.Value)) nearMeCells++; } //_aliveCells.AsParallel().Count(j => i.Value.IsNearMe(j.Value)); aliveNeighbors[i.Key] = nearMeCells; } alive = new List<PointULong>(); foreach (var i in aliveNeighbors.AsParallel()) { var isAlive = _aliveCells.ContainsKey(i.Key); var willBorn = Algorithm.NextState(isAlive, i.Value); if (willBorn) alive.Add(i.Key); } _aliveCells.Clear(); _aroundAliveCells.Clear(); SetAlive(alive); }
private void SaveRunningSprintData(Dictionary<string, double> resultOfAnalysis, Dictionary<string, uint> sectionPositions, uint columnPosition) { if (!resultOfAnalysis.Any(r => r.Key.Equals("--Indefinido--"))) resultOfAnalysis.Add("--Indefinido--", 0); foreach (var keyValue in resultOfAnalysis.AsParallel()) { SetSprintValueByResponsible(_worksheet, sectionPositions, columnPosition, keyValue.Key, keyValue.Value); Console.WriteLine("\t\t> {0} - {1}", keyValue.Key, keyValue.Value); } }