/// <summary> /// if needed, will merge the images base on page in the image names /// </summary> /// <param name="imageBytes"></param> /// <param name="imageNames"></param> /// <returns></returns> public Dictionary<PageImageIndex, System.Drawing.Image> Merge(Dictionary<PageImageIndex, System.Drawing.Image> imagesList, string outputPath) { var imageListByPage = imagesList.GroupBy(i => i.Key.PageIndex); var newImageList = new Dictionary<PageImageIndex, System.Drawing.Image>(); foreach (var imagesInfo in imageListByPage) { var imagesPage = new Dictionary<PageImageIndex, System.Drawing.Image>(); foreach (var item in imagesInfo) { var image = item.Value; if (item.Value == null) { var imagePath = string.Format(@"{0}\{1}", outputPath, item.Key.ImageName); image = new System.Drawing.Bitmap(imagePath); } imagesPage.Add(item.Key, image); } //var imagesPage = imagesInfo.Select(i => i).ToDictionary(x => x.Key, x => x.Value); var keyValue = MergeGroup(imagesPage, outputPath); newImageList.Add(keyValue.Key, keyValue.Value); } return newImageList; }
public void InitCaches() { var db = new FacesDBDataContext(_connectionString); _faceUKeyLookup = db.Faces.ToDictionary(x => x.FaceUKey, x => (api.Face) new FaceImpl(x, _m, null)); var query = (from f in db.Faces join p in db.Persons on f.PersonID equals p.PersonID select new { f, p }); _Faces = new Dictionary<api.Face,api.Person>(); Dictionary<int, api.Person> persons = new Dictionary<int,api.Person>(); foreach (var x in query) { // todo; build pers dic at same time... api.Person person = null; if (!persons.TryGetValue(x.p.PersonID, out person)) { person = (api.Person)new PersonImpl(x.p.FirstName, x.p.LastName, x.p.PersonID); persons.Add(person.Id, person); } api.Face thisFace = _faceUKeyLookup[x.f.FaceUKey]; thisFace.Person = person; _Faces.Add(thisFace, person); } _Persons = _Faces.GroupBy(x => x.Value).ToDictionary(x => x.Key, x => x.Select(y=>y.Key).ToList()); _allPersonsLookup = persons; foreach (var pers in db.Persons) // add in other persons that don't have faces. { if (!_allPersonsLookup.ContainsKey(pers.PersonID)) _allPersonsLookup.Add(pers.PersonID, (api.Person)new PersonImpl(pers.FirstName, pers.LastName, pers.PersonID)); } _PicturesToFaces = db.Faces .ToLookup(x => x.PictureID, x => _faceUKeyLookup[x.FaceUKey]); }
public AggregateResult(IEnumerable<GameResult> results) { _playerToScoreMap = new Dictionary<BotPlayer, int>(); results.SelectMany(x => x.Players).Each(x => _playerToScoreMap[x] = 0); results.Each(result => { if (result.IsTie) { result.Players.Each(player => { _playerToScoreMap[player]++; }); } else { _playerToScoreMap[result.Winner] += 3; } }); var winners = _playerToScoreMap.GroupBy(x => x.Value).OrderByDescending(x => x.Key).First(); if (winners.Count() == _playerToScoreMap.Count) { IsTie = true; } else { Winner = winners.First().Key; } }
public EBIDatasetParser() { var keymap = new Dictionary<string, ColumnName>(); keymap["Array Data File"] = ColumnName.Sample; //E-MTAB-365 keymap["Characteristics[Age]"] = ColumnName.Age; keymap["Characteristics[Grade::Scarff Bloom Richardson]"] = ColumnName.Grade; keymap["Characteristics[ESR1::Protein expression]"] = ColumnName.ER; keymap["Characteristics[PGR::Protein expression]"] = ColumnName.PR; keymap["Characteristics[ERBB2::Protein expression]"] = ColumnName.HER2; //E-TABM-158 keymap["Characteristics [EstrogenReceptorStatus]"] = ColumnName.ER; keymap["Characteristics [Progesterone Receptor status]"] = ColumnName.PR; keymap["Characteristics [ErbB2 positive (IHC)]"] = ColumnName.HER2; keymap["Characteristics [dead of disease]"] = ColumnName.DeadOfDisease; keymap["Characteristics [node positive]"] = ColumnName.NodalStatus; keymap["Characteristics [TumorStaging]"] = ColumnName.TumorStage; keymap["Characteristics [alive at endpoint]"] = ColumnName.OverallServive; keymap["Characteristics [TumorGrading]"] = ColumnName.Grade; nameKeyMap = keymap.GroupBy(m => m.Value).ToDictionary(m => m.Key, m => new HashSet<string>(from n in m select n.Key)); }
void SplitGroup() { int counter = 0; var groups = requests.GroupBy(x => counter++ % 2); foreach (var group in groups) { new OpenSeaRequestGroup(getRetryDelay(), group, getRetryDelay); } }
private static Dictionary <string, string> CreateExtensionLookup() { var dict = MimeTypeLookup .GroupBy(i => i.Value) .ToDictionary(x => x.Key, x => x.First().Key, StringComparer.OrdinalIgnoreCase); dict["image/jpg"] = ".jpg"; return(dict); }
public MiHome(Dictionary <string, string> namesMap, string gatewayPassword = null, string gatewaySid = null) : this(gatewayPassword, gatewaySid) { if (namesMap.GroupBy(x => x.Value).Any(x => x.Count() > 1)) { throw new ArgumentException("Values in the dictionary must be unique"); } _namesMap = namesMap; }
internal IEnumerable <string> Help() { // The magic number `19` here is calculated based on how the description is dispayed for other help entries to keep the texts aligned // (As of now other help entries include REPL commands and script derectives, both have manually formatted help description strings. string format = "{0,-" + Math.Max(19, _maxCommandNameLength) + "} {1}"; return(_commands.GroupBy(entry => entry.Value). Select(group => string.Format(format, string.Join(_commandSeparator, group.Key.Names.Select(s => CommandPrefix + s)), group.Key.Description)). OrderBy(line => line)); }
public void Dump() { foreach (var e in dict.GroupBy(en => en.Key.Substring(0, en.Key.IndexOf(' ')))) { foreach (var c in e.OrderByDescending(a => a.Value)) { Console.WriteLine(c.Key + " : " + c.Value); } } }
public async Task Send(Dictionary <BinaryData, SendMessageOptions> items) { // await sender.SendMessagesAsync(items.Select(x => GetServiceBusMessage(x.Key, x.Value))); var bySessionId = items.GroupBy(s => s.Value?.SessionId); foreach (var sessionSet in bySessionId) { await sender.SendMessagesAsync(sessionSet.Select(x => GetServiceBusMessage(x.Key, x.Value))); } }
public static List <TestComparisonGroup> Compare(Dictionary <TestSuite, List <Test> > raw) { return(raw.GroupBy(x => x.Key.Name) .Select(x => new TestComparisonGroup { Name = x.Key, Tests = CompareGroups(x.ToList()) }) .ToList()); }
/// <summary> /// 检测字典中的重复值。 /// </summary> /// <param name="dicField">字典。</param> /// <returns>检测的重复值集合结果,key是重复的值,key对应的是一个重复值字典集合。</returns> public IEnumerable <IGrouping <string, KeyValuePair <int, string> > > DuplicateDetection(Dictionary <int, string> dicField) { if (dicField == null || dicField.Count == 0) { return(null); } var duplicateValues = dicField.GroupBy(x => x.Value).Where(x => x.Count() > 1); return(duplicateValues); }
/// <summary> /// 检测字点中的重复值。 /// </summary> /// <param name="dicField">字典。</param> /// <returns>检测的重复值集合结果,key是重复的值,key对应的是一个重复值字典集合。</returns> public Dictionary <string, int> GetDuplicateValueCount(Dictionary <int, string> dicField) { if (dicField == null || dicField.Count == 0) { return(null); } var duplicateValues = dicField.GroupBy(x => x.Value).Where(x => x.Count() > 1); return(duplicateValues.ToDictionary(groupValue => groupValue.Key, groupValue => groupValue.ToList().Count)); }
public Contracts.ExpensesReportDto GenerateReport() { // from user Id to user Id var expenseMap = new Dictionary<Tuple<int, int>, decimal>(); Action<int, int, decimal> addToMap = (fromUser, toUser, amount) => { var key = new Tuple<int, int>(fromUser, toUser); if (expenseMap.ContainsKey(key)) amount += expenseMap[key]; if (amount != 0) expenseMap[key] = amount; else expenseMap.Remove(key); }; // add expenses var allExpenses = DataContext.ExpenseItemsAsLightDto.ToArray(); var calculator = new CostCalculatorStrategy(); foreach (var expense in DataContext.Expenses.Where(e => e.Pricing != null).ToArray()) { var expenseItems = allExpenses.Where(ei => ei.ExpenseId == expense.Id); foreach (var costData in calculator.CalculateCosts(expense, expenseItems)) { addToMap(costData.UserId, expense.Creator.Id, costData.Cost); } } // remove bi-directional items NormalizeMap(expenseMap); // build result var resultItems = new List<ExpensesUserReportDto>(); var allUsers = DataContext.UsersAsLightDto.ToDictionary(u=>u.Id); foreach (var emi in expenseMap.GroupBy(em => em.Key.Item1)) { var user = allUsers[emi.Key]; resultItems.Add(new ExpensesUserReportDto() { UserId = user.Id, FullName = user.FullName, TotalCost = emi.Sum(ei => ei.Value), CostDetails = emi.Select(ei => new ExpensesCostDetailDto() { Cost = ei.Value, UserId = ei.Key.Item2, FullName = allUsers[ei.Key.Item2].FullName }).ToArray() }); } var result = new ExpensesReportDto(); result.Users = resultItems.ToArray(); return result; }
static void Main(string[] args) { string command = Console.ReadLine(); Dictionary <string, string> dict = new Dictionary <string, string>(); while (command != "Lumpawaroo") { string[] arr = command .Split(' ', StringSplitOptions.RemoveEmptyEntries) .ToArray(); if (arr.Contains("|")) { string[] gosho = arr.ToArray(); string side = command.Split(" | ", 2)[0]; string user = command.Split(" | ", 2)[1]; if (!dict.ContainsKey(user)) { dict.Add(user, side); } } if (arr.Contains("->")) { string side = command.Split(" -> ", 2)[1]; string user = command.Split(" -> ", 2)[0]; if (dict.ContainsKey(user)) { dict[user] = side; } else { dict.Add(user, side); } Console.WriteLine($"{user} joins the {side} side!"); } command = Console.ReadLine(); } foreach (var item in dict.GroupBy(x => x.Value) .OrderByDescending(x => x.Count()) .ThenBy(x => x.Key)) { Console.WriteLine($"Side: {item.Key}, Members: {item.Count()}"); foreach (var gosho in item.OrderBy(x => x.Key)) { Console.WriteLine($"! {gosho.Key}"); } } }
static void Main(string[] args) { string inputLine = Console.ReadLine(); var catalog = new Dictionary <string, string>(); while (inputLine != "Lumpawaroo") { if (inputLine.Contains(" | ")) { string[] tokens = inputLine.Split(" | "); string forceSide = tokens[0]; string forceUser = tokens[1]; if (!catalog.ContainsKey(forceUser)) { catalog.Add(forceUser, forceSide); } } else if (inputLine.Contains(" -> ")) { string[] tokens = inputLine.Split(" -> "); string forceSide = tokens[1]; string forceUser = tokens[0]; if (catalog.ContainsKey(forceUser)) { if (!catalog.ContainsKey(forceSide)) { catalog[forceUser] = forceSide; } } else if (!catalog.ContainsKey(forceUser)) { catalog.Add(forceUser, forceSide); } Console.WriteLine($"{forceUser} joins the {forceSide} side!"); } inputLine = Console.ReadLine(); } var currentUser = catalog .GroupBy(x => x.Value) .OrderByDescending(x => x.Count()) .ThenBy(x => x.Key); foreach (var kvp in currentUser) { Console.WriteLine($"Side: {kvp.Key}, Members: {kvp.Count()}"); foreach (var user in kvp.OrderBy(x => x.Key)) { Console.WriteLine($"! {user.Key}"); } } }
static void Main(string[] args) { string command = Console.ReadLine(); Dictionary <string, string> forceUsers = new Dictionary <string, string>(); while (command != "Lumpawaroo") { var input = command.Split(); if (input.Contains("|")) { string[] cmdArg = command.Split(" | "); string forceSide = cmdArg[0]; string forceUser = cmdArg[1]; if (!forceUsers.ContainsKey(forceUser)) { forceUsers.Add(forceUser, forceSide); } } else if (input.Contains("->")) { string[] cmdArg = command.Split(" -> "); string forceUser = cmdArg[0]; string forceSide = cmdArg[1]; if (forceUsers.ContainsKey(forceUser)) { forceUsers[forceUser] = forceSide; } else { forceUsers.Add(forceUser, forceSide); } Console.WriteLine($"{forceUser} joins the {forceSide} side!"); } command = Console.ReadLine(); } foreach (var user in forceUsers .GroupBy(x => x.Value) .OrderByDescending(x => x.Count()) .ThenBy(n => n.Key)) { Console.WriteLine($"Side: {user.Key}, Members: {user.Count()}"); foreach (var item in user.OrderBy(m => m.Key)) { Console.WriteLine(($"! {item.Key}")); } } }
private static HashSet <PackageIdentity> GetHighestVersionsById(Dictionary <string, PackageIdentity> identities) { var results = new HashSet <PackageIdentity>(); foreach (var group in identities.GroupBy(e => e.Value.Id, StringComparer.OrdinalIgnoreCase)) { results.Add(group.OrderByDescending(e => e.Value.Version).First().Value); } return(results); }
/// <summary> /// Group votes by task. /// </summary> /// <param name="allVotes">A list of all votes.</param> /// <returns>Returns all the votes, grouped by task (case-insensitive).</returns> public static IOrderedEnumerable<IGrouping<string, KeyValuePair<string, HashSet<string>>>> GroupVotesByTask(Dictionary<string, HashSet<string>> allVotes) { var grouped = allVotes.GroupBy(v => VoteString.GetVoteTask(v.Key.GetFirstLine()), StringComparer.OrdinalIgnoreCase).OrderBy(v => v.Key); if(VoteCounter.Instance.OrderedTaskList != null) { grouped = grouped.OrderBy(v => VoteCounter.Instance.OrderedTaskList.IndexOf(v.Key)); } return grouped; }
public State(Dictionary <UInt64, Fact> facts) { Facts = facts; A = new Lazy <Dictionary <uint, Fact[]> >(() => Facts .GroupBy(prop => prop.Value.AId) .ToDictionary(g => g.Key, g => g.Select(v => v.Value).ToArray())); Rel = new Lazy <Dictionary <uint, Fact[]> >(() => Facts .GroupBy(prop => prop.Value.RelId) .ToDictionary(g => g.Key, g => g.Select(v => v.Value).ToArray())); B = new Lazy <Dictionary <uint, Fact[]> >(() => Facts .GroupBy(prop => prop.Value.BId) .ToDictionary(g => g.Key, g => g.Select(v => v.Value).ToArray())); _hashCode = new Lazy <int>(() => (int)Facts .Select(p => p.Key) .Aggregate((a, e) => a ^ e)); }
private ClientGroupStats BuildClientGroupStatsResponse(bool forSender = false) { Dictionary <string, int> clientGroupCounts = _clientIDGroupNameHash.GroupBy(x => x.Value) .ToDictionary(x => x.Key, x => x.Count()); return(new ClientGroupStats() { GroupName = forSender ? _clientIDGroupNameHash[Context.ConnectionId] : "", ConnectedClientGroupCounts = clientGroupCounts }); }
public void Write(LogWriter writer) { var groups = _resultCache.GroupBy(kvp => kvp.Value.Sequence); foreach (var group in groups) { var operations = group.ToArray(); var batch = EncodeBatch(operations); writer.EncodeBlocks(batch); } }
public static void createDiscreteSets(Dictionary <int, string> inputSet, string filePath, BlobPusher pusher) { List <Dictionary <int, string> > dictionaryList = inputSet.GroupBy(pair => pair.Value) .Select(d => d.ToDictionary(pair => pair.Key, pair => pair.Value)) .ToList(); foreach (Dictionary <int, string> dict in dictionaryList) { pusher.push(dict, filePath + "/" + dict.First().Value); } }
static void Main(string[] args) { string input = Console.ReadLine(); Dictionary<string, string> userSide = new Dictionary<string, string>(); while (input != "Lumpawaroo") { if(input.Contains("|")) { string[] sideArgs = input.Split(" | "); string side = sideArgs[0]; string user = sideArgs[1]; if(!userSide.ContainsKey(user)) { userSide.Add(user, side); } } else if(input.Contains("->")) { string[] userArgs = input.Split(" -> "); string user = userArgs[0]; string side = userArgs[1]; if(!userSide.ContainsKey(user)) { userSide.Add(user, side); Console.WriteLine($"{user} joins the {side} side!"); } else { userSide[user] = side; Console.WriteLine($"{user} joins the {side} side!"); } } input = Console.ReadLine(); } var sorted = userSide.GroupBy(x => x.Value).OrderByDescending(x => x.Count()).ThenBy(x => x.Key); foreach (var side in sorted) { Console.WriteLine($"Side: { side.Key}, Members: {side.Count()} "); foreach (var user in side.OrderBy(x => x.Key)) { Console.WriteLine($"! {user.Key}"); } } }
/// <summary> /// Writes various results to a StreamWriter. /// </summary> /// <param name="writer">A StreamWriter instance.</param> /// <param name="writeCommunityParameters">Set true to write community parameters.</param> /// <param name="writeWorkerParameters">Set true to write worker parameters.</param> /// <param name="writeWorkerCommunities">Set true to write worker communities.</param> /// <param name="writeProbWords">Set true to write word probabilities</param> /// <param name="topWords">Number of words to select</param> public void WriteResults(StreamWriter writer, bool writeCommunityParameters, bool writeWorkerParameters, bool writeWorkerCommunities, bool writeProbWords, int topWords = 30) { base.WriteResults(writer, writeCommunityParameters, writeWorkerCommunities, writeWorkerCommunities); DataMappingWords MappingWords = Mapping as DataMappingWords; if (writeProbWords && this.ProbWords != null) { int NumClasses = ProbWords.Length; var classifiedWords = new Dictionary <string, KeyValuePair <string, double> >(); for (int c = 0; c < NumClasses; c++) { string className = string.Empty; if (MappingWords != null) { if (MappingWords.WorkerCount > 100) // Assume it's CF { className = MappingWords.CFLabelName[c]; } else { className = MappingWords.SPLabelName[c]; } writer.WriteLine($"Class {className}"); } Vector probs = ProbWords[c].GetMean(); var probsDictionary = probs.Select((value, index) => new KeyValuePair <string, double>(MappingWords.Vocabulary[index], Math.Log(value))).OrderByDescending(x => x.Value).ToArray(); topWords = Math.Min(topWords, probsDictionary.Length); for (int w = 0; w < topWords; w++) { writer.WriteLine($"\t{probsDictionary[w].Key}: \t{probsDictionary[w].Value:0.000}"); if (!string.IsNullOrEmpty(className)) { KeyValuePair <string, double> classifiedWord; if (!classifiedWords.TryGetValue(probsDictionary[w].Key, out classifiedWord) || classifiedWord.Value < probsDictionary[w].Value) { classifiedWords[probsDictionary[w].Key] = new KeyValuePair <string, double>(className, probsDictionary[w].Value); } } } } writer.WriteLine(); writer.WriteLine($"Main classes:"); foreach (var wordByClass in classifiedWords.GroupBy(classified => classified.Value.Key)) { writer.WriteLine($"Class {wordByClass.Key}:"); foreach (var word in wordByClass.OrderByDescending(w => w.Value.Value)) { writer.WriteLine($"\t{word.Key}"); } } } }
static void Main(string[] args) { string command = null; //<member,side> var users = new Dictionary <string, string>(); while ((command = Console.ReadLine()) != "Lumpawaroo") { string side = null; string member = null; var action = command.Split(); if (action.Contains("|")) { side = command.Split(" | ", 2)[0]; member = command.Split(" | ", 2)[1]; if (!users.ContainsKey(member)) { users.Add(member, side); } } else if (action.Contains("->")) { side = command.Split(" -> ", 2)[1]; member = command.Split(" -> ", 2)[0]; if (users.ContainsKey(member)) { users[member] = side; } else { users.Add(member, side); } Console.WriteLine($"{member} joins the {side} side!"); } } foreach (var orderedSide in users .GroupBy(x => x.Value) .OrderByDescending(x => x.Count()) .ThenBy(x => x.Key)) { Console.WriteLine($"Side: {orderedSide.Key}, Members: {orderedSide.Count()}"); foreach (var orderedUser in orderedSide.OrderBy(x => x.Key)) { Console.WriteLine($"! {orderedUser.Key}"); } } }
public async Task <IEnumerable <SurvivingMutant> > RunAll( ITestRunner testRunner, string baseTempDirectory, IEventListener eventListener) { var survivingMutants = new List <SurvivingMutant>(); var survivingSyntaxNodes = new HashSet <SyntaxNode>(); var reportedMembers = new HashSet <string>(); var jobsBySourceFile = jobsWithMetadata.GroupBy(x => x.Key.SourceFilePath, x => x).ToArray(); for (var sourceFileIndex = 0; sourceFileIndex < jobsBySourceFile.Length; sourceFileIndex++) { var jobsForSourceFile = jobsBySourceFile[sourceFileIndex]; var sourceFilePath = jobsForSourceFile.Key; eventListener.BeginMutationOfFile( sourceFilePath, Path.GetDirectoryName(config.SolutionFilePath), sourceFileIndex, jobsBySourceFile.Length); foreach (var mutationJobAndMetadata in jobsForSourceFile) { var metadata = mutationJobAndMetadata.Key; var mutationJob = mutationJobAndMetadata.Value; var syntaxNodeAlreadyHadSurvivingMutant = survivingSyntaxNodes.Contains(mutationJob.OriginalNode); if (syntaxNodeAlreadyHadSurvivingMutant) { continue; } if (!reportedMembers.Contains(metadata.MemberName)) { eventListener.MemberMutating(metadata.MemberName); reportedMembers.Add(metadata.MemberName); } eventListener.SyntaxNodeMutating(metadata.SyntaxNodeIndex, metadata.SyntaxNodesTotal); var survivingMutant = await mutationJob.Run(testRunner, baseTempDirectory, eventListener); if (survivingMutant != null) { survivingMutants.Add(survivingMutant); survivingSyntaxNodes.Add(mutationJob.OriginalNode); eventListener.MutantSurvived(survivingMutant); } } eventListener.EndMutationOfFile(sourceFilePath); } return(survivingMutants); }
public static int mostBalancedPartition(Dictionary<int, int> parent, List<int> files_size) { Dictionary<int, IEnumerable<int>> children = parent.GroupBy(pair => pair.Value) .ToDictionary(group => group.Key, group => group.Select(pair => pair.Key)); Dictionary<int, long> realFileSizes = new Dictionary<int, long>(); calculateRealFileSizesRecursive(children, realFileSizes, files_size, 0); long minimumDifference = int.MaxValue; mostBalancedPartitionRecursive(children, realFileSizes, 0, ref minimumDifference); return (int)minimumDifference; }
private async Task <Solution?> FixAllContextsAsync( FixAllContext originalFixAllContext, ImmutableArray <FixAllContext> fixAllContexts ) { var cancellationToken = originalFixAllContext.CancellationToken; var progressTracker = originalFixAllContext.GetProgressTracker(); progressTracker.Description = FixAllContextHelper.GetDefaultFixAllTitle( originalFixAllContext ); // We have 2*P + 1 pieces of work. Computing diagnostics and fixes/changes per context, and then one pass // applying fixes. progressTracker.AddItems(fixAllContexts.Length * 2 + 1); // Mapping from document to the cumulative text changes created for that document. var docIdToTextMerger = new Dictionary <DocumentId, TextChangeMerger>(); // Process each context one at a time, allowing us to dump most of the information we computed for each once // done with it. The only information we need to preserve is the data we store in docIdToTextMerger foreach (var fixAllContext in fixAllContexts) { Contract.ThrowIfFalse( fixAllContext.Scope is FixAllScope.Document or FixAllScope.Project ); await FixSingleContextAsync(fixAllContext, progressTracker, docIdToTextMerger) .ConfigureAwait(false); } // Finally, merge in all text changes into the solution. We can't do this per-project as we have to have // process *all* diagnostics in the solution to find the changes made to all documents. using (progressTracker.ItemCompletedScope()) { if (docIdToTextMerger.Count == 0) { return(null); } var currentSolution = originalFixAllContext.Solution; foreach (var group in docIdToTextMerger.GroupBy(kvp => kvp.Key.ProjectId)) { currentSolution = await ApplyChangesAsync( currentSolution, group.SelectAsArray(kvp => (kvp.Key, kvp.Value)), cancellationToken ) .ConfigureAwait(false); } return(currentSolution); } }
/// <summary> /// 将此翻译输出为可移动字符串 /// </summary> /// <returns></returns> public string Pack() { var content = new StringBuilder(); foreach (var group in _translatableStrings.GroupBy(e => e.Value)) { content.AppendLine(string.Join(":", group.Select(e => Convert.ToString(e.Key, 16).PadLeft(8, '0')))); content.AppendLine(group.Key.PackEscapeCharacters()); content.AppendLine(); } return(content.ToString()); }
protected void PopulateSourceFiles() { _sourceFiles = _methodDictionary.GroupBy(kvp => kvp.Key.GetSourceFilePath()).Select( kvp => new SourceFile( criteriaContext: CriteriaContext, containedMethods: kvp.Select(k => k.Value).ToArray(), fullName: kvp.Key, displayName: Path.GetFileName(kvp.Key), height: _maxEndLine + 10 )).ToArray(); }
/// <summary> /// Creates the new round. /// </summary> /// <param name="newPilotSequence">The new pilot sequence.</param> private void CreateNewRound(Dictionary <string, FlightGroup> newPilotSequence) { // Group the pilots by flight group var flightGroupings = newPilotSequence.GroupBy(nps => nps.Value); // Populate the round with them. foreach (var flightGroup in flightGroupings) { var pilots = flightGroup.Select(p => this.PilotsInContest.Where(pilot => pilot.Id == p.Key).Single()).ToList(); this.Contest.Rounds[this.CurrentRoundOrdinal].FlightGroups.Add(flightGroup.Key, pilots); } }
static void Main(string[] args) { string command = string.Empty; var dict = new Dictionary <string, string>(); string user = string.Empty; // key string side = string.Empty; // value while ((command = Console.ReadLine()) != "Lumpawaroo") { var input = command .Split(new string[] { " | ", " -> " }, StringSplitOptions.RemoveEmptyEntries) .ToList(); if (command.Split().Contains("|")) { user = input[1]; // key side = input[0]; // value if (!dict.ContainsKey(user)) { dict.Add(user, side); } } else if (command.Split().Contains("->")) { user = input[0]; // key side = input[1]; // value if (dict.ContainsKey(user)) { dict[user] = side; } else { dict.Add(user, side); } Console.WriteLine($"{user} joins the {side} side!"); } } foreach (var Side in dict .GroupBy(x => x.Value) .OrderByDescending(x => x.Count()) .ThenBy(x => x.Key)) { Console.WriteLine($"Side: {Side.Key}, Members: {Side.Count()}"); foreach (var User in Side.OrderBy(x => x.Key)) { Console.WriteLine($"! {User.Key}"); } } }
static void Main(string[] args) { Dictionary <string, string> forceUsers = new Dictionary <string, string>(); string command = null; while ((command = Console.ReadLine()) != "Lumpawaroo") { var test = command.Split(); if (test.Contains("|")) { string[] commandArr = command.Split(" | "); string forceSide = commandArr[0]; string forceUser = commandArr[1]; if (!forceUsers.ContainsKey(forceUser)) { forceUsers.Add(forceUser, forceSide); } } else if (test.Contains("->")) { string[] commandArr = command.Split(" -> "); string forceUser = commandArr[0]; string forceSide = commandArr[1]; if (forceUsers.ContainsKey(forceUser)) { forceUsers[forceUser] = forceSide; } else { forceUsers.Add(forceUser, forceSide); } Console.WriteLine($"{forceUser} joins the {forceSide} side!"); } } foreach (var users in forceUsers .GroupBy(x => x.Value) .OrderByDescending(x => x.Count()) .ThenBy(c => c.Key)) { Console.WriteLine($"Side: {users.Key}, Members: {users.Count()}"); foreach (var elm in users.OrderBy(t => t.Key)) { Console.WriteLine($"! {elm.Key}"); } } }
static void Main(string[] args) { var users = new Dictionary <string, string>(); while (true) { string input = Console.ReadLine(); if (input == "Lumpawaroo") { break; } if (input.Contains("|")) { string[] tokens = Regex.Split(input, @" \| "); string user = tokens[1]; string side = tokens[0]; if (!users.ContainsKey(user)) { users.Add(user, side); } users[user] = side; } else { string[] tokens = Regex.Split(input, @" \-\> "); string user = tokens[0]; string side = tokens[1]; if (!users.ContainsKey(user)) { users.Add(user, side); } users[user] = side; Console.WriteLine("{0} joins the {1} side!", user, side); } } var filtered = users.GroupBy(x => x.Value).ToDictionary(x => x.Key, x => x.ToDictionary(y => y.Key, y => y.Value)); foreach (var item in filtered) { string side = item.Key; Dictionary <string, string> abv = item.Value; Console.WriteLine("Side:{0}, Members{1}", side, abv.Count); foreach (var itemm in abv) { string name = itemm.Key; Console.WriteLine(name); } } }
public static void GenerateSalesReportXMLMontly(List<XMLReportInfo> salesReports) { var doc = new XDocument(); var sales = new XElement("sales"); foreach (var report in salesReports) { var sale = new XElement("sale", new XAttribute("vendor", report.Key)); var dates = report.Dates.Distinct().ToList(); Dictionary<DateTime, decimal> pair = new Dictionary<DateTime, decimal>(); for (int i = 0; i < dates.Count; i++) { pair[dates[i]] = 0; } for (int i = 0; i < report.Dates.Count; i++) { for (int j = 0; j < dates.Count; j++) { if (report.Dates[i] == dates[j]) { pair[dates[j]] += report.Sums[i]; } } } var monthExpens = pair.GroupBy(x => x.Key.Month).ToList(); for (int i = 0; i < monthExpens.Count(); i++) { var expense = new XElement("expenses", new XAttribute("month", CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(monthExpens[i].Key).Substring(0,3) + "-2013")); decimal sum = 0; foreach (var item in monthExpens) { foreach (var dailySum in item) { sum += dailySum.Value; } } expense.Value = sum.ToString(); sale.Add(expense); } sales.Add(sale); } doc.Add(sales); // Console.WriteLine(doc); doc.Save(@"..\..\SalesReportByMonth.xml"); }
/// <summary> /// Parse and Import to DTOs /// </summary> /// <param name="spreadsheet"></param> /// <param name="parseErrors"></param> /// <returns></returns> public List<DocumentImportDTO> ValidateAndImportDocuments(ExcelPackage spreadsheet, ref Dictionary<string, List<string>> parseErrors) { var items = new List<DocumentImportDTO>(); if (spreadsheet != null && spreadsheet.Workbook != null) { var worksheet = spreadsheet.Workbook.Worksheets.SingleOrDefault(x => x.Name == "Items"); if (worksheet == null) { return items; } var totalRows = worksheet.Dimension.End.Row; for (var rowId = 2; rowId <= totalRows; rowId++) { //Prepare handle name for storing and grouping errors var urlSegment = worksheet.GetValue<string>(rowId, 1); var name = worksheet.GetValue<string>(rowId, 4); var handle = urlSegment.HasValue() ? urlSegment : name; if (string.IsNullOrWhiteSpace(handle) || items.Any(x => x.UrlSegment == urlSegment)) continue; List<string> errors = parseErrors.ContainsKey(handle) ? parseErrors[handle] : new List<string>(); var item = GetDocumentImportDataTransferObject(worksheet, rowId, name, ref errors); parseErrors[handle] = errors; items.Add(item); } //Remove duplicate errors parseErrors = parseErrors.GroupBy(x => x.Value) .Select(x => x.First()) .ToDictionary(pair => pair.Key, pair => pair.Value); } //Remove handles with no errors parseErrors = parseErrors.Where(x => x.Value.Any()).ToDictionary(pair => pair.Key, pair => pair.Value); return items; }
public void ThreadNamesTest() { var rnd = new Random(); var range = Enumerable.Range(0, 50); var rangeBack = new Dictionary<int, int>(); var rangeBackLocker = new object(); range.AsParallel().AsOrdered() .WithDegreeOfParallelism(4).ForAll(x => { lock (rangeBackLocker) { rangeBack.Add(x, Thread.CurrentThread.ManagedThreadId); } Thread.Sleep(100 * rnd.Next(10)); }); Assert.AreEqual(rangeBack.GroupBy(x=>x.Value).Count(), 4); }
public void DictionaryExample() { // Mime Types Dictionary<string, string> lookupTable = new Dictionary<string, string>(); lookupTable.Add("html", "text/html"); lookupTable.Add("htm", "text/html"); lookupTable.Add("png", "image/png"); lookupTable.Add("pdf", "application/pdf"); // Are there any type with more than one extension associated? var t = lookupTable.GroupBy(x => x.Key).Select(x => new { MimeType = x.Key, Count = x.Count() }).Where(x => x.Count > 1); // for each of the types with more than one extension... foreach (var item in t) { // get the extensions: var extensionArray = lookupTable.Where(x => x.Value == item.MimeType).Select(x => x.Key).ToArray<string>(); var extensions = string.Join(",", extensionArray); Console.WriteLine("{0} has the following extensions: {1}", item, extensions); } }
public virtual Dictionary<string, string> DowncaseDictionary(Dictionary<string, string> dict) { Contract.Requires<ArgumentNullException>(dict != null); return dict.GroupBy(x => x.Key.ToLower()).Select(x => x.First()) .ToDictionary(x => x.Key.ToLower(), x => x.Value); }
void CheckSchema() { using( MySqlTransaction transaction = connection.BeginTransaction() ) { // Create metadata table. Does noting if table already exists. transaction.ExecuteNonQuery( MetadataTableSchema ); // load metadata using( MySqlCommand loadMetadataCmd = new MySqlCommand( LoadMetadataQuery, connection, transaction ) ) { using( MySqlDataReader reader = loadMetadataCmd.ExecuteReader() ) { if( reader.Read() ) { // read existing metadata int workingFormatVersion = reader.GetInt32( 0 ); string workingServerVersionString = reader.GetString( 1 ); DateTime workingLastModified = reader.GetInt64( 2 ).ToDateTime(); Logger.Log( LogType.SystemActivity, "Loading PlayerDB (format {0}, generated by {1}, last modified {2})", workingFormatVersion, workingServerVersionString, workingLastModified.ToCompactString() ); } else { // no metadata found - insert a row Logger.Log( LogType.Warning, "No existing metadata record found in the specified database." ); GenerateSchema( transaction ); } } } // load the rank mapping var databaseRankMapping = new Dictionary<int, Rank>(); using( MySqlCommand loadRankMappingCmd = new MySqlCommand( LoadRankMappingQuery, connection, transaction ) ) { using( MySqlDataReader reader = loadRankMappingCmd.ExecuteReader() ) { while( reader.Read() ) { int index = reader.GetInt32( 0 ); string rankName = reader.GetString( 1 ); Rank rank = Rank.Parse( rankName ); if( rank == null ) { rank = RankManager.DefaultRank; Logger.Log( LogType.Warning, "MySqlPlayerDBProvider: Unrecognized rank \"{0}\". Any reference to this rank will be replaced with \"{1}\".", rankName, rank.Name ); } databaseRankMapping.Add( index, rank ); } } } // check if multiple indices refer to the same rank var indicesGroupedByRank = databaseRankMapping.GroupBy( pair => pair.Value ); foreach( var indexGroup in indicesGroupedByRank.Where( group => group.Count() > 1 ) ) { Logger.Log( LogType.Warning, "MySqlPlayerDBProvider: Multiple incides ({0}) refer to the same rank ({1}) and will be merged.", indexGroup.Select( pair => pair.Key ).JoinToString(), indexGroup.Key.Name ); } // enumerate all rank IDs in the database var allRankIDs = new HashSet<int>(); using( MySqlCommand listRanksCmd = new MySqlCommand( ListRanksQuery, connection, transaction ) ) { using( MySqlDataReader reader = listRanksCmd.ExecuteReader() ) { while( reader.Read() ) { allRankIDs.Add( reader.GetInt32( 0 ) ); } } } using( MySqlCommand listPreviousRanksCmd = new MySqlCommand( ListPreviousRanksQuery, connection, transaction ) ) { using( MySqlDataReader reader = listPreviousRanksCmd.ExecuteReader() ) { while( reader.Read() ) { allRankIDs.Add( reader.GetInt32( 0 ) ); } } } // Replace any unknown rank indices with the default rank. var unknownRanks = allRankIDs.Except( databaseRankMapping.Keys ); if( unknownRanks.Count() > 0 ) { Logger.Log( LogType.Warning, "MySqlPlayerDBProvider: Following unrecognized rank indices will be replaced with the default rank ({0}): {1}", RankManager.DefaultRank.Name, unknownRanks.JoinToString() ); foreach( int unknownIndex in unknownRanks ) { databaseRankMapping.Add( unknownIndex, RankManager.DefaultRank ); } } // check if rank mappings are in sync rankMapping = RankManager.Ranks .OrderBy( rank => rank.Index ) .ToDictionary( rank => rank.Index ); if( !rankMapping.SequenceEqual( databaseRankMapping.OrderBy( pair => pair.Key ) ) ) { Logger.Log( LogType.Warning, "MySqlPlayerDBProvider: Updating database rank mapping..." ); RebuildRankMapping( databaseRankMapping, transaction ); } // done loading (phew) transaction.Commit(); } }
void BuildCachedVersionsList(List<FileRevision> versions) { using (var sw = File.CreateText(DataFileName)) { foreach (var fileGroup in versions.GroupBy(v => v.FileSpec)) { // get in ascending order var fileVersions = fileGroup.OrderBy(f => f.VssVersion).ToList(); var brokenVersions = new List<int>(); var notRetainedVersions = new List<int>(); var otherErrors = new Dictionary<int, string>(); if (IsShouldBePinned(fileGroup.Key)) { // reduce file versions to latest only fileVersions = fileVersions.Skip(fileVersions.Count - 1).ToList(); } foreach (var file in fileVersions) { var inf = _cache.GetFileInfo(file.FileSpec, file.VssVersion); if (inf == null) throw new ApplicationException(string.Format("No in cache, but should be: {0}@{1}", file.FileSpec, file.VssVersion)); if (inf.ContentPath != null) { if (brokenVersions.Count > 0 || notRetainedVersions.Count > 0 || otherErrors.Count > 0) { var commentPlus = string.Format("\nBalme for '{0}' can be incorrect, because:", file.FileSpec); if (brokenVersions.Count > 0) { commentPlus += "\n\tbroken vss versions: " + string.Join(", ", brokenVersions.Select(v => v.ToString(CultureInfo.InvariantCulture)).ToArray()); } if (notRetainedVersions.Count > 0) { commentPlus += "\n\tnot retained versions: " + string.Join(", ", notRetainedVersions.Select(v => v.ToString(CultureInfo.InvariantCulture)).ToArray()); } if (otherErrors.Count > 0) { foreach (var otherErrorsGroup in otherErrors.GroupBy(kvp => kvp.Value)) { var revs = otherErrorsGroup.Select(kvp => kvp.Key.ToString(CultureInfo.InvariantCulture)).ToArray(); commentPlus += string.Format("\n\tError in VSS versions {0}: '{1}'", string.Join(", ", revs), otherErrorsGroup.Key); } } file.Comment += commentPlus; } sw.WriteLine("Ver:{0} Spec:{1} Phys:{2} User:{3} At:{4} DT:{5} Comment:{6}", file.VssVersion, file.FileSpec, file.Physical, file.User, file.At.Ticks, file.At, file.Comment.Replace('\n', '\u0001') ); notRetainedVersions.Clear(); brokenVersions.Clear(); otherErrors.Clear(); } else if (inf.Notes == "not-retained") notRetainedVersions.Add(file.VssVersion); else if (inf.Notes == "broken-revision") brokenVersions.Add(file.VssVersion); else if (!string.IsNullOrWhiteSpace(inf.Notes)) otherErrors[file.VssVersion] = inf.Notes; } if (brokenVersions.Count > 0 || notRetainedVersions.Count > 0 || otherErrors.Count > 0) throw new ApplicationException(string.Format("Absent content for latest file version: {0}", fileGroup.Key)); } } }
IEnumerable<IGrouping<string, string>> OverrideWithInputs(IEnumerable<IGrouping<string, string>> parameters) { var overrides = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); if (Configuration != null) overrides.Add("Configuration", Configuration); if (Incremental) overrides.Add("Incremental", "True"); overrides.Add("OpenWrap-CurrentBuildVersion", _generatedVersion.ToString()); if (_sharedAssemblyInfoFile != null) overrides.Add("OpenWrap-SharedAssemblyInfoFile", _sharedAssemblyInfoFile.Path.FullPath); return overrides.GroupBy(x => x.Key, x => x.Value).Concat(_wildcards.Concat(parameters).Where(param => !overrides.ContainsKey(param.Key))); }
// entry, <minlevel, maxlevel> public static Dictionary<uint, Tuple<uint, uint>> GetLevels(Dictionary<WowGuid, Unit> units) { if (units.Count == 0) return null; var entries = units.GroupBy(unit => unit.Key.GetEntry()); var list = new Dictionary<uint, List<uint>>(); foreach (var pair in entries.SelectMany(entry => entry)) { if (list.ContainsKey(pair.Key.GetEntry())) list[pair.Key.GetEntry()].Add(pair.Value.Level.GetValueOrDefault(1)); else list.Add(pair.Key.GetEntry(), new List<uint> { pair.Value.Level.GetValueOrDefault(1) }); } var result = list.ToDictionary(pair => pair.Key, pair => Tuple.Create(pair.Value.Min(), pair.Value.Max())); return result.Count == 0 ? null : result; }
private void btnMoveHoldemTable_Click(object sender, EventArgs e) { var gameTableWindowList = new Dictionary<string, IntPtr>(); var childs = NativeMethodsHelper.GetAllWindows(); foreach (var handle in childs) { var sb = new StringBuilder(500); var length = NativeMethodsHelper.GetWindowText((IntPtr)handle, sb, 500); if (length <= 0) continue; var title = sb.ToString(); var pattern = @"\[(?<NickName>.*)\]\[(?<TableId>.*)\]\[(?<JumpEntryId>.*)\]"; foreach (Match m in Regex.Matches(title, pattern)) { if (m.Success == false) continue; ; var nickName = m.Groups["NickName"]; var tableId = m.Groups["TableId"]; var jumpEntryId = m.Groups["JumpEntryId"]; // JumpEntryId -> NickName 순으로 정렬 gameTableWindowList.Add(string.Format("{0}.{1}", tableId, nickName), (IntPtr)handle); } } // 정렬 if (gameTableWindowList.Count == 0) return; // 위치 정렬 var tableIdList = gameTableWindowList.GroupBy(g => g.Key.Split('.')[0]).ToList().OrderBy(list => list.Key).ToList(); if (tableIdList.Count > 0) { int yLocation = 0; foreach (var tableIdKV in tableIdList) { var tableId = tableIdKV.Key; var lists = gameTableWindowList.Where(g => g.Key.Split('.')[0] == tableId).OrderBy(g => g.Key).Select(g => g.Value).ToList(); this.MoveGameTable(tableId, lists, yLocation++); } } }
private void WriteETWActor(StringBuilder sb, XElement provider, Dictionary<Tuple<int, int, string>, XElement> events) { sb.AppendFormat("public autostart actor actor_{0}", provider.Attribute("guid").Value.Replace("-", "").TrimStart('{').TrimEnd('}')); sb.AppendLine(); sb.AppendLine("\t(EtwEvent.Node node)"); sb.AppendLine("{"); sb.AppendLine("\tprocess node accepts m:EtwProviderMsgEx"); sb.AppendFormat("\t\twhere (m.EventRecord.Header.ProviderId == {0} )", provider.Attribute("guid").Value); sb.AppendLine(); sb.AppendLine("\t{"); sb.AppendLine("\t\tswitch(m.EventRecord.Header.Descriptor.Version)"); sb.AppendLine("\t\t{"); foreach (var etwEventGroup in events.GroupBy(p => p.Key.Item2)) { sb.AppendFormat("\t\t\t//EventVersion {0}", etwEventGroup.Key); sb.AppendLine(); sb.AppendFormat("\t\t\tcase $ {0} =>", etwEventGroup.Key); sb.AppendLine(); sb.AppendLine("\t\t\t\tswitch(m.EventRecord.Header.Descriptor.Id)"); sb.AppendLine("\t\t\t\t{"); foreach (var etwEvent in etwEventGroup) { sb.AppendFormat("\t\t\t\t\t//{0} =>", GetEventName(etwEvent.Key.Item3, etwEvent.Key.Item2)); sb.AppendLine(); sb.AppendFormat("\t\t\t\t\tcase $ {0} =>", etwEvent.Key.Item1); sb.AppendLine(); sb.AppendLine("\t\t\t\t\t\tswitch(m.Payload)"); sb.AppendLine("\t\t\t\t\t\t{"); sb.AppendFormat("\t\t\t\t\t\t\tcase decodedMsg: {0} from BinaryDecoder <{0}> =>", GetEventName(etwEvent.Key.Item3, etwEvent.Key.Item2)); sb.AppendLine(); sb.AppendLine("\t\t\t\t\t\t\t{"); sb.AppendLine("\t\t\t\t\t\t\t\tdecodedMsg.EtwKeywords = Keywords.Decode(m.EventRecord.Header.Descriptor.Keywords);"); sb.AppendLine("\t\t\t\t\t\t\t\tdecodedMsg.EventId = m.EventRecord.Header.Descriptor.Id;"); sb.AppendLine("\t\t\t\t\t\t\t\tdecodedMsg.ActivityId = m.EventRecord.Header.ActivityId;"); sb.AppendLine(); if (string.Equals(etwEvent.Value?.Attribute("opcode")?.Value, "win:Start")) { sb.AppendLine("\t\t\t\t\t\t\t\tint count = m.ExtendedData.Count;"); sb.AppendLine("\t\t\t\t\t\t\t\tif (count > 0)"); sb.AppendLine("\t\t\t\t\t\t\t\t{"); sb.AppendLine("\t\t\t\t\t\t\t\t\tarray <EventHeaderExtendedDataItem> items = m.ExtendedData;"); sb.AppendLine("\t\t\t\t\t\t\t\t\tEVENT_HEADER_EXT_TYPE_RELATED_ACTIVITYID dataItem = items[0].DataItem as EVENT_HEADER_EXT_TYPE_RELATED_ACTIVITYID;"); sb.AppendLine(); sb.AppendLine("\t\t\t\t\t\t\t\t\tif (dataItem != null)"); sb.AppendLine("\t\t\t\t\t\t\t\t\t\tdecodedMsg.RelatedActivityId = dataItem.RelatedActivityId;"); sb.AppendLine(); sb.AppendLine("\t\t\t\t\t\t\t\t\tdecodedMsg.ActivityTree = Facton_ActivityTree_Utils.GetActivityTree(decodedMsg.ActivityId, decodedMsg.RelatedActivityId, m.EventRecord.Header.ProcessId, m.EventRecord.Header.ThreadId);"); sb.AppendLine("\t\t\t\t\t\t\t\t}"); sb.AppendLine(); } else { if (etwEvent.Key.Item1 != 0 && etwEvent.Key.Item1 != 65534) { sb.AppendLine("\t\t\t\t\t\t\t\tdecodedMsg.ActivityTree = Facton_ActivityTree_Utils.GetActivityTree(decodedMsg.ActivityId, m.EventRecord.Header.ProcessId, m.EventRecord.Header.ThreadId);"); } } sb.AppendFormat("\t\t\t\t\t\t\t\tep_{0} ep = endpoint ep_{0};", provider.Attribute("name").Value.Replace('-', '_')); sb.AppendLine(); sb.AppendLine("\t\t\t\t\t\t\t\tdispatch ep accepts decodedMsg;"); sb.AppendLine("\t\t\t\t\t\t\t}"); sb.AppendLine("\t\t\t\t\t\t\tdefault =>"); sb.AppendFormat("\t\t\t\t\t\t\t\tThrowDecodingException(\"{0}\", \"{1}\");", provider.Attribute("name").Value, GetEventName(etwEvent.Key.Item3, etwEvent.Key.Item2)); sb.AppendLine(); sb.AppendLine("\t\t\t\t\t\t}"); sb.AppendLine(); } sb.AppendLine("\t\t\t\t}"); sb.AppendLine(); } sb.AppendLine("\t\t}"); sb.AppendLine("\t}"); sb.AppendLine("}"); sb.AppendLine(); }
public async Task<List<string>> IssueInventoryAsync(Dictionary<string, IEnumerable<ImportInvetoryIssueToSalesman>> stockLines) { return await Task.Run(() => { var errors = new List<string>(); Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Starting inventory issue to salesmen...")); var applicationId = _configService.Load().CostCentreApplicationId; foreach (var stockLine in stockLines.GroupBy(n => n.Key)) //key=>salesmancode { InventoryTransferNote inventoryTransferDoc = null; InventoryAdjustmentNote inventoryAdjustmentNote = null; var salsmancode = stockLine.Key; var distributor = _repositoryHelpers.MapDistributor( _ctx.tblCostCentre.FirstOrDefault( n => n.CostCentreType == (int) CostCentreType.Distributor)); Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Loading Salesman....")); var transferTo = _costCentreRepository.GetByCode(salsmancode,CostCentreType.DistributorSalesman, true); var salesmanUser = _userRepository.GetByCostCentre(distributor.Id).FirstOrDefault(); if (distributor != null && transferTo != null && salesmanUser != null) { #region create inventory adjustment note inventoryAdjustmentNote = _inventoryAdjustmentNoteFactory.Create(distributor, applicationId, distributor, salesmanUser, "", InventoryAdjustmentNoteType .Available, Guid.Empty); Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("AInventory adjustment note created for distribuor=>{0}",distributor.CostCentreCode)); #endregion #region create inventory transfer note inventoryTransferDoc = _inventoryTransferNoteFactory.Create(distributor, applicationId, salesmanUser, transferTo, distributor, ""); Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("AInventory transfer note created to salesman=>{0}", transferTo.CostCentreCode)); #endregion foreach (var stockitem in stockLine.SelectMany(n => n.Value.ToList())) { string msg = string.Empty; try { var product = _ctx.tblProduct.FirstOrDefault( p => p.ProductCode != null && p.ProductCode == stockitem.ProductCode); if (product != null) { var lineitem = _inventoryAdjustmentNoteFactory.CreateLineItem( stockitem. ApprovedQuantity, product.id, 0, 0, "Inventory Adjustment"); inventoryAdjustmentNote.AddLineItem(lineitem); InventoryTransferNoteLineItem itnLineitem = _inventoryTransferNoteFactory.CreateLineItem( product.id, stockitem. ApprovedQuantity, 0, 0, ""); if (itnLineitem != null) inventoryTransferDoc.AddLineItem(itnLineitem); if (msg != "") { FileUtility.LogError(msg); errors.Add(msg); } } else { var error = string.Format("{0} doest exist=>", stockitem.ProductCode); if (!errors.Any(p => p.Contains(error))) errors.Add(error); } } catch (Exception ex) { Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Error occured while adjusting inventory..See error logs")); FileUtility.LogError(ex.Message); } } Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Confirming inventory adjustment note for distributr=>{0}", distributor.CostCentreCode)); inventoryAdjustmentNote.Confirm(); _inventoryAdjustmentNoteWfManager.SubmitChanges(inventoryAdjustmentNote); Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Inventory adjustment note CONFIRMED for distributr=>{0}", distributor.CostCentreCode)); Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Confirming inventory transfer to salesman=>{0}", transferTo.CostCentreCode)); inventoryTransferDoc.Confirm(); _inventoryTransferNoteWfManager.SubmitChanges(inventoryTransferDoc); Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Inventory transfer CONFIRMED to salesman=>{0}", transferTo.CostCentreCode)); } else { FileUtility.LogError( string.Format("Inventory issue failed for salesman=>{0}", salsmancode)); if (distributor == null) { FileUtility.LogError( string.Format("Distributor is null=> doest exist")); Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("Distributor is null=> doest exist")); } if (transferTo == null) { FileUtility.LogError( string.Format("salesman is with code=>{0} doest exist", salsmancode)); Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("salesman is with code=>{0} doest exist", salsmancode)); } if (salesmanUser == null) { Messenger.Default.Send(DateTime.Now.ToString("hh:mm:ss") + string.Format("user is null=> doest exist")); FileUtility.LogError(string.Format("user is null=> doest exist")); } FileUtility.LogError("----------------------------------------------"); } } return errors; }); }
private IEnumerable<NuGetFramework> GetNearestPCLtoPCL(NuGetFramework framework, IEnumerable<NuGetFramework> reduced) { // Compare each framework in the target framework individually // against the list of possible PCLs. This effectively lets // each sub-framework vote on which PCL is nearest. var subFrameworks = ExplodePortableFramework(framework); // reduce the sub frameworks - this would only have an effect if the PCL is // poorly formed and contains duplicates such as portable-win8+win81 subFrameworks = Reduce(subFrameworks); // Find all frameworks in all PCLs var pclToFrameworks = ExplodePortableFrameworks(reduced); var allPclFrameworks = pclToFrameworks.Values.SelectMany(f => f).Distinct(_fullComparer); var scores = new Dictionary<NuGetFramework, int>(NuGetFramework.Comparer); // find the nearest PCL for each framework foreach (var sub in subFrameworks) { Debug.Assert(!sub.IsPCL, "a PCL returned a PCL as its profile framework"); // from all possible frameworks, find the best match var nearestForSub = GetNearest(sub, allPclFrameworks); // +1 each framework containing the best match foreach (var pair in pclToFrameworks) { if (pair.Value.Contains(nearestForSub, _fullComparer)) { if (!scores.ContainsKey(pair.Key)) { scores.Add(pair.Key, 1); } else { scores[pair.Key]++; } } } } // take the highest vote count, this will be at least one reduced = scores.GroupBy(pair => pair.Value).OrderByDescending(g => g.Key).First().Select(e => e.Key); return reduced; }
static TypeMapper() { typeMapping = new Dictionary<string, Type>(); typeMapping.Add("bigint", typeof(long)); typeMapping.Add("int", typeof(int)); typeMapping.Add("smallint", typeof(short)); typeMapping.Add("tinyint", typeof(byte)); typeMapping.Add("decimal", typeof(decimal)); typeMapping.Add("numeric", typeof(decimal)); typeMapping.Add("money", typeof(decimal)); typeMapping.Add("smallmoney", typeof(decimal)); typeMapping.Add("bit", typeof(bool)); typeMapping.Add("float", typeof(float)); typeMapping.Add("real", typeof(double)); typeMapping.Add("datetime2", typeof(DateTime)); typeMapping.Add("datetime", typeof(DateTime)); typeMapping.Add("smalldatetime", typeof(DateTime)); typeMapping.Add("date", typeof(DateTime)); typeMapping.Add("datetimeoffset", typeof(DateTime)); typeMapping.Add("time", typeof(DateTime)); typeMapping.Add("timestamp", typeof(DateTime)); typeMapping.Add("nvarchar", typeof(string)); typeMapping.Add("char", typeof(string)); typeMapping.Add("varchar", typeof(string)); typeMapping.Add("text", typeof(string)); typeMapping.Add("nchar", typeof(string)); typeMapping.Add("ntext", typeof(string)); typeMapping.Add("varbinary", typeof(byte[])); typeMapping.Add("binary", typeof(byte[])); typeMapping.Add("image", typeof(byte[])); typeMapping.Add("uniqueidentifier", typeof(Guid)); reverseTypeMapping = typeMapping .GroupBy(kv => kv.Value, kv => kv.Key) .ToDictionary(g => g.Key, g => g.First()); reverseTypeMapping.Add(typeof(char[]), "nchar"); reverseTypeMapping.Add(typeof(int?), "int"); reverseTypeMapping.Add(typeof(uint), "int"); reverseTypeMapping.Add(typeof(uint?), "int"); reverseTypeMapping.Add(typeof(long?), "bigint"); reverseTypeMapping.Add(typeof(ulong), "bigint"); reverseTypeMapping.Add(typeof(ulong?), "bigint"); reverseTypeMapping.Add(typeof(short?), "smallint"); reverseTypeMapping.Add(typeof(ushort), "smallint"); reverseTypeMapping.Add(typeof(ushort?), "smallint"); reverseTypeMapping.Add(typeof(byte?), "tinyint"); reverseTypeMapping.Add(typeof(sbyte), "tinyint"); reverseTypeMapping.Add(typeof(sbyte?), "tinyint"); reverseTypeMapping.Add(typeof(char), "tinyint"); reverseTypeMapping.Add(typeof(char?), "tinyint"); reverseTypeMapping.Add(typeof(decimal?), "decimal"); reverseTypeMapping.Add(typeof(bool?), "bit"); reverseTypeMapping.Add(typeof(float?), "float"); reverseTypeMapping.Add(typeof(double?), "real"); reverseTypeMapping.Add(typeof(DateTime?), "datetime2"); reverseTypeMapping.Add(typeof(Guid?), "uniqueidentifier"); }
public override HashSet<string[]> ReduceNames(Dictionary<string, int> nodeNames) { var hash = new HashFunction8(); var groups = nodeNames.GroupBy(n => hash.HashName(n.Key)).Select(g => new Group { Hash = g.Key, Instances = g.ToList(), Words = hash.HashName(g.First().Key).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).ToArray() }).OrderBy(g => g.Instances.Count).ToArray(); var numbers = groups.Where(g => g.Hash.All(c => '0' <= c && c <= '9')).Select(g => Convert.ToInt32(g.Hash)); groups = groups.Where(g => !g.Hash.All(c => '0' <= c && c <= '9')).ToArray(); { var wordFrequency = new Dictionary<string, int>(); var wordCount = 0; foreach (var group in groups) { foreach (var word in group.Words) { if (!wordFrequency.ContainsKey(word)) { wordFrequency[word] = 0; } wordFrequency[word] += group.Instances.Count; wordCount += group.Instances.Count; } } WordScore = wordFrequency.ToDictionary(k => k.Key, k => wordCount/(1.0*k.Value)); } Logger.Log(string.Format("The {0} groups have an average size {1}", groups.Length, groups.Average(g => g.Instances.Count))); bool reduced; int pass = 0; do { #if DEBUG Filename = "Reductions_3_" + pass + ".txt"; lock (Filename) { File.Delete(Filename); } #endif var reductions = Logger.Batch(groups.Length - 1, i => ReduceName(groups, i, 25), "reduced this pass") .Where(p => p != null).OrderBy(p => p.Item1).ToList(); reduced = reductions.Count > 0; foreach (var reduction in reductions) { groups[reduction.Item2].Instances.AddRange(groups[reduction.Item1].Instances); groups[reduction.Item1] = null; } groups = groups.Where(g => g != null).OrderBy(g => g.Instances.Count()).ToArray(); #if DEBUG lock (Filename) { File.AppendAllText(Filename, ("~~~ " + reductions.Count + " ~~~ reductions were made in this pass" + "\n")); } #endif Logger.Log(reductions.Count + " reductions were made"); Logger.Log(string.Format("The {0} groups have an average size {1}", groups.Length, groups.Average(g => g.Instances.Count()))); pass++; } while (reduced); var numberNameGroups = numbers.OrderBy(n => n).Select(n => new[] {n.ToString()}); var textNameGroups = groups.Select(g => g.Instances.Select(inst => inst.Key).Distinct().ToArray()); return new HashSet<string[]>(numberNameGroups.Concat(textNameGroups)); }
private void AverageHitsPerSecondPerHourSectionOutput(Dictionary<DateTime, int> hitsPerSecond) { Console.WriteLine(); OutputHeading("Average hits per second, by hour"); var groupedHourlyList = hitsPerSecond.GroupBy(u => u.Key.Hour) .Select(grp => new { GroupID = grp.Key, subList = grp.ToList() }) .ToList(); foreach (var hourlyHits in groupedHourlyList) { Console.WriteLine("{0,2:D2}-{1,2:D2} : {2:0}", hourlyHits.GroupID, hourlyHits.GroupID + 1, hourlyHits.subList.Average(c => c.Value)); } }
IEnumerable<IGrouping<string, string>> OverrideWithInputs(IEnumerable<IGrouping<string,string>> parameters) { var overrides = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); if (Configuration != null) overrides.Add("Configuration", Configuration); if (Incremental) overrides.Add("Incremental", "True"); return overrides.GroupBy(x => x.Key, x => x.Value).Concat(parameters.Where(param => !overrides.ContainsKey(param.Key))); }
public void displayWinner() { Dictionary<PairParticipant, double> dict = new Dictionary<PairParticipant, double>(); foreach (Сompetition competition in competitions) { var CompetitionProtocols = this.protocols.FindAll(protocol => protocol.competition == competition); var pairsInCompetition = CompetitionProtocols.GroupBy(protocol => protocol.pair); var data = pairsInCompetition.Select( g => new { Pair = g.Key, Score = g.Sum(pair => pair.score) * competition.coefficient } ); foreach (var datum in data) { if (dict.ContainsKey(datum.Pair)) { dict[datum.Pair] += datum.Score; } else { dict.Add(datum.Pair, datum.Score); } } } var result = dict.GroupBy(x => x.Key).Select( g => new { Pair = g.Key, Score = g.Sum(x => x.Value) } ).OrderBy(x => x.Score); System.Console.Write("Number of pairs is: "); System.Console.WriteLine(result.Count()); System.Console.WriteLine("Winner is: "); result.First().Pair.display(); System.Console.WriteLine(); System.Console.Write("Score is: "); System.Console.WriteLine(result.First().Score); }
private static async Task PermuteSingleDiagonal(Dictionary<FaceType, RelativePosition> relations, CubeConfiguration<FaceColour> configuration, ICollection<IRotation> solution) { var groups = relations.GroupBy(kvp => kvp.Value).ToList(); var oppositeRelation = groups.FirstOrDefault(group => group.Key == RelativePosition.Opposite); if (oppositeRelation != null) { switch (oppositeRelation.Count()) { case 2: case 4: await CommonActions.ApplyAndAddRotation(Rotations.UpperClockwise, solution, configuration).ConfigureAwait(false); relations = CrossRelativePositions(configuration); await PermuteSingleDiagonal(relations, configuration, solution).ConfigureAwait(false); return; } } // TODO: TIDY var sameRelation = groups.FirstOrDefault(group => group.Key == RelativePosition.Same); if (sameRelation == null) return; if (sameRelation.Count() > 1) { await CommonActions.ApplyAndAddRotation(Rotations.UpperClockwise, solution, configuration).ConfigureAwait(false); relations = CrossRelativePositions(configuration); await PermuteSingleDiagonal(relations, configuration, solution).ConfigureAwait(false); return; } var faceType = sameRelation.First().Key; var faceColour = configuration.Faces[faceType].TopCentre(); var cubeRotation = await CommonActions.PositionOnFront(configuration, faceColour).ConfigureAwait(false); if (cubeRotation != null) solution.Add(cubeRotation); if (oppositeRelation.First().Key == FaceRules.FaceAtRelativePositionTo(faceType, RelativePosition.Right)) { await PermuteClockwise(configuration, solution).ConfigureAwait(false); } else { await PermuteAntiClockwise(configuration, solution).ConfigureAwait(false); } }
static void Main(string[] args) { try { NameValueCollection appSettings = System.Configuration.ConfigurationManager.AppSettings; Dictionary<string, List<string>> uprnDictionaryResidual = new Dictionary<string, List<string>>(); Boolean overwriteResidual = true; // Open the geodatabase for residual. Geodatabase geodatabaseResidual = Geodatabase.Open(appSettings["residualGeoDB"]); StringBuilder residualCsv = new StringBuilder(); string sqlStatementResidual = "SELECT * FROM " + appSettings["residualTableName"]; foreach (Row attrQueryRow in geodatabaseResidual.ExecuteSQL(sqlStatementResidual)) { string uprn = ""; string day = ""; string route = ""; if (!attrQueryRow.IsNull("LLPG_UPRN_DOUBLE")) { uprn = attrQueryRow.GetDouble("LLPG_UPRN_DOUBLE").ToString(); } else { overwriteResidual = false; } if (!attrQueryRow.IsNull("REFUSE_DAY")) { day = attrQueryRow.GetString("REFUSE_DAY"); } else { //overwriteResidual = false; } if (!attrQueryRow.IsNull("Route")) { route = attrQueryRow.GetString("Route"); } else { //overwriteResidual = false; } //Matthew Steer added this on: 29.9.16 string gullBag = ""; if (!attrQueryRow.IsNull("Gull_Bag")) gullBag = attrQueryRow.GetString("Gull_Bag"); string newLine = string.Format("{0},{1},{2},{3}{4}", uprn, day, route, gullBag, Environment.NewLine); residualCsv.Append(newLine); // Additional fields for assisted string address = ""; string postcode = ""; string refuseRound = ""; string refuseSequence = ""; string llpgName = ""; string llpgNo = ""; string llpgStreet = ""; string llpgTown = ""; string llpgPostTown = ""; string llpgPostcode = ""; if (!attrQueryRow.IsNull("Address")) address = attrQueryRow.GetString("Address"); if (!attrQueryRow.IsNull("Postal_Code")) postcode = attrQueryRow.GetString("Postal_Code"); if (!attrQueryRow.IsNull("Region")) refuseRound = attrQueryRow.GetString("Region"); if (!attrQueryRow.IsNull("Sequence")) refuseSequence = attrQueryRow.GetInteger("Sequence").ToString(); if (!attrQueryRow.IsNull("LLPG_NAME")) llpgName = attrQueryRow.GetString("LLPG_NAME"); if (!attrQueryRow.IsNull("LLPG_NO")) llpgNo = attrQueryRow.GetString("LLPG_NO"); if (!attrQueryRow.IsNull("LLPG_STREET")) llpgStreet = attrQueryRow.GetString("LLPG_STREET"); if (!attrQueryRow.IsNull("LLPG_TOWN")) llpgTown = attrQueryRow.GetString("LLPG_TOWN"); if (!attrQueryRow.IsNull("LLPG_POSTTOWN")) llpgPostTown = attrQueryRow.GetString("LLPG_POSTTOWN"); if (!attrQueryRow.IsNull("LLPG_POSTCODE")) llpgPostcode = attrQueryRow.GetString("LLPG_POSTCODE"); //And add the relevant data to our dictionary if (!uprnDictionaryResidual.ContainsKey(uprn)) { uprnDictionaryResidual.Add(uprn, new List<string> { route, day, address, postcode, refuseRound, refuseSequence, llpgName, llpgNo, llpgStreet, llpgTown, llpgPostTown, llpgPostcode, gullBag }); } } geodatabaseResidual.Close(); if (overwriteResidual) File.WriteAllText(appSettings["residualCsv"], residualCsv.ToString()); Dictionary<string, List<string>> uprnDictionaryOrganic = new Dictionary<string, List<string>>(); Boolean overwriteOrganic = true; // Open the geodatabase for organic. Geodatabase geodatabaseOrganic = Geodatabase.Open(appSettings["organicGeoDB"]); StringBuilder organicCsv = new StringBuilder(); string sqlStatementOrganic = "SELECT LLPG_UPRN_DOUBLE, Organic_Collection, Route FROM " + appSettings["organicTableName"]; foreach (Row attrQueryRow in geodatabaseOrganic.ExecuteSQL(sqlStatementOrganic)) { string uprn = ""; string route = ""; string day = ""; if (!attrQueryRow.IsNull("LLPG_UPRN_DOUBLE")) { uprn = attrQueryRow.GetDouble("LLPG_UPRN_DOUBLE").ToString(); } else { //overwriteOrganic = false; } if (!attrQueryRow.IsNull("Organic_Collection")) { day = attrQueryRow.GetString("Organic_Collection"); } else { //overwriteOrganic = false; } if (!attrQueryRow.IsNull("Route")) { route = attrQueryRow.GetString("Route"); } else { //overwriteOrganic = false; } string newLine = string.Format("{0},{1},{2}{3}", uprn, day, route, Environment.NewLine); organicCsv.Append(newLine); // Additional fields for assisted string address = ""; string postcode = ""; string organicRound = ""; string organicSequence = ""; string llpgName = ""; string llpgNo = ""; string llpgStreet = ""; string llpgTown = ""; string llpgPostTown = ""; string llpgPostcode = ""; string week = ""; if (!attrQueryRow.IsNull("Address")) address = attrQueryRow.GetString("Address"); if (!attrQueryRow.IsNull("Postal_Code")) postcode = attrQueryRow.GetString("Postal_Code"); if (!attrQueryRow.IsNull("Region")) organicRound = attrQueryRow.GetString("Region"); if (!attrQueryRow.IsNull("Sequence")) organicSequence = attrQueryRow.GetInteger("Sequence").ToString(); if (!attrQueryRow.IsNull("LLPG_NAME")) llpgName = attrQueryRow.GetString("LLPG_NAME"); if (!attrQueryRow.IsNull("LLPG_NO")) llpgNo = attrQueryRow.GetString("LLPG_NO"); if (!attrQueryRow.IsNull("LLPG_STREET")) llpgStreet = attrQueryRow.GetString("LLPG_STREET"); if (!attrQueryRow.IsNull("LLPG_TOWN")) llpgTown = attrQueryRow.GetString("LLPG_TOWN"); if (!attrQueryRow.IsNull("LLPG_POSTTOWN")) llpgPostTown = attrQueryRow.GetString("LLPG_POSTTOWN"); if (!attrQueryRow.IsNull("LLPG_POSTCODE")) llpgPostcode = attrQueryRow.GetString("LLPG_POSTCODE"); if (!attrQueryRow.IsNull("Collection")) week = attrQueryRow.GetString("Collection"); // And add the relevant data to our dictionary if (!uprnDictionaryOrganic.ContainsKey(uprn)) { uprnDictionaryOrganic.Add(uprn, new List<string> { route, day, address, postcode, organicRound, organicSequence, week, llpgName, llpgNo, llpgStreet, llpgTown, llpgPostTown, llpgPostcode }); } } geodatabaseOrganic.Close(); if (overwriteOrganic) File.WriteAllText(appSettings["organicCsv"], organicCsv.ToString()); Dictionary<string, List<string>> uprnDictionaryRecycling = new Dictionary<string, List<string>>(); Boolean overwriteRecycling = true; // Open the geodatabase for recyling. Geodatabase geodatabaseRecycling = Geodatabase.Open(appSettings["recyclingGeoDB"]); StringBuilder recylingCsv = new StringBuilder(); string sqlStatementRecyling = "SELECT LLPG_UPRN_DOUBLE, Recycle_Collection, Route , Green_Sack FROM " + appSettings["recyclingTableName"]; foreach (Row attrQueryRow in geodatabaseRecycling.ExecuteSQL(sqlStatementRecyling)) { string uprn = ""; string day = ""; string route = ""; string greensack = ""; if (!attrQueryRow.IsNull("LLPG_UPRN_DOUBLE")) { uprn = attrQueryRow.GetDouble("LLPG_UPRN_DOUBLE").ToString(); } else { //overwriteRecycling = false; } if (!attrQueryRow.IsNull("Recycle_Collection")) { day = attrQueryRow.GetString("Recycle_Collection"); } else { //overwriteRecycling = false; } if (!attrQueryRow.IsNull("Route")) { route = attrQueryRow.GetString("Route"); } else { //overwriteRecycling = false; } if (!attrQueryRow.IsNull("Green_Sack")) { greensack = attrQueryRow.GetString("Green_Sack"); } else { //overwriteRecycling = false; } string newLine = string.Format("{0},{1},{2},{3}{4}", uprn, day, route, greensack, Environment.NewLine); recylingCsv.Append(newLine); // Additional fields for assisted string address = ""; string postcode = ""; string recyclingRound = ""; string recyclingSequence = ""; string llpgName = ""; string llpgNo = ""; string llpgStreet = ""; string llpgTown = ""; string llpgPostTown = ""; string llpgPostcode = ""; string llpgLocality = ""; if (!attrQueryRow.IsNull("Address")) address = attrQueryRow.GetString("Address"); if (!attrQueryRow.IsNull("Postal_Code")) postcode = attrQueryRow.GetString("Postal_Code"); if (!attrQueryRow.IsNull("Region")) recyclingRound = attrQueryRow.GetString("Region"); if (!attrQueryRow.IsNull("Sequence")) recyclingSequence = attrQueryRow.GetInteger("Sequence").ToString(); if (!attrQueryRow.IsNull("LLPG_NAME")) llpgName = attrQueryRow.GetString("LLPG_NAME"); if (!attrQueryRow.IsNull("LLPG_NO")) llpgNo = attrQueryRow.GetString("LLPG_NO"); if (!attrQueryRow.IsNull("LLPG_STREET")) llpgStreet = attrQueryRow.GetString("LLPG_STREET"); if (!attrQueryRow.IsNull("LLPG_TOWN")) llpgTown = attrQueryRow.GetString("LLPG_TOWN"); if (!attrQueryRow.IsNull("LLPG_POSTTOWN")) llpgPostTown = attrQueryRow.GetString("LLPG_POSTTOWN"); if (!attrQueryRow.IsNull("LLPG_POSTCODE")) llpgPostcode = attrQueryRow.GetString("LLPG_POSTCODE"); //if (!attrQueryRow.IsNull("LLPG_LOCALITY")) llpgLocality = attrQueryRow.GetString("LLPG_LOCALITY"); // And add the relevant data to our dictionary if (!uprnDictionaryRecycling.ContainsKey(uprn)) { uprnDictionaryRecycling.Add(uprn, new List<string> { route, day, address, postcode, recyclingRound, recyclingSequence, llpgName, llpgNo, llpgStreet, llpgTown, llpgPostTown, llpgPostcode, llpgLocality }); } } geodatabaseRecycling.Close(); if (overwriteRecycling) File.WriteAllText(appSettings["recyclingCsv"], recylingCsv.ToString()); // For recycling we also generate a set of route participation monitor sheets for importing // firstly create a set of dictionaries grouped by route var recyclingDictionaries = uprnDictionaryRecycling.GroupBy(pair => pair.Value[4]) .ToDictionary(gr => gr.Key, gr => gr.ToDictionary(item => item.Key, item => item.Value)); string recyclingRoutesHeaderLine = string.Format("{0}{1}", "LLPG_NAME, LLPG_NO, LLPG_STREET, LLPG_LOCALITY, LLPG_TOWN, LLPG_POSTTOWN, LLPG_POSTCODE, Recycle_collection, Recycling_Round, Service_Location_RECYCLING_Sequence", Environment.NewLine); foreach (var route in recyclingDictionaries) { StringBuilder mondayCsv = new StringBuilder(); mondayCsv.Append(recyclingRoutesHeaderLine); StringBuilder tuesdayCsv = new StringBuilder(); tuesdayCsv.Append(recyclingRoutesHeaderLine); StringBuilder wednesdayCsv = new StringBuilder(); wednesdayCsv.Append(recyclingRoutesHeaderLine); StringBuilder thursdayCsv = new StringBuilder(); thursdayCsv.Append(recyclingRoutesHeaderLine); StringBuilder fridayCsv = new StringBuilder(); fridayCsv.Append(recyclingRoutesHeaderLine); Boolean mondayRoute = false; Boolean tuesdayRoute = false; Boolean wednesdayRoute = false; Boolean thursdayRoute = false; Boolean fridayRoute = false; // Each route is a set of dictionaries foreach (var item in route.Value) { string llpgName = "\"" + item.Value[6] + "\""; string llpgNo = item.Value[7]; string llpgStreet = item.Value[8]; string llpgLocality = item.Value[12]; string llpgTown = item.Value[9]; string llpgPostTown = item.Value[10]; string llpgPostCode = item.Value[11]; string recycycleCollection = item.Value[1]; string recycleRound = item.Value[4]; string recycleSequence = item.Value[5]; string newLine = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}{10}", llpgName, llpgNo, llpgStreet, llpgLocality, llpgTown, llpgPostTown, llpgPostCode, recycycleCollection, recycleRound, recycleSequence, Environment.NewLine); switch (item.Value[1]) { case "Monday": mondayCsv.Append(newLine); mondayRoute = true; break; case "Tuesday": tuesdayCsv.Append(newLine); tuesdayRoute = true; break; case "Wednesday": wednesdayCsv.Append(newLine); wednesdayRoute = true; break; case "Thursday": thursdayCsv.Append(newLine); thursdayRoute = true; break; case "Friday": fridayCsv.Append(newLine); fridayRoute = true; break; } } if (mondayRoute) File.WriteAllText(appSettings["recyclingRoutesCsvPath"] + route.Key + "_Monday.csv", mondayCsv.ToString()); if (tuesdayRoute) File.WriteAllText(appSettings["recyclingRoutesCsvPath"] + route.Key + "_Tuesday.csv", tuesdayCsv.ToString()); if (wednesdayRoute) File.WriteAllText(appSettings["recyclingRoutesCsvPath"] + route.Key + "_Wednesday.csv", wednesdayCsv.ToString()); if (thursdayRoute) File.WriteAllText(appSettings["recyclingRoutesCsvPath"] + route.Key + "_Thursday.csv", thursdayCsv.ToString()); if (fridayRoute) File.WriteAllText(appSettings["recyclingRoutesCsvPath"] + route.Key + "_Friday.csv", fridayCsv.ToString()); } // Also need to do an output for the assisted collections db // this will be from each of the databases, into a single file,taken from the dictionaries we've built up. // The table holds the data for each UPRN. // The fields are: UPRN as number, Address, Postal_Code, Organic_Day, Organic_Route, Oroutea, Organics_Round, Organic_Week, Service_Location_ORGANIC_Sequence, Recycle_collection, Recycle_route, Recycling_Round, Service_Location_RECYCLING_Sequence, Residual_Collection, Residual_Route, Refuse_Round, Service_Location_REFUSE_Sequence, LLPG_NAME, LLPG_NO, LLPG_STREET, LLPG_LOCALITY, LLPG_TOWN, LLPG_POSTTOWN, LLPG_POSTCODE StringBuilder uprnCsv = new StringBuilder(); char[] charsToTrim = { 'a', 'b', 'A', 'B' }; string headerLine = string.Format("{0}{1}", "UPRN as number, Address, Postal_Code, Organic_Day, Organic_Route, Oroutea, Organics_Round, Organic_Week, Service_Location_ORGANIC_Sequence, Recycle_collection, Recycle_route, Recycling_Round, Service_Location_RECYCLING_Sequence, Residual_Collection, Residual_Route, Refuse_Round, Service_Location_REFUSE_Sequence, LLPG_NAME, LLPG_NO, LLPG_STREET, LLPG_LOCALITY, LLPG_TOWN, LLPG_POSTTOWN, LLPG_POSTCODE, Gull_Bag", Environment.NewLine); uprnCsv.Append(headerLine); foreach (var val in uprnDictionaryResidual) { string uprn = val.Key; string address = "\"" + val.Value[2] + "\""; string postcode = val.Value[3]; string organicDay = ""; string organicRoute = ""; string oRoutea = ""; string organicsRoute = ""; string organicWeek = ""; string serviceLocationOrganicSequence = ""; if (uprnDictionaryOrganic.ContainsKey(val.Key) && uprnDictionaryOrganic[val.Key][1].Split(' ') != null) organicDay = uprnDictionaryOrganic[val.Key][1].Split(' ')[0]; if (uprnDictionaryOrganic.ContainsKey(val.Key)) organicRoute = uprnDictionaryOrganic[val.Key][0]; if (uprnDictionaryOrganic.ContainsKey(val.Key) && uprnDictionaryOrganic[val.Key][0].Length > 2) oRoutea = uprnDictionaryOrganic[val.Key][0].Substring(0, 1) + (uprnDictionaryOrganic[val.Key][0].Length > 3 ? uprnDictionaryOrganic[val.Key][0].Substring(2, 2).TrimEnd(charsToTrim) : uprnDictionaryOrganic[val.Key][0].Substring(2, 1).TrimEnd(charsToTrim)); if (uprnDictionaryOrganic.ContainsKey(val.Key) && uprnDictionaryOrganic[val.Key][0].Length > 2) organicsRoute = uprnDictionaryOrganic[val.Key][0].Substring(0, 1) + (uprnDictionaryOrganic[val.Key][0].Length > 3 ? uprnDictionaryOrganic[val.Key][0].Substring(2, 2).TrimEnd(charsToTrim) : uprnDictionaryOrganic[val.Key][0].Substring(2, 1).TrimEnd(charsToTrim)); if (uprnDictionaryOrganic.ContainsKey(val.Key) && uprnDictionaryOrganic[val.Key][6] != null && uprnDictionaryOrganic[val.Key][6].Split(' ').Length > 2) organicWeek = uprnDictionaryOrganic[val.Key][6].Split(' ')[1] + " " + uprnDictionaryOrganic[val.Key][6].Split(' ')[2]; if (uprnDictionaryOrganic.ContainsKey(val.Key)) serviceLocationOrganicSequence = uprnDictionaryOrganic[val.Key][5]; string recycleCollection = ""; string recycleRoute = ""; string recyclingRound = ""; string serviceLocationRecyclingSequence = ""; if (uprnDictionaryRecycling.ContainsKey(val.Key)) recycleCollection = uprnDictionaryRecycling[val.Key][1]; if (uprnDictionaryRecycling.ContainsKey(val.Key)) recycleRoute = uprnDictionaryRecycling[val.Key][0]; if (uprnDictionaryRecycling.ContainsKey(val.Key) && uprnDictionaryRecycling[val.Key][0].Length > 2) recyclingRound = uprnDictionaryRecycling[val.Key][0].Substring(0, 1) + (uprnDictionaryRecycling[val.Key][0].Length > 3 ? uprnDictionaryRecycling[val.Key][0].Substring(2, 2).TrimEnd(charsToTrim) : uprnDictionaryRecycling[val.Key][0].Substring(2, 1).TrimEnd(charsToTrim)); if (uprnDictionaryRecycling.ContainsKey(val.Key)) serviceLocationRecyclingSequence = uprnDictionaryRecycling[val.Key][5]; string residualCollection = val.Value[1]; string residualRoute = val.Value[0]; string refuseRound = ""; if (val.Value[0].Length > 2) refuseRound = val.Value[0].Substring(0, 1) + (val.Value[0].Length > 3 ? val.Value[0].Substring(2, 2).TrimEnd(charsToTrim) : val.Value[0].Substring(2, 1).TrimEnd(charsToTrim)); string serviceLocationRefuseSequence = val.Value[5]; string llpgName = "\"" + val.Value[6] + "\""; string llpgNo = val.Value[7]; string llpgStreet = val.Value[8]; string llpgLocality = ""; string llpgTown = val.Value[9]; string llpgPosttown = val.Value[10]; string llpgPostcode = val.Value[11]; string newLine = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23}{24}", uprn, address, postcode, organicDay, organicRoute, oRoutea, organicsRoute, organicWeek, serviceLocationOrganicSequence, recycleCollection, recycleRoute, recyclingRound, serviceLocationRecyclingSequence, residualCollection, residualRoute, refuseRound, serviceLocationRefuseSequence, llpgName, llpgNo, llpgStreet, llpgLocality, llpgTown, llpgPosttown, llpgPostcode, Environment.NewLine); uprnCsv.Append(newLine); } // Then add all the ones from organic where they don't exist in residual foreach (var val in uprnDictionaryOrganic.Where(x => !uprnDictionaryResidual.ContainsKey(x.Key))) { string uprn = val.Key; string address = "\"" + val.Value[2] + "\""; string postcode = val.Value[3]; string organicDay = ""; string organicRoute = ""; string oRoutea = ""; string organicsRoute = ""; string organicWeek = ""; string serviceLocationOrganicSequence = ""; organicDay = val.Value[1].Split(' ')[0]; organicRoute = val.Value[0]; // Round is the Letter and Third and Fourth Digit oRoutea = val.Value[0].Substring(0, 1) + val.Value[0].Substring(2, 2).TrimEnd(charsToTrim); organicsRoute = val.Value[0].Substring(0, 1) + val.Value[0].Substring(2, 2).TrimEnd(charsToTrim); if (val.Value[6] != null && val.Value[6].Split(' ') != null && val.Value[6].Split(' ').Length > 2) organicWeek = val.Value[6].Split(' ')[1] + " " + val.Value[6].Split(' ')[2]; serviceLocationOrganicSequence = val.Value[5]; string recycleCollection = ""; string recycleRoute = ""; string recyclingRound = ""; string serviceLocationRecyclingSequence = ""; if (uprnDictionaryRecycling.ContainsKey(val.Key)) recycleCollection = uprnDictionaryRecycling[val.Key][1]; if (uprnDictionaryRecycling.ContainsKey(val.Key)) recycleRoute = uprnDictionaryRecycling[val.Key][0]; if (uprnDictionaryRecycling.ContainsKey(val.Key) && uprnDictionaryRecycling[val.Key][0].Length > 2) recyclingRound = uprnDictionaryRecycling[val.Key][0].Substring(0, 1) + (uprnDictionaryRecycling[val.Key][0].Length > 3 ? uprnDictionaryRecycling[val.Key][0].Substring(2, 2).TrimEnd(charsToTrim) : uprnDictionaryRecycling[val.Key][0].Substring(2, 1).TrimEnd(charsToTrim)); if (uprnDictionaryRecycling.ContainsKey(val.Key)) serviceLocationRecyclingSequence = uprnDictionaryRecycling[val.Key][5]; string residualCollection = ""; string residualRoute = ""; string refuseRound = ""; string serviceLocationRefuseSequence = ""; string llpgName = "\"" + val.Value[7] + "\""; string llpgNo = val.Value[8]; string llpgStreet = val.Value[9]; string llpgLocality = ""; string llpgTown = val.Value[10]; string llpgPosttown = val.Value[11]; string llpgPostcode = val.Value[12]; string newLine = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23}{24}", uprn, address, postcode, organicDay, organicRoute, oRoutea, organicsRoute, organicWeek, serviceLocationOrganicSequence, recycleCollection, recycleRoute, recyclingRound, serviceLocationRecyclingSequence, residualCollection, residualRoute, refuseRound, serviceLocationRefuseSequence, llpgName, llpgNo, llpgStreet, llpgLocality, llpgTown, llpgPosttown, llpgPostcode, Environment.NewLine); uprnCsv.Append(newLine); } // Then add all the ones from organic where they don't exist in residual foreach (var val in uprnDictionaryOrganic.Where(x => !uprnDictionaryResidual.ContainsKey(x.Key) && !uprnDictionaryOrganic.ContainsKey(x.Key))) { string uprn = val.Key; string address = "\"" + val.Value[2] + "\""; string postcode = val.Value[3]; string organicDay = ""; string organicRoute = ""; string oRoutea = ""; string organicsRoute = ""; string organicWeek = ""; string serviceLocationOrganicSequence = ""; string recycleCollection = ""; string recycleRoute = ""; string recyclingRound = ""; string serviceLocationRecyclingSequence = ""; recycleCollection = val.Value[1]; recycleRoute = val.Value[0]; if (uprnDictionaryRecycling.ContainsKey(val.Key) && uprnDictionaryRecycling[val.Key][0].Length > 2) recyclingRound = uprnDictionaryRecycling[val.Key][0].Substring(0, 1) + (uprnDictionaryRecycling[val.Key][0].Length > 3 ? uprnDictionaryRecycling[val.Key][0].Substring(2, 2).TrimEnd(charsToTrim) : uprnDictionaryRecycling[val.Key][0].Substring(2, 1).TrimEnd(charsToTrim)); serviceLocationRecyclingSequence = val.Value[5]; string residualCollection = ""; string residualRoute = ""; string refuseRound = ""; string serviceLocationRefuseSequence = ""; string llpgName = "\"" + val.Value[6] + "\""; string llpgNo = val.Value[7]; string llpgStreet = val.Value[8]; string llpgLocality = ""; string llpgTown = val.Value[9]; string llpgPosttown = val.Value[10]; string llpgPostcode = val.Value[11]; string newLine = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23}{24}", uprn, address, postcode, organicDay, organicRoute, oRoutea, organicsRoute, organicWeek, serviceLocationOrganicSequence, recycleCollection, recycleRoute, recyclingRound, serviceLocationRecyclingSequence, residualCollection, residualRoute, refuseRound, serviceLocationRefuseSequence, llpgName, llpgNo, llpgStreet, llpgLocality, llpgTown, llpgPosttown, llpgPostcode, Environment.NewLine); uprnCsv.Append(newLine); } File.WriteAllText(appSettings["uprnCsv"], uprnCsv.ToString()); } catch (FileGDBException ex) { Console.WriteLine("{0} - {1}", ex.Message, ex.ErrorCode); } catch (Exception ex) { Console.WriteLine("General exception. " + ex.Message); } //} }
private DfmTagNameResolveResult ResolveTagNamesFromPath(string fencesPath, string[] fencesCodeLines, string tagName, Regex regexToExtractCode) { var lazyResolveResults = _dfmTagNameLineRangeCache.GetOrAdd(fencesPath, path => new Lazy<ConcurrentDictionary<string, DfmTagNameResolveResult>>( () => { var linesOfSnippetComment = new Dictionary<long, string>(); for (long i = 0; i < fencesCodeLines.Length; i++) { var match = regexToExtractCode.Match(fencesCodeLines[i]); if (match.Success) { linesOfSnippetComment.Add(i + 1, match.Groups[1].Value); } } var excludedLines = new HashSet<long>(linesOfSnippetComment.Keys); var dictionary = new ConcurrentDictionary<string, DfmTagNameResolveResult>(StringComparer.OrdinalIgnoreCase); foreach (var snippetCommentsInPair in linesOfSnippetComment.GroupBy(kvp => kvp.Value)) { DfmTagNameResolveResult tagResolveResult; var lineNumbers = snippetCommentsInPair.Select(line => line.Key).OrderBy(line => line).ToList(); if (lineNumbers.Count == 2) { tagResolveResult = new DfmTagNameResolveResult { IsSuccessful = true, StartLine = lineNumbers[0] + 1, EndLine = lineNumbers[1] - 1, ExcludesLines = excludedLines }; } else { tagResolveResult = new DfmTagNameResolveResult { IsSuccessful = false, ErrorMessage = lineNumbers.Count == 1 ? $"Tag name {snippetCommentsInPair.Key} is not closed" : $"Tag name {snippetCommentsInPair.Key} occurs {lineNumbers.Count} times" }; } dictionary.TryAdd(snippetCommentsInPair.Key, tagResolveResult); } return dictionary; })); DfmTagNameResolveResult resolveResult; var tagNamesDictionary = lazyResolveResults.Value; return (tagNamesDictionary.TryGetValue(tagName, out resolveResult) || tagNamesDictionary.TryGetValue($"snippet{tagName}", out resolveResult)) ? resolveResult : new DfmTagNameResolveResult { IsSuccessful = false, ErrorMessage = $"Tag name {tagName} is not found" }; }