/// <summary> /// Builds the class constructor. /// </summary> /// <param name="type">The type.</param> /// <param name="sb">The string builder.</param> /// <param name="options">The options.</param> private static void BuildClassConstructor(IGrouping <string, PropertyBag> type, StringBuilder sb, JsGeneratorOptions options) { if ( type.Any( p => (p.CollectionInnerTypes != null && p.CollectionInnerTypes.Any(q => !q.IsPrimitiveType)) || p.TransformablePropertyType == PropertyBag.TransformablePropertyTypeEnum.ReferenceType)) { sb.AppendLine( $"{options.OutputNamespace}.{Helpers.GetName(type.First().TypeName, options.ClassNameConstantsToRemove)} = function (cons, overrideObj) {{"); sb.AppendLine("\tif (!overrideObj) { overrideObj = { }; }"); sb.AppendLine("\tif (!cons) { cons = { }; }"); } else if (type.First().TypeDefinition.IsEnum) { sb.AppendLine( $"{options.OutputNamespace}.{Helpers.GetName(type.First().TypeName, options.ClassNameConstantsToRemove)} = {{"); } else { sb.AppendLine( $"{options.OutputNamespace}.{Helpers.GetName(type.First().TypeName, options.ClassNameConstantsToRemove)} = function (cons) {{"); sb.AppendLine("\tif (!cons) { cons = { }; }"); } }
private static DeptWiseAttendanceDTO CreateAttendanceDTO(IGrouping <int, ActivityLogDTO> grp, IEnumerable <Employee> allEmployees) { var deptMembers = allEmployees.Where(e => e.Deprtment.Id == grp.First().Department.Id); var dto = new DeptWiseAttendanceDTO { DepartmentName = grp.First().Department.Name, Attendance = grp.GroupBy(gd => gd.Employee.Id) .Select(empGroup => new AttendanceDTO { EmployeeName = empGroup.First().Employee.Name, EmployeeId = empGroup.First().Employee.Id, Attended = true, Date = empGroup.First().TimeStamp.ToString("yyyy-MM-dd") }) .ToList() }; var absents = deptMembers.Where(m => !dto.Attendance.Any(a => a.EmployeeId == m.Id)); var date = dto.Attendance.First().Date; dto.Attendance.AddRange(absents.Select(a => new AttendanceDTO { EmployeeName = a.Name, EmployeeId = a.Id, Attended = false, Date = date })); return(dto); }
//internal TableInfo(DB2Connection connection, DB2DataReader reader) //{ // _connection = connection; // Name = Convert.ToString(reader.GetValue(reader.GetOrdinal("NAME"))); // Remarks = Convert.ToString(reader.GetValue(reader.GetOrdinal("REMARKS"))); //} internal TableInfo(IGrouping<string, DataRow> data) { _data = data; Name = data.First().Field<string>("TBNAME"); Remarks = data.First().Field<string>("TBREMARKS"); }
//internal TableInfo(DB2Connection connection, DB2DataReader reader) //{ // _connection = connection; // Name = Convert.ToString(reader.GetValue(reader.GetOrdinal("NAME"))); // Remarks = Convert.ToString(reader.GetValue(reader.GetOrdinal("REMARKS"))); //} internal TableInfo(IGrouping <string, DataRow> data) { _data = data; Name = data.First().Field <string>("TBNAME"); Remarks = data.First().Field <string>("TBREMARKS"); }
private static StringBuilder GenerateClass(IGrouping <string, RouteInfo> group, bool isLast) { string classFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller"; string crefNamespace = GetCrefNamespace(classFullName, GetConvertedNamespace(group.First().Namespace)); StringBuilder sb = new StringBuilder(); sb.AppendLine($" /// <summary>"); sb.AppendLine($" /// <see cref=\"{crefNamespace}\"/>"); sb.AppendLine($" /// </summary>"); sb.AppendLine($" public class {group.Key}Route"); sb.AppendLine(" {"); for (int i = 0; i < group.Count(); i++) { var item = group.ElementAt(i); var renamedAction = RenameOverloadedAction(group, i); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public const string {renamedAction} = \"{item.Path}\";"); if (i != group.Count() - 1) { sb.AppendLine(); } } sb.AppendLine(" }"); if (!isLast) { sb.AppendLine(); } return(sb); }
private static long GetSpeedInBytes(IGrouping <long, KeyValuePair <long, long> > measurements, int useMiliseconds = 0) { long time = useMiliseconds == 0 ? measurements.Last().Key - measurements.First().Key : useMiliseconds; long downloadedBytes = (measurements.Last().Value - measurements.First().Value); return(downloadedBytes / (time / 1000)); }
private static CounterRecord AggregateDuplicates <T>(IGrouping <T, CounterRecord> records) { if (records.Count() <= 1) { return(records.First()); } List <CounterRecord> listRecords = records.ToList(); if (records.Count() <= 1) { return(records.First()); } CounterRecord record = new CounterRecord { ItemName = listRecords[0].ItemName, ItemPlatform = listRecords[0].ItemPlatform, ItemType = listRecords[0].ItemType, RunDate = listRecords[0].RunDate, Identifiers = listRecords.SelectMany(x => x.Identifiers).Distinct(new CounterIdentifierComparer()).ToArray(), Metrics = listRecords.SelectMany(x => x.Metrics).Distinct(new CounterMetricComparer()).GroupBy(x => x.MetricType).Select(x => new CounterMetric { MetricType = x.Key, MetricValue = x.Sum(y => y.MetricValue) }).ToArray(), }; return(record); }
public GroupedOrderTagViewModel(Order selectedItem, IGrouping<string, OrderTagGroup> orderTagGroups) { Name = orderTagGroups.Key; OrderTags = orderTagGroups.Select(x => new GroupedOrderTagButtonViewModel(selectedItem, x)).ToList(); ColumnCount = orderTagGroups.First().ColumnCount; ButtonHeight = orderTagGroups.First().ButtonHeight; }
private static string getHTMLPorCadaTipoDeItem(IGrouping <ItemMinuta.tipoItem, ItemMinuta> itemAgrupadoPorTipo, int cantidadTiposDeItem) { string itemsMinutaPorCadaTipo; if (!Dominio.ItemMinuta.esTipoItemEspecial(itemAgrupadoPorTipo.First()) || cantidadTiposDeItem > 1) { // Agregamos el tipo itemsMinutaPorCadaTipo = String.Format("<li> {0} <ul>", ItemMinuta.getDescripcionForKey(itemAgrupadoPorTipo.Key)); // Agregamos todas las descripciones foreach (var itemMinuta in itemAgrupadoPorTipo) { itemsMinutaPorCadaTipo += String.Format("<li> {0} </li>", itemMinuta.descripcion); } // Cerramos la lista de items de ese tipo. itemsMinutaPorCadaTipo += "</ul> </li>"; } else { // Si entramos en este caso es uno de los tipos especiales (holidays, later, sick) entonces no hay otro nivel de indentacion. itemsMinutaPorCadaTipo = String.Format("<li> {0} </li>", itemAgrupadoPorTipo.First().descripcion); } return(itemsMinutaPorCadaTipo); }
public GroupedOrderTagViewModel(Order selectedItem, IGrouping <string, OrderTagGroup> orderTagGroups) { Name = orderTagGroups.Key; OrderTags = orderTagGroups.Select(x => new GroupedOrderTagButtonViewModel(selectedItem, x)).ToList(); ColumnCount = orderTagGroups.First().ColumnCount; ButtonHeight = orderTagGroups.First().ButtonHeight; }
private static double GetSpeedInKBs(IGrouping <long, KeyValuePair <long, long> > measurements, int useMiliseconds = 0) { long time = useMiliseconds == 0 ? measurements.Last().Key - measurements.First().Key : useMiliseconds; double downloadedKBs = (measurements.Last().Value - measurements.First().Value) / (double)Constants.Kilobyte; return(downloadedKBs / (time / 1000d)); }
private static DeptWiseAttendanceDTO CreateAttendanceDTO(IGrouping<int, ActivityLogDTO> grp, IEnumerable<Employee> allEmployees) { var deptMembers = allEmployees.Where(e => e.Deprtment.Id == grp.First().Department.Id); var dto = new DeptWiseAttendanceDTO { DepartmentName = grp.First().Department.Name, Attendance = grp.GroupBy(gd => gd.Employee.Id) .Select(empGroup => new AttendanceDTO { EmployeeName = empGroup.First().Employee.Name, EmployeeId = empGroup.First().Employee.Id, Attended = true, Date = empGroup.First().TimeStamp.ToString("yyyy-MM-dd") }) .ToList() }; var absents = deptMembers.Where(m => !dto.Attendance.Any(a => a.EmployeeId == m.Id)); var date = dto.Attendance.First().Date; dto.Attendance.AddRange(absents.Select(a => new AttendanceDTO { EmployeeName = a.Name, EmployeeId = a.Id, Attended = false, Date = date })); return dto; }
public MenuItemGroupedPropertyViewModel(TicketItemViewModel selectedItem, IGrouping<string, MenuItemPropertyGroup> menuItemPropertyGroups) { Name = menuItemPropertyGroups.Key; Properties = menuItemPropertyGroups.Select(x => new MenuItemGroupedPropertyItemViewModel(selectedItem, x)).ToList(); ColumnCount = menuItemPropertyGroups.First().ColumnCount; ButtonHeight = menuItemPropertyGroups.First().ButtonHeight; TerminalButtonHeight = menuItemPropertyGroups.First().TerminalButtonHeight; TerminalColumnCount = menuItemPropertyGroups.First().TerminalColumnCount; }
public MenuItemGroupedPropertyViewModel(TicketItemViewModel selectedItem, IGrouping <string, MenuItemPropertyGroup> menuItemPropertyGroups) { Name = menuItemPropertyGroups.Key; Properties = menuItemPropertyGroups.Select(x => new MenuItemGroupedPropertyItemViewModel(selectedItem, x)).ToList(); ColumnCount = menuItemPropertyGroups.First().ColumnCount; ButtonHeight = menuItemPropertyGroups.First().ButtonHeight; TerminalButtonHeight = menuItemPropertyGroups.First().TerminalButtonHeight; TerminalColumnCount = menuItemPropertyGroups.First().TerminalColumnCount; }
public void OnSlaveInfoRefresh(IGrouping <string, KeyValuePair <string, string> > group) { var masterLinkStatus = group.First(kv => kv.Key.Equals("master_link_status")).Value; var replOffset = long.Parse(group.First(kv => kv.Key.Equals("slave_repl_offset")).Value); var priority = int.Parse(group.First(kv => kv.Key.Equals("slave_priority")).Value); LinkStatus = masterLinkStatus; REPLOffset = replOffset; Priority = priority; }
private static MetaField AggregateFieldInstances(IGrouping <int, MetaField> field_instances) { if (g_field_type_aggregation_threshold < 1.0) { long instances_num = 0; Dictionary <FieldType, long> cnt_dict = new Dictionary <FieldType, long>(); Dictionary <FieldType, bool> list_dict = new Dictionary <FieldType, bool>(); foreach (var instance in field_instances) { ++instances_num; if (cnt_dict.ContainsKey(instance.fieldType)) { ++cnt_dict[instance.fieldType]; list_dict[instance.fieldType] = list_dict[instance.fieldType] || instance.isList; } else { cnt_dict[instance.fieldType] = 1; list_dict[instance.fieldType] = instance.isList; } } if (instances_num == 0) { throw new ArgumentException("No instances for a field", "field_instances"); } long dominating_num = cnt_dict.Max(_ => _.Value); FieldType dominating_type = cnt_dict.First(_ => _.Value == dominating_num).Key; bool dominating_list = list_dict[dominating_type]; double dominating_type_ratio = dominating_num / (double)instances_num; if (dominating_type_ratio >= g_field_type_aggregation_threshold) { var dominating_field = new MetaField { fieldId = field_instances.Key, fieldType = dominating_type, isList = dominating_list, typeId = field_instances.First().typeId }; Log.WriteLine("Found dominating type {0} for Type {1}: Field {2} ({3:P1}).", dominating_type, dominating_field.typeId, dominating_field.fieldId, dominating_type_ratio); return(dominating_field); } } return(field_instances.Aggregate(field_instances.First(), (f, current) => { f.isList = f.isList || current.isList; f.fieldType = UpdateFieldType(f.fieldType, current.fieldType); return f; })); }
public MarketingList(IGrouping <Guid, Entity> listGroup) { Id = listGroup.Key; Name = listGroup.First().GetAttributeValue <string>("listname"); Purpose = listGroup.First().GetAttributeValue <string>("purpose"); Subscribers = listGroup.Where(g => g.GetAttributeValue <AliasedValue>("c.contactid") != null).Select(e => new EntityReference("contact", (Guid)e.GetAttributeValue <AliasedValue>("c.contactid").Value)) .Concat(listGroup.Where(g => g.GetAttributeValue <AliasedValue>("l.leadid") != null).Select(e => new EntityReference("lead", (Guid)e.GetAttributeValue <AliasedValue>("l.leadid").Value))) .Concat(listGroup.Where(g => g.GetAttributeValue <AliasedValue>("a.accountid") != null).Select(e => new EntityReference("account", (Guid)e.GetAttributeValue <AliasedValue>("a.accountid").Value))) .Distinct(); }
public AggregatedResult(IGrouping <string, TournamentResult> results) { Username = results.First().Username; Title = results.First().Title; MaxRating = results.Max(p => p.Rating); Ranks = results.Select(p => p.Rank); Scores = results.Select(p => p.Score >= p.Points ? p.Score : p.Points); // A TournamentResult should only have either Score (Arena tournaments) or Points (Swiss tournaments) TieBreaks = results.Select(p => p.TieBreak); TotalScores = Scores.Sum(); TotalTieBreaks = TieBreaks.Sum(); AveragePerformance = (double)results.Select(p => p.Performance).Sum() / results.Count(); }
private Line CreateLine(IGrouping <string, Line> groupedLine) { return(new Line { Description = groupedLine.First().Description, LineTotalInclVat = groupedLine.Sum(y => y.LineTotalInclVat), MerchantProductNo = groupedLine.Key, Quantity = groupedLine.Sum(y => y.Quantity), Status = groupedLine.First().Status, UnitPriceInclVat = groupedLine.First().UnitPriceInclVat }); }
private static DuplicatedFiles MapGrouping(IGrouping <string, IndexedFile> grouping) { var result = new DuplicatedFiles { Count = grouping.Count(), Etag = grouping.First().Etag, Files = grouping.ToList(), TotalSize = grouping.Sum(f => f.Size), IndividualSize = grouping.First().Size }; return(result); }
/// <summary> /// Initializes a new instance of the <see cref="ApiActionDescription" /> class. /// </summary> /// <param name="group">The group.</param> public ApiActionDescription(IGrouping <string, ApiDescription> group) { this.Name = group.First().ActionDescriptor.ActionName; this.ParameterDescriptions = group.Select(a => a.ParameterDescriptions).First(); this.Routes = group.Select(a => new ApiRouteDescription(a)); try { this.Summary = JsonConvert.DeserializeObject <JObject>(group.Key).Value <string>("summary"); this.Example = JsonConvert.DeserializeObject <JObject>(group.Key).Value <string>("example"); this.Remarks = JsonConvert.DeserializeObject <JObject>(group.Key).Value <string>("remarks"); this.Returns = JsonConvert.DeserializeObject <JObject>(group.Key).Value <string>("returns"); } catch (JsonReaderException jrException) { this.Summary = string.Empty; this.Example = string.Empty; this.Remarks = string.Empty; this.Returns = string.Empty; } // Generate sample requests var sampleRequests = new List <ApiActionSample>(); foreach (var mediaTypeFormatter in group.First().SupportedRequestBodyFormatters) { var request = new ApiActionSample(mediaTypeFormatter, group.First(), ApiActionSampleDirection.Request); if (request.Sample != null) { sampleRequests.Add(request); } } this.SampleRequests = sampleRequests; // Generate sample responses var sampleResponses = new List <ApiActionSample>(); foreach (var mediaTypeFormatter in group.First().SupportedResponseFormatters) { var response = new ApiActionSample(mediaTypeFormatter, group.First(), ApiActionSampleDirection.Response); if (response.Sample != null) { sampleResponses.Add(response); } } this.SampleResponses = sampleResponses; }
/// <summary> /// Initializes a new instance of the <see cref="RescueSecond"/> class. /// </summary> /// <param name="group">The group.</param> /// <param name="time">The time.</param> public RescueSecond(IGrouping <Guid, RescueRoomInfo> group, DateTime time) { this.IsRescue = group.First().IsRescue; this.RescueResultId = group.Key; this.Time = time; this.Level = 2; this.RescueResultName = group.First().RescueResult.RescueResultName; if (string.IsNullOrEmpty(this.RescueResultName)) { this.RescueResultName = "--"; } this.Count = group.Count(); }
public Section MergeSections(IGrouping <string, Section> combinedSections, Guid chapterId) { var mergedSection = new Section() { Description = combinedSections.First().Description, Numeric = combinedSections.First().Numeric, ChapterId = chapterId }; var disciplineCount = _disciplineGuids.Count; var sectionCount = combinedSections.Count(); if (disciplineCount == sectionCount) { mergedSection.Name = combinedSections.Key; } else { var sectionOwners = combinedSections.Select(o => _disciplineNames[o.DisciplineId]); var sectionNames = new StringBuilder(); sectionNames.Append("("); foreach (var owner in sectionOwners) { sectionNames.Append(owner); if (owner != sectionOwners.Last()) { sectionNames.Append(" | "); } } sectionNames.Append(" only)"); mergedSection.Name = $"{combinedSections.Key} {sectionNames}"; } var allRules = combinedSections.SelectMany(o => o.Rules); var allRulesLookup = allRules.ToLookup(o => o.Description, o => o); foreach (var combinedRules in allRulesLookup) { mergedSection.Rules.Add(MergeRules(combinedRules, mergedSection.SectionId)); } return(mergedSection); }
public Rule MergeRules(IGrouping <string, Rule> combinedRules, Guid sectionId) { var mergedRule = new Rule() { Numeric = combinedRules.First().Numeric, Description = combinedRules.Key, SectionId = sectionId }; var disciplineCount = _disciplineGuids.Count; var ruleCount = combinedRules.Count(); if (disciplineCount == ruleCount) { mergedRule.Name = combinedRules.First().Name; } else { var ruleOwners = combinedRules.Select(o => _disciplineNames[o.DisciplineId]); var ruleNames = new StringBuilder(); ruleNames.Append("("); foreach (var owner in ruleOwners) { ruleNames.Append(owner); if (owner != ruleOwners.Last()) { ruleNames.Append(" | "); } } ruleNames.Append(" only)"); mergedRule.Name = $"{mergedRule.Name} {ruleNames}"; } var allSubRules = combinedRules.SelectMany(o => o.SubRules); var allSubRulesLookup = allSubRules.ToLookup(o => o.Description, o => o); foreach (var combinedSubRules in allSubRulesLookup) { mergedRule.SubRules.Add(MergeSubRules(combinedSubRules, mergedRule.RuleId)); } return(mergedRule); }
public Chapter MergeChapters(IGrouping <string, Chapter> combinedChapters, Guid disciplineId) { var mergedChapter = new Chapter() { Description = combinedChapters.First().Description, Numeric = combinedChapters.First().Numeric, DisciplineId = disciplineId }; var disciplineCount = _disciplineGuids.Count; var chapterCount = combinedChapters.Count(); if (disciplineCount == chapterCount) { mergedChapter.Name = combinedChapters.Key; } else { var chapterOwners = combinedChapters.Select(o => _disciplineNames[o.DisciplineId]); var chapterNames = new StringBuilder(); chapterNames.Append("("); foreach (var owner in chapterOwners) { chapterNames.Append(owner); if (owner != chapterOwners.Last()) { chapterNames.Append(" | "); } } chapterNames.Append(" only)"); mergedChapter.Name = $"{combinedChapters.Key} {chapterNames}"; } var allSections = combinedChapters.SelectMany(o => o.Sections); var allSectionsLookup = allSections.ToLookup(o => o.Name, o => o); foreach (var combinedSections in allSectionsLookup) { mergedChapter.Sections.Add(MergeSections(combinedSections, mergedChapter.ChapterId)); } return(mergedChapter); }
/// <summary> /// Initializes a new instance of the <see cref="DestinationThird"/> class. /// </summary> /// <param name="group">The group.</param> /// <param name="time">The time.</param> public DestinationThird(IGrouping <string, RescueRoomInfo> group, DateTime time) { this.DestinationId = group.First().DestinationId.Value; this.DestinationRemarks = group.Key; this.Time = time; this.Level = 3; this.DestinationRemarksForDisplay = group.First().DestinationRemarks; this.Count = group.Count(); if (string.IsNullOrEmpty(this.DestinationRemarksForDisplay)) { this.DestinationRemarksForDisplay = "--"; } }
private static StringBuilder GenerateClass(IGrouping <string, RouteInfo> group, bool isLast) { string classFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller"; string crefNamespace = GetCrefNamespace(classFullName, GetConvertedNamespace(group.First().Namespace)); StringBuilder sb = new StringBuilder(); sb.AppendLine($" /// <summary>"); sb.AppendLine($" /// <see cref=\"{crefNamespace}\"/>"); sb.AppendLine($" /// </summary>"); sb.AppendLine($" public class {group.Key}Route"); sb.AppendLine(" {"); for (int i = 0; i < group.Count(); i++) { var item = group.ElementAt(i); var renamedAction = RenameOverloadedAction(group, i); sb.AppendLine(" /// <summary>"); sb.AppendLine($" /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>"); sb.AppendLine(" /// </summary>"); sb.AppendLine($" public const string {renamedAction} = \"{item.Path}\";"); if (config != null && config.GenerateMethod) { sb.AppendLine($" public static async Task<T> {item.ActionName}Async<T>({GeneraParameters(item.Parameters, true, false)})"); sb.AppendLine(" {"); sb.AppendLine($" var routeInfo = new {nameof(RouteInfo)}"); sb.AppendLine(" {"); sb.AppendLine($" {nameof(RouteInfo.HttpMethods)} = \"{item.HttpMethods}\","); sb.AppendLine($" {nameof(RouteInfo.Path)} = {renamedAction},"); sb.Append(GenerateParameters(item.Parameters)); sb.AppendLine(" };"); sb.AppendLine($" return await {nameof(HttpClientAsync)}.{nameof(HttpClientAsync.Async)}<T>(routeInfo{GeneraParameters(item.Parameters, false, true)});"); sb.AppendLine(" }"); } if (i != group.Count() - 1) { sb.AppendLine(); } } sb.AppendLine(" }"); if (!isLast) { sb.AppendLine(); } return(sb); }
/// <summary> /// Check that changes grouped by entity id belongs to website. /// </summary> /// <param name="groupedChanges">Changes grouped by entity id.</param> /// <param name="context">Crm DB context.</param> /// <param name="websiteId">Website id.</param> /// <returns></returns> private bool ChangesBelongsToWebsite(IGrouping <Guid, IChangedItem> groupedChanges, CrmDbContext context, Guid websiteId) { var entityId = groupedChanges.Key; var entityName = this.GetEntityNameFromChangedItem(groupedChanges.First()); if (string.Equals("adx_website", entityName, StringComparison.OrdinalIgnoreCase)) { return(websiteId == entityId); } // if entity hasn't relationship with website or entity was deleted -> mark as `belongs to website` EntityTrackingInfo info; if (groupedChanges.Any(gc => gc.Type == ChangeType.RemoveOrDeleted) || !entityInfoList.TryGetValue(entityName, out info) || info.WebsiteLookupAttribute == null) { return(true); } // trying to get website's id from changed items var itemWithWebsiteIdValue = groupedChanges .OfType <NewOrUpdatedItem>() .FirstOrDefault(item => item.NewOrUpdatedEntity.Contains(info.WebsiteLookupAttribute)); // if all changes doesn't contain website lookup attribute but we know that entity should have it then try to get value from service context var updatedEntity = itemWithWebsiteIdValue != null ? itemWithWebsiteIdValue.NewOrUpdatedEntity : context.Service.RetrieveSingle(new EntityReference(entityName, entityId), new ColumnSet(info.WebsiteLookupAttribute)); return(updatedEntity?.GetAttributeValue <EntityReference>(info.WebsiteLookupAttribute)?.Id == websiteId); }
private void SaveStream(IGrouping <string, trout_streams_minnesota> section, string stateName, int stateId, List <trout_streams_minnesota> badList) { using (var context = new MinnesotaShapeDataContext()) using (var troutDashContext = new TroutDashPrototypeContext()) { try { var id = section.Key; Console.WriteLine("Loading Trout Stream Id: " + id); var route = context.StreamRoute.Single(sr => sr.kittle_nbr == id); stream stream = CreateStream(route, stateName, stateId); Console.WriteLine("Saving trout stream: " + stream.name); troutDashContext.streams.Add(stream); troutDashContext.SaveChanges(); CreateStreamSections(route, section, stream); troutDashContext.SaveChanges(); } catch (Exception) { Console.WriteLine("FAILED LOAIND STREAM: " + section.Key); badList.Add(section.First()); } } }
public static Delivery MapToDelivery(this IGrouping <int, Message> groupedMessages) { var delivery = new Delivery(); if (!groupedMessages.Any()) { return(delivery); } delivery.PositionHistory = new List <Zuehlke.Camp2013.ConnectedVehicles.Position>(); delivery.StatusHistory = new List <DeliveryStatus>(); delivery.Vehicle = new Vehicle { VehicleId = groupedMessages.First().VehicleId, SensorHistory = new List <SensorData>() }; foreach (var message in groupedMessages) { delivery.PositionHistory.Add(message.MapToPosition()); if (message.Type == MessageType.STATUS) { delivery.StatusHistory.Add(message.MapToDeliveryStatus()); } if (message.Type == MessageType.SENSOR) { delivery.Vehicle.SensorHistory.Add(message.MapToSensorData()); } } return(delivery); }
private static void GroupSubBranchesIntoOneMainBranch( IGrouping <CommitId, KeyValuePair <string, MSubBranch> > groupByBranch) { // All sub branches in the groupByBranch have same name and parent commit id, lets take // the first sub branch and base the branch corresponding to the group on that sub branch MSubBranch subBranch = groupByBranch.First().Value; string branchId = subBranch.Name + "-" + subBranch.ParentCommitId; MBranch branch = GetBranch(branchId, subBranch); // Get active sub branches in group (1 if either local or remote, 2 if both) var activeSubBranches = groupByBranch .Where(b => b.Value.IsActive).Select(g => g.Value) .ToList(); branch.IsActive = activeSubBranches.Any(); MSubBranch localSubBranch = activeSubBranches.FirstOrDefault(b => b.IsLocal); MSubBranch remoteSubBranch = activeSubBranches.FirstOrDefault(b => b.IsRemote); branch.IsLocal = localSubBranch != null; branch.LocalTipCommitId = localSubBranch?.TipCommitId ?? CommitId.None; branch.IsRemote = remoteSubBranch != null; branch.RemoteTipCommitId = remoteSubBranch?.TipCommitId ?? CommitId.None; branch.IsCurrent = activeSubBranches.Any(b => b.IsCurrent); branch.IsDetached = activeSubBranches.Any(b => b.IsDetached); branch.LocalAheadCount = 0; branch.RemoteAheadCount = 0; // Set branch if of each sub branch groupByBranch.ForEach(b => b.Value.BranchId = branch.Id); }
private IEnumerable <QuizInfoForDb> CreateQuizInfo(QuizSlide slide, IGrouping <string, QuizAnswer> answer) { var block = slide.GetBlockById(answer.Key); if (block is FillInBlock) { return(CreateQuizInfoForDb(block as FillInBlock, answer.First().Text)); } if (block is ChoiceBlock) { return(CreateQuizInfoForDb(block as ChoiceBlock, answer)); } if (block is OrderingBlock) { return(CreateQuizInfoForDb(block as OrderingBlock, answer)); } if (block is MatchingBlock) { return(CreateQuizInfoForDb(block as MatchingBlock, answer)); } if (block is IsTrueBlock) { return(CreateQuizInfoForDb(block as IsTrueBlock, answer)); } return(null); }
private StandardOrganisationSummary MapToStandardOrganisationSummary(IGrouping <string, StandardOrganisationDocument> standardOrganisation) { var result = new StandardOrganisationSummary { StandardCode = standardOrganisation.First().StandardCode }; var periods = new List <Period>(); foreach (var standardOrganisationDocument in standardOrganisation) { var period = new Period { EffectiveFrom = standardOrganisationDocument.EffectiveFrom }; if (standardOrganisationDocument.EffectiveTo != null && standardOrganisationDocument.EffectiveTo != default(DateTime)) { period.EffectiveTo = standardOrganisationDocument.EffectiveTo; } periods.Add(period); } result.Periods = periods; return(result); }
private ElectricityInfoEntity createSummaryElectricityRow(IGrouping <int, ElectricityFileInfo> row) { var defaultValues = row.First(); var maxPaymentDate = row.Max(x => x.PaymentDate); return(new ElectricityInfoEntity { AmountAfterTax = row.Sum(x => x.Amount), BankAccount = defaultValues.BankAccount, BankAccountType = defaultValues.BankAccountType, Branch = defaultValues.BankBranch, Bank = defaultValues.BankCode, BillCreatingDate = row.Min(x => x.BillCreatingDate), ConsumerAddress = defaultValues.ConsumerAddress, ConsumerName = defaultValues.ConsumerName, ConsumerNumber = defaultValues.ConsumerNumber, CustomerId = defaultValues.CustomerId, GeneralRowId = defaultValues.GeneralRowId, Invoice = 0, JournalEntryNumber = 0, MonthOfLastInvoice = maxPaymentDate.Month, NumberOfCreditDays = defaultValues.NumberOfCreditDays, PaymentDate = maxPaymentDate, YearOfLastInvoice = maxPaymentDate.Year, IsMatched = row.Where(x => !x.IsMatched).Count() == 0, Contract = row.Key, RowId = 0, }); }
public static PageRequest GetEventFromGroup(IGrouping<Guid, PageRequest> group) { var element = group.First(); var other = group.Skip(1).ToList(); if (other.Count == 0) return element; else return new RequestSessionGroup(element, other); }
private void PerformJobs(IGrouping<ISynchronizeInvoke, UpdateUIJob> jobGroup) { var firstJob = jobGroup.First(); jobGroup.Where(job => job != firstJob).ForEach(firstJob.MergeWith); firstJob.Perform(); }
private static IEnumerable<IAutoCompleteListItem> parseClientGroup(IGrouping<ulong, Toggl.TogglAutocompleteView> c) { var projectItems = c.GroupBy(p => p.ProjectID).Select(parseProjectGroup); if (c.Key == 0) return projectItems; var clientName = c.First().ClientLabel; return new ClientCategory(clientName, projectItems.ToList()).Yield<IAutoCompleteListItem>(); }
public AirCondRow(IGrouping<Color, AirConditioner> groupCond) { var firstAir = groupCond.First(); Color = groupCond.Key; AirConds = groupCond.ToList(); Count = AirConds.Count; ColorName = firstAir.ColorName; Mark = firstAir.Mark; }
static void DisplayGroupResults(IGrouping<int, RunResult> group) { Console.WriteLine("Benchmark {0}, Runner {1}, {2} iterations", group.First().BenchmarkType.Name, group.First().RunnerType.Name, group.Key); Console.WriteLine(); Console.WriteLine("{0,-30}{1,-14}{2,-12}{3,-10}{4}", "Implementation", "Duration", "Difference", "Each", "Multiplier"); Console.WriteLine(new string('=', 78)); IOrderedEnumerable<RunResult> ordered = group.OrderBy(x => x.Duration); RunResult best = ordered.First(); ordered.Select(x => new DisplayResult(x, best)) .Each(DisplayResult); Console.WriteLine(); }
static string Generate(IGrouping<string, MethodDom> group) { var first = group.First(); XElement body; var doc = GetDoc(out body); body.Add( x("h1", first.Type.SimpleName + GetMemberName(first) + Names[Strings.SuffixDelimeter] + Names[GetMethodKindName(first)] + " " ), BuildMembers("OverloadList",group) ); return doc.ToString(); }
private static void ProcessSubscription(IGrouping<string, Subscription> userSubs) { string cookie = string.Empty; foreach (var sub in userSubs) { string fileName = GenerateReport(sub, sub == userSubs.First(), ref cookie); if (fileName != string.Empty) { Task.Factory.StartNew(() => { SendEmail(sub, fileName); }); } } }
static void DisplayGroupResults(IGrouping<int, RunResult> group) { Console.WriteLine("Benchmark {0}, Runner {1}, {2} iterations", group.First().BenchmarkType.Name, group.First().RunnerType.Name, group.Key); Console.WriteLine(); Console.WriteLine("{0,-30}{1,-14}{2,-12}{3,-10}{4,-12}{5,-12}{6}", "Implementation", "Duration", "Difference", "Each", "Multiplier", "Memory(KB)", "Throughput"); Console.WriteLine(new string('=', 102)); IOrderedEnumerable<RunResult> ordered = group.OrderBy(x => x.Duration); RunResult best = ordered.First(); IEnumerable<DisplayResult> results = ordered.Select(x => new DisplayResult(x, best)); foreach (DisplayResult x in results) { DisplayResult(group.Key, x); } Console.WriteLine(); }
private static MembershipDetails _CreateSingleMembershipWithCorrectStatus(IGrouping<int, MembershipDetails> groupedDetails) { var firstDetails = groupedDetails.First(); var statusToUse = groupedDetails .OrderBy(d => d.MembershipStatus) .First().MembershipStatus; return new MembershipDetails { BecNumber = firstDetails.BecNumber, FirstName = firstDetails.FirstName, LastName = firstDetails.LastName, MembershipStatus = statusToUse }; }
private static IPlugin FindMaxVersionPlugin(IGrouping<string, IPlugin> plugins) { Debug.Assert(plugins.Any()); var maxVersionPlugin = plugins.First(); foreach (var plugin in plugins) { if (maxVersionPlugin.Version.CompareTo(plugin.Version) == -1) { LogManager.Warning(String.Format("Found previous version of plugin. Current version:" + PluginTostring(plugin) + " Previous version: " + PluginTostring(maxVersionPlugin))); maxVersionPlugin = plugin; } else { if (maxVersionPlugin != plugin) { LogManager.Warning(String.Format("Found previous version of plugin. Current version: " + PluginTostring(maxVersionPlugin) +" Previous version: " + PluginTostring(plugin))); } } } return maxVersionPlugin; }
private static bool HasSingletonExtensionPointsInView( IGrouping<Guid, Product> group, IEnumerable<IExtensionPointInfo> extensionPoints, IPatternManager patternManager) { return extensionPoints.Any(x => (x.Cardinality == Cardinality.OneToOne || x.Cardinality == Cardinality.ZeroToOne) && patternManager.GetCandidateExtensionPoints(x.RequiredExtensionPointId) .Any(f => f.Schema.Pattern.Id == group.Key && f.Id == group.First().ExtensionId)); }
private void ShowItemOnRow(DataGridViewRow row, IGrouping<string, DeviceReadLog> g) { row.Tag = g; string[] temp = g.Key.Split(','); row.Cells["colReadDate"].Value = temp[1]; row.Cells["colDevice"].Value = temp.Length >= 3 ? g.First().DeviceName : null; //表示按设备来统计 row.Cells["colDeviceType"].Value = temp[0]; row.Cells["colAmount"].Value = g.Sum(it => it.Amount); }
private static VerizonRecord CreateRecordFromGrouping(IGrouping<string, VerizonRecord> g) { return new VerizonRecord { Date = g.OrderBy(r => r.Date).Last().Date, Description = g.First().Description, Minutes = g.Sum(r => r.Minutes), Number = g.Key }; }
private static XElement CoalesqueParagraphDeletedAndMoveFromParagraphMarksTransform( IGrouping<DeletedParagraphCollectionType, BlockContentInfo> g, IGrouping<DeletedParagraphCollectionType, BlockContentInfo> nextGroup) { // This function constructs a paragraph. XElement newParagraph = new XElement(W.p, nextGroup.First().ThisBlockContentElement.Elements(W.pPr), g.Select(z => CollapseParagraphTransform(z.ThisBlockContentElement)), nextGroup.Select(z => CollapseParagraphTransform(z.ThisBlockContentElement))); return newParagraph; }
private static PdfPTable CreateReportTable(IGrouping<GroupingByDate, Income> sales) { var dataTable = new PdfPTable(new float[] { 2, 1, 1.5f, 3.5f, 1 }); dataTable.WidthPercentage = 100f; Font dateFont = FontFactory.GetFont("Arial", 11); // var date = sales.Key.Year + "-" + // sales.Key.Month.ToString().PadLeft(2, '0') + "-" + // sales.Key.Day.ToString().PadLeft(2, '0'); var date = sales.First().Date.ToString("dd-MMM-yyyy"); var dateParagraph = new Paragraph("Date: " + date, dateFont); var dateCell = new PdfPCell(dateParagraph); dateCell.Padding = 5; dateCell.Colspan = 5; dateCell.BackgroundColor = new BaseColor(243, 243, 243); dataTable.AddCell(dateCell); var headerFont = FontFactory.GetFont("Arial", 10, Font.BOLD); var productCell = new PdfPCell(new Paragraph("Product", headerFont)); var quantityCell = new PdfPCell(new Paragraph("Quantity", headerFont)); var unitPriceCell = new PdfPCell(new Paragraph("Unit Price", headerFont)); var locationCell = new PdfPCell(new Paragraph("Location", headerFont)); var sumCell = new PdfPCell(new Paragraph("Sum", headerFont)); var headerCells = new PdfPCell[] { productCell, quantityCell, unitPriceCell, locationCell, sumCell }; foreach (var cell in headerCells) { cell.BackgroundColor = new BaseColor(200, 200, 200); cell.Padding = 5; } var headerRow = new PdfPRow(headerCells); dataTable.Rows.Add(headerRow); var dataFont = FontFactory.GetFont("Arial", 10); decimal total = 0; foreach (var sale in sales) { var productDataCell = new PdfPCell(new Paragraph(sale.Product.Name, dataFont)); var quantityDataCell = new PdfPCell(new Paragraph(sale.Quantity.ToString() + " " + sale.Product.Measure.Name, dataFont)); var unitPriceDataCell = new PdfPCell(new Paragraph(sale.SalePrice.ToString(), dataFont)); var locationDataCell = new PdfPCell(new Paragraph(sale.Supermarket.Name, dataFont)); var sum = ((decimal)sale.Quantity * sale.SalePrice); var sumDataCell = new PdfPCell(new Paragraph(sum.ToString(), dataFont)); var dataCells = new PdfPCell[] { productDataCell, quantityDataCell, unitPriceDataCell, locationDataCell, sumDataCell }; foreach (var cell in dataCells) { cell.Padding = 5; } var dataRow = new PdfPRow(dataCells); dataTable.Rows.Add(dataRow); total += sum; } Font totalSumFont = FontFactory.GetFont("Arial", 11, Font.BOLD); var footerTotal = new PdfPCell(new Paragraph("Total sum for " + date + ":", dataFont)); footerTotal.Colspan = 4; footerTotal.HorizontalAlignment = Element.ALIGN_RIGHT; footerTotal.Padding = 5; dataTable.AddCell(footerTotal); var footerSum = new PdfPCell(new Paragraph(total.ToString(), totalSumFont)); footerSum.Padding = 5; dataTable.AddCell(footerSum); return dataTable; }
/// <summary> /// Builds the class constructor. /// </summary> /// <param name="type">The type.</param> /// <param name="sb">The string builder.</param> /// <param name="options">The options.</param> private static void BuildClassConstructor(IGrouping<string, PropertyBag> type, StringBuilder sb, JsGeneratorOptions options) { if ( type.Any( p => (p.CollectionInnerTypes != null && p.CollectionInnerTypes.Any(q => !q.IsPrimitiveType)) || p.TransformablePropertyType == PropertyBag.TransformablePropertyTypeEnum.ReferenceType)) { sb.AppendLine( $"{options.OutputNamespace}.{Helpers.GetName(type.First().TypeName, options.ClassNameConstantsToRemove)} = function (cons, overrideObj) {{"); sb.AppendLine("\tif (!overrideObj) { overrideObj = { }; }"); sb.AppendLine("\tif (!cons) { cons = { }; }"); } else if (type.First().TypeDefinition.IsEnum) { sb.AppendLine( $"{options.OutputNamespace}.{Helpers.GetName(type.First().TypeName, options.ClassNameConstantsToRemove)} = {{"); } else { sb.AppendLine( $"{options.OutputNamespace}.{Helpers.GetName(type.First().TypeName, options.ClassNameConstantsToRemove)} = function (cons) {{"); sb.AppendLine("\tif (!cons) { cons = { }; }"); } }
private MutationNode GroupOrMutant(IGrouping<string, MutationTarget> byGroupGrouping) { if(byGroupGrouping.Count() == 1) { var mutationTarget = byGroupGrouping.First(); return new Mutant(mutationTarget.Id, mutationTarget); } else { return new MutantGroup(byGroupGrouping.Key, from mutationTarget in byGroupGrouping select new Mutant(mutationTarget.Id, mutationTarget) ); } }
private UpdatePart GetDeleteForPrimitiveListTabe(PrimitiveListTable primitiveListTable, IGrouping<Table, PropertyMapping> propGroup) { var mainTableContext = GetTableContext(primitiveListTable, "M"); var builder = new DeleteSqlBuilder(mainTableContext); var nextParameter = builder.GetNextParameter(); var equalPredicate = builder.GetEquality(mainTableContext, primitiveListTable.Columns.First().ColumnName, nextParameter); builder.Where(equalPredicate); return new UpdatePart { SqlString = builder.GetSql(), Parameters = { new Parameter { Name = nextParameter, Property = propGroup.First(z => z.DeclaredType != null).DeclaredType.Tables.OfType<EntityTable>().First().IdentityColumn} } }; }
private void _write(IGrouping<int, SentenceErrors> errorsGroup, LinguisticObjectType type) { //if (errorsGroup.Count() != 1) // throw new Exception("для одного предложения объектов ошибок одного типа должно быть ровно 1"); XlHelper.AddMargin(); var group = errorsGroup.First(errors => errors.ErrorObjects.ContainsKey(type)); var errorObjects = group.ErrorObjects[type]; _writeHeader(group.Sentence, type, errorsGroup.Key, errorObjects.Count()); _writeBody(errorObjects); }
private void WriteAssembly(IGrouping<string, DeclaredSymbolInfo> symbolsInAssembly) { WriteLine("<div class=\"resultGroup\">"); WriteLine("<div class=\"resultGroupHeader\" onClick=\"toggle(this, '{0}');\">", symbolsInAssembly.Key); string assemblyHeader = symbolsInAssembly.Key; ////assemblyHeader = assemblyHeader + " (" + symbolsInAssembly.Count().ToString() + ")"; WriteLine("<div class=\"resultGroupAssemblyName\">{0}</div>", assemblyHeader); WriteLine("<div class=\"resultGroupProjectPath\">{0}</div>", Markup.HtmlEscape(symbolsInAssembly.First().ProjectFilePath)); WriteLine("</div>"); WriteLine("<div id=\"{0}\">", symbolsInAssembly.Key); foreach (var symbol in symbolsInAssembly) { Markup.WriteSymbol(symbol, sb); } WriteLine("</div></div>"); }
private static OptionSource ResolvePrecedence(IGrouping<string, OptionSource> optionSources) { //go through and pick one based on your rules! return optionSources.First(); }
public ActivityEditorVm( Model.Task task, Dal.SoheilEdmContext uow, IGrouping<Model.Activity, Model.StateStationActivity> ssaGroup) : base(ssaGroup.Key) { Message = new Common.SoheilException.EmbeddedException(); if (!ssaGroup.Any()) { Message.AddEmbeddedException("فعالیتی وجود ندارد"); return; } //make ProcessList self-aware of all changes ProcessList.CollectionChanged += (s, e) => { if (e.NewItems != null) foreach (ProcessEditorVm processVm in e.NewItems) { ProcessList_Added(processVm); } }; //Add Choices foreach (var choice in ssaGroup.OrderBy(ssa => ssa.ManHour)) { Choices.Add(new ChoiceEditorVm(choice)); } //Add existing processes foreach (var process in task.Processes.Where(x => x.StateStationActivity.Activity.Id == ssaGroup.Key.Id)) { ProcessList.Add(new ProcessEditorVm(process, Model, uow)); } //Add process command AddProcessCommand = new Commands.Command(o => { DateTime dt; if (GetTaskStart == null) dt = ProcessList.Any() ? ProcessList .Where(x => x.ActivityModel.Id == ssaGroup.Key.Id) .Max(x => x.Model.EndDateTime) : task.StartDateTime; else dt = GetTaskStart(); var minMH = ssaGroup.Min(x => x.ManHour); var processVm = new ProcessEditorVm( new Model.Process { StartDateTime = dt, EndDateTime = dt, StateStationActivity = ssaGroup.First(x=>x.ManHour == minMH), TargetCount = 0, Task = task, }, Model, uow);//activity Model is set here ProcessList.Add(processVm); processVm.IsSelected = true; }); }
private IEnumerable<QuizInfoForDb> CreateQuizInfo(Course course, int slideIndex, IGrouping<string, QuizAnswer> answer) { var slide = (QuizSlide)course.Slides[slideIndex]; var block = slide.GetBlockById(answer.Key); if (block is FillInBlock) return CreateQuizInfoForDb(block as FillInBlock, answer.First().Text); if (block is ChoiceBlock) return CreateQuizInfoForDb(block as ChoiceBlock, answer); return CreateQuizInfoForDb(block as IsTrueBlock, answer); }
private IEnumerable<QuizInfoForDb> CreateQuizInfoForDb(IsTrueBlock isTrueBlock, IGrouping<string, QuizAnswer> data) { var isTrue = isTrueBlock.IsRight(data.First().ItemId); return new List<QuizInfoForDb> { new QuizInfoForDb { QuizId = isTrueBlock.Id, ItemId = null, IsRightAnswer = isTrue, Text = data.First().ItemId, QuizType = typeof(IsTrueBlock), IsRightQuizBlock = isTrue } }; }
private IEnumerable<QuizInfoForDb> CreateQuizInfoForDb(ChoiceBlock choiceBlock, IGrouping<string, QuizAnswer> answers) { if (!choiceBlock.Multiple) { var answerItemId = answers.First().ItemId; var isTrue = choiceBlock.Items.First(x => x.Id == answerItemId).IsCorrect; return new List<QuizInfoForDb> { new QuizInfoForDb { QuizId = choiceBlock.Id, ItemId = answerItemId, IsRightAnswer = isTrue, Text = null, QuizType = typeof (ChoiceBlock), IsRightQuizBlock = isTrue } }; } var ans = answers.Select(x => x.ItemId).ToList() .Select(x => new QuizInfoForDb { QuizId = choiceBlock.Id, IsRightAnswer = choiceBlock.Items.Where(y => y.IsCorrect).Any(y => y.Id == x), ItemId = x, Text = null, QuizType = typeof(ChoiceBlock), IsRightQuizBlock = false }).ToList(); var isRightQuizBlock = ans.All(x => x.IsRightAnswer) && choiceBlock.Items.Where(x => x.IsCorrect) .Select(x => x.Id) .All(x => ans.Where(y => y.IsRightAnswer).Select(y => y.ItemId).Contains(x)); foreach (var info in ans) info.IsRightQuizBlock = isRightQuizBlock; return ans; }
private static Completion CreateCompletion(ITextSnapshot snapshot, IGrouping<string, Protocol.Response.AutocompleteResponse.Completion> i) { var ret = new Completion(i.Key, i.First().completionText, GetDescription(i), GetImageSource(i.First()), null); ret.Properties.AddProperty(typeof(ITrackingSpan), GetReplacementSpanFromCompletions(snapshot, i.First())); return ret; }