internal static void MainSlow() { // Sets the Console to read from string //Console.SetIn(new StringReader(Test001)); int n = int.Parse(Console.ReadLine()); frames = new List<int[]>(n); perm = new int[n][]; used = new bool[n]; for (int i = 0; i < n; i++) { var frame = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray(); if (frame.Length != 2) { throw new ArgumentException("Frames must have two dimensions!"); } frames.Add(frame); } frames = frames.OrderBy(f => f[0]).ThenBy(f => f[1]).ToList(); Permutate(0, n); Console.WriteLine(count); Console.WriteLine(string.Join(Environment.NewLine, allPerms.OrderBy(f => f))); }
private IList<IPriceValue> GetDiscountPrices(IList<IPriceValue> prices, MarketId marketId, Currency currency) { currency = GetCurrency(currency, marketId); var priceValues = new List<IPriceValue>(); _promotionHelper.Reset(); foreach (var entry in GetEntries(prices)) { var price = prices .OrderBy(x => x.UnitPrice.Amount) .FirstOrDefault(x => x.CatalogKey.CatalogEntryCode.Equals(entry.Code) && x.UnitPrice.Currency.Equals(currency)); if (price == null) { continue; } priceValues.Add(_promotionEntryService.GetDiscountPrice( price, entry, currency, _promotionHelper)); } return priceValues; }
public void VisaData(IList<AktivPeriod> perioder) { panel1.Controls.Clear(); double pixlarPerDygn = 1000;// (double)panel1.Width; var förstaTimme = perioder.OrderBy(o => o.Starttid.Hour).FirstOrDefault().Starttid.Hour; var sistaTimme = perioder.OrderBy(o => o.Starttid.Hour).LastOrDefault().Starttid.Hour; var daghöjd = 30; var marginal = 10; var vänsterMarginal = 120; var minutlängd = (pixlarPerDygn - vänsterMarginal) / (sistaTimme - förstaTimme) / 60; // pixlarPerDygn / 24 / 60; var position = 0; for (int timme = förstaTimme; timme <= sistaTimme; timme++) { var timstreck = new TimMarkering(timme); timstreck.Top = 0; timstreck.Left = (int)(position * minutlängd * 60) + vänsterMarginal; panel1.Controls.Add(timstreck); position++; } var y = marginal + daghöjd; foreach (var period in perioder.OrderByDescending(o => o.Starttid).GroupBy(o => o.Starttid.Date).Select(o => new { Datum = o.Key, Perioder = o })) { var daglabel = new Label(); daglabel.Top = y; daglabel.Left = marginal; daglabel.Text = period.Datum.ToString("dddd, d MMM"); panel1.Controls.Add(daglabel); foreach (var item in period.Perioder) { var aktivitet = new Aktivitetsmarkering(item); aktivitet.BackColor = System.Drawing.Color.Blue; aktivitet.Top = y; aktivitet.Height = daghöjd; aktivitet.Width = (int)(minutlängd * item.Tidsmängd.TotalMinutes); if (aktivitet.Width == 0) aktivitet.Width = 1; aktivitet.Left = (int)(item.Starttid.Subtract(period.Datum).TotalMinutes * minutlängd) + vänsterMarginal - (int)(förstaTimme * 60 * minutlängd); panel1.Controls.Add(aktivitet); } y += daghöjd + marginal; } }
protected void Page_Init(object sender, EventArgs e) { Drugs = Lib.Data.Drug.FindAll(); SelectedDrugs = Lib.Systems.Lists.GetMyDrugs(); AvailableDrugs = new List<Lib.Data.Drug>(); foreach (var d in Drugs) { bool found = false; for (int i = 0; i < SelectedDrugs.Count; i++) { if (d.ID.Value == SelectedDrugs[i].ID.Value) { found = true; break; } } if (found) continue; AvailableDrugs.Add(d); } SelectedDrugs = SelectedDrugs.OrderBy(l => l.GenericName).ToList(); AvailableDrugs = AvailableDrugs.OrderBy(l => l.GenericName).ToList(); Eocs = _complianceSvc.GetEocs().ToList(); }
public void GuardarAsignaciones(IList<int> ordenesVenta, IList<Usuario> asistentes) { try { var transactionOptions = new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }; using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) { foreach (var idOrdenVenta in ordenesVenta) { var ordenVenta = _orderVentaDA.ObtenerPorID(idOrdenVenta); var asistenteConMenorCarga = asistentes.OrderBy(p => p.CantidadOV).FirstOrDefault(); if (asistenteConMenorCarga != null) { asistenteConMenorCarga.CantidadOV++; ordenVenta.Estado = Constantes.EstadoOrdenVenta.Asignado; ordenVenta.AsistentePlaneamiento = asistenteConMenorCarga; _orderVentaDA.AsignarAsistentePlaneamiento(ordenVenta); } } transactionScope.Complete(); } } catch (Exception ex) { throw ThrowException(ex, MethodBase.GetCurrentMethod().Name); } }
/// <summary> /// Exports the provided questions in CSV format: category,question,answer /// </summary> /// <param name="questions"></param> /// <returns></returns> public static string Export(IList<Question> questions) { StringBuilder builder = new StringBuilder(); foreach (Question question in questions.OrderBy(q => q.Category.Name)) { #if LOGGING builder.AppendLine(string.Format("{0},{1},{2},{3}", question.Category.Name.Replace(",", "~"), question.Title.Replace(",", "~"), question.Answer.Replace(",", "~"), question.NextAskOn.ToShortDateString()) ); #else builder.AppendLine(string.Format("{0},{1},{2}", question.Category.Name.Replace(",","~"), question.Title.Replace(",","~"), question.Answer.Replace(",","~")) ); #endif } return builder.ToString(); }
/// <summary> /// Returns the next machine to schedule. /// </summary> /// <param name="next">Next</param> /// <param name="choices">Choices</param> /// <param name="current">Curent</param> /// <returns>Boolean</returns> public virtual bool TryGetNext(out MachineInfo next, IList<MachineInfo> choices, MachineInfo current) { var machines = choices.OrderBy(mi => mi.Machine.Id.Value).ToList(); var currentMachineIdx = machines.IndexOf(current); var orderedMachines = machines.GetRange(currentMachineIdx, machines.Count - currentMachineIdx); if (currentMachineIdx != 0) { orderedMachines.AddRange(machines.GetRange(0, currentMachineIdx)); } var availableMachines = orderedMachines.Where( mi => mi.IsEnabled && !mi.IsBlocked && !mi.IsWaiting).ToList(); if (availableMachines.Count == 0) { next = null; return false; } int idx = 0; while (this.RemainingDelays.Count > 0 && this.ExploredSteps == this.RemainingDelays[0]) { idx = (idx + 1) % availableMachines.Count; this.RemainingDelays.RemoveAt(0); IO.PrintLine("<DelayLog> Inserted delay, '{0}' remaining.", this.RemainingDelays.Count); } next = availableMachines[idx]; this.ExploredSteps++; return true; }
/// <summary> /// Sorts the object collection by object Type, then by name of object. /// This makes for an easy compare of two different memory snapshots /// </summary> /// <returns></returns> public static IList<Object> Sort(IList<Object> unSorted) { if (unSorted == null) return null; IList<Object> sorted = unSorted.OrderBy(x => x.GetType().ToString()).ThenBy(x => x.name).ToList(); return sorted; }
/// <summary> /// Benchmarks and compares the execution time stats of the given algorithms. /// </summary> /// <param name="numberOfIterations">The number of iterations to run.</param> /// <param name="reportIndividualIterations"> /// <para>If set to <c>true</c>, reports individual iteration stats; if <c>false</c>, reports average iteration stats.</para> /// <para>If the algorithm runs really fast, the floating point calculations will come out to zero, so you will want to set this to <c>false</c>.</para> /// </param> /// <param name="algorithms">The algorithms to compare.</param> /// <returns>The list of algorithms, sorted from fastest to slowest, with their <see cref="Algorithm.ExecutionTime"/> property set.</returns> public static IList<Algorithm> CompareExecutionTime(int numberOfIterations, bool reportIndividualIterations, IList<Algorithm> algorithms) { if (algorithms == null || !algorithms.Any()) { throw new ArgumentNullException("algorithms"); } foreach (Algorithm algorithm in algorithms) { ("Running " + algorithm.Name).Dump(); algorithm.BenchmarkAndCacheExecutionTime(numberOfIterations, reportIndividualIterations); "\tDone".Dump(); } "".Dump(); ("Total iterations: " + numberOfIterations.ToString("n0")).Dump(); "".Dump(); algorithms = algorithms.OrderBy(algorithm => algorithm.ExecutionTime.Average).ToList(); for (int i = 0; i < algorithms.Count; i++) { DumpAlgorithmStats(algorithms[i], i + 1 < algorithms.Count ? algorithms[i + 1] : null, reportIndividualIterations); } return algorithms; }
public frmRefundTypeMappings(IList<RefundTypeMappingDTO> refundMappingTypeDTOs) { InitializeComponent(); checkBoxIssueRefundCheck.DataBindings.Add(new Binding("Checked", refundTypeMappingDTOBindingSource, "IssueCheck", true, DataSourceUpdateMode.OnPropertyChanged)); checkBoxEnabled.DataBindings.Add(new Binding("Checked", refundTypeMappingDTOBindingSource, "Enabled", true, DataSourceUpdateMode.OnPropertyChanged)); checkBoxIssueRefundCheck.DataBindings.Add(new Binding("Enabled", refundTypeMappingDTOBindingSource, "Enabled", true, DataSourceUpdateMode.OnPropertyChanged)); comboBoxCheckRecipient.DataBindings.Add(new Binding("Enabled", refundTypeMappingDTOBindingSource, "EnableCheckField", true, DataSourceUpdateMode.OnPropertyChanged)); comboBoxCheckRecipient.DataBindings.Add(new Binding("SelectedItem", refundTypeMappingDTOBindingSource, "RefundCheckRecipient")); comboBoxQBFrom.DataBindings.Add(new Binding("Enabled", refundTypeMappingDTOBindingSource, "EnableFromField", true, DataSourceUpdateMode.OnPropertyChanged)); comboBoxQBPaymentType.DataBindings.Add(new Binding("Enabled", refundTypeMappingDTOBindingSource, "EnableQuickbooksPayTypeField", true, DataSourceUpdateMode.OnPropertyChanged)); comboBoxQBIncomeAccount.DataBindings.Add(new Binding("Enabled", refundTypeMappingDTOBindingSource, "Enabled", true, DataSourceUpdateMode.OnPropertyChanged)); comboBoxRefundBankAccount.DataBindings.Add(new Binding("Enabled", refundTypeMappingDTOBindingSource, "EnableBankAccountField", true, DataSourceUpdateMode.OnPropertyChanged)); comboBoxCheckRecipient.DataSource = Enum.GetValues(typeof(RefundCheckRecipient)); Configuration configuration = UserSettings.getInstance().Configuration; quickbooksPaytypeBindingSource.DataSource = configuration.QuickbooksPaytypes; quickbooksCustomerBindingSource.DataSource = configuration.QuickbooksCustomers; quickbooksIncomeAccountBindingSource.DataSource = configuration.QuickbooksIncomeAccounts; quickbooksBankAccountBindingSource.DataSource = configuration.QuickbooksBankAccounts; refundTypeMappingDTOBindingSource.DataSource = refundMappingTypeDTOs.OrderBy(x => x.EaglesoftAdjustment); }
/// <summary> /// Bir kelimenin çözümleri ile aranan çözümlerin aynı sayıda ve bire bir aynı /// olup olmadığını kontrol eder. Aranan çözümlerin hangi sırada verildiği önemli değildir. /// </summary> /// <param name="token">kelime</param> /// <param name="expectedAnalyses">aranan ve olması gereken çözümlerin tamamı</param> public static void AllAnalysesEqual(string token, IList<string> expectedAnalyses) { IList<Word> words = Analyzer.Analyze(token); IList<string> actualAnalyses = words.Select(word => word.Analysis).ToList(); bool equalIgnoreOrder = actualAnalyses.OrderBy(t => t).SequenceEqual(expectedAnalyses.OrderBy(t => t)); Assert.True(equalIgnoreOrder); }
public void Init(dynamic pedal, IList<ToolkitKnob> knobs) { var sortedKnobs = knobs.OrderBy(k => k.Index).ToList(); tableLayoutPanel.RowCount = knobs.Count; for (var i = 0; i < sortedKnobs.Count; i++) { var knob = sortedKnobs[i]; var label = new Label(); tableLayoutPanel.Controls.Add(label, 0, i); if (knob.Name != null) { var name = knob.Name; var niceName = nameParser.Match(name); if(niceName.Groups.Count > 1) { name = niceName.Groups[1].Value; } label.Text = name; } label.Anchor = AnchorStyles.Left; var numericControl = new NumericUpDownFixed(); tableLayoutPanel.Controls.Add(numericControl, 1, i); numericControl.DecimalPlaces = 2; numericControl.Minimum = (decimal)knob.MinValue; numericControl.Maximum = (decimal)knob.MaxValue; numericControl.Increment = (decimal)knob.ValueStep; numericControl.Value = Math.Min((decimal)pedal.KnobValues[knob.Key], numericControl.Maximum); numericControl.ValueChanged += (obj, args) => pedal.KnobValues[knob.Key] = (float)Math.Min(numericControl.Value, numericControl.Maximum); } }
void AssertEquals(IList<IList<int>> firstList, IList<IList<int>> secondList) { Assert.AreEqual(firstList.Count(), secondList.Count()); firstList = firstList .OrderBy(list => list[0]) .ThenBy(list => list[1]) .ThenBy(list => list[2]) .ToList(); secondList = secondList .OrderBy(list => list[0]) .ThenBy(list => list[1]) .ThenBy(list => list[2]) .ToList(); Assert.IsTrue(firstList .Zip(secondList , (firstSubList, secondeSubList) => firstSubList .Zip(secondeSubList , (first, second) => first == second) .All(item => item)) .All(item => item)); ; }
public ProductViewModel(Product product, IList<Category> categories) : this() { this.ProductId = product.Id; this.ProductGuid = product.Guid; this.Code = product.Code; this.Title = product.Title; this.Description = product.Description; this.Keywords = product.Keywords; this.Cost = product.Cost; this.Type = product.Type; this.IsFeatured = product.IsFeatured; this.ImageUrls = product.Images.Select(o => new ProductImageViewModel(o)).ToList(); foreach (Category category in categories.OrderBy(o => o.DisplayName)) { CategoryViewModel categoryViewModel = new CategoryViewModel(category); categoryViewModel.Selected = product.Categories.Any(o => o.Id == category.Id); foreach(var child in category.Children) { categoryViewModel.Children.First(o => o.Id == child.Id).Selected = product.Categories.Any(o => o.Id == category.Id && o.Children.Any(x => x.Id == child.Id)); } this.Categories.Add(categoryViewModel); } }
public ZapperProcessor(FileZapperSettings settings = null, IList<IZapperPhase> phases = null) { _log.Info("Initializing"); ZapperFiles = new ConcurrentDictionary<string, ZapperFile>(); ZapperFilesDeleted = new ConcurrentDictionary<string, ZapperFileDeleted>(); if (settings == null) { settings = new FileZapperSettings(); settings.Load(); } Settings = settings; if (phases != null) { foreach (var phase in phases) { phase.ZapperProcessor = this; } _phases = phases.OrderBy(x => x.PhaseOrder); } else { List<IZapperPhase> allphases = new List<IZapperPhase>(); allphases.Add(new PhaseCleanup { PhaseOrder = 1, ZapperProcessor = this, IsInitialPhase = true }); allphases.Add(new PhaseParseFilesystem { PhaseOrder = 2, ZapperProcessor = this }); allphases.Add(new PhaseCalculateSamples { PhaseOrder = 3, ZapperProcessor = this }); allphases.Add(new PhaseCalculateHashes { PhaseOrder = 4, ZapperProcessor = this }); allphases.Add(new PhaseRemoveDuplicates { PhaseOrder = 5, ZapperProcessor = this }); _phases = allphases.OrderBy(x => x.PhaseOrder); } }
public IList<NameModel> SortNameByLastAndFirstName(IList<NameModel> unsortedNames) { if (unsortedNames != null && unsortedNames.Count > 0) { return unsortedNames.OrderBy(n => n.LastName).ThenBy(n => n.FirstName).ToList(); } return null; }
public FieldsGenerator(ModelBase model, IList<Field> fields, string padding = "") : base(model) { foreach (Field field in fields.OrderBy(x => x.Name)) { GenerateField(field, padding); } }
public void CreateFileFromList(string baseFilename, IList<int> markers) { var markerFile = GetMarkerFilename(baseFilename); using (var sw = File.CreateText(markerFile)) { foreach (var mark in markers.OrderBy(x => x)) sw.WriteLine(mark.ToString()); } }
private void CarregarPrimeiroAcesso() { txtNome.Focus(); ListGrupoVisao = new ManterGrupoVisao().GetAll(); grdGrupoVisoes.DataSource = ListGrupoVisao.OrderBy(l => l.Nome).ToList(); grdGrupoVisoes.DataBind(); }
public void Carregar(IList<TicketDeOrcamentoPessoal> ticketsDeOrcamentoPessoal) { TodosOsTicketsCadastrados = ticketsDeOrcamentoPessoal; rptTickets.DataSource = ticketsDeOrcamentoPessoal.OrderBy(x => x.Descricao); rptTickets.DataBind(); CarregarAcordoConvencao(); }
/// <summary> /// Employee View Model Constructor. /// Will load all employees from excel /// </summary> public EmployeeViewModel() { RMA_Roots.AppConfig.LoadAppConfiguration("EmployeeOverview"); _sitzplanSource = new BitmapImage(new Uri(@"D:\sitzplan.png")); var import = new Import(); _employees = import.Employees; _employees = _employees.OrderBy(f => f.Vorname).ToList(); _showSeatingVisibility = Visibility.Hidden; }
public void Insert(IList<string> values) { if (values != null && values.Count > 0) { foreach (string str in values.OrderBy(i => i)) { flow.Controls.Add(NewLabel(str)); } } }
public void FormOrgList(IList<MyJobLeads.DomainModel.Entities.Organization> Organizations) { OrganizationList = Organizations .OrderBy(x => x.Name) .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList(); }
public void SaveAllProperties(IList<KeyValuePair<string, object>> output) { IEnumerable<KeyValuePair<string, object>> sorted = output.OrderBy(kvp => kvp.Key); this.properties = sorted.ToList(); foreach (var item in output) { this.LoadProperty(item.Key, item.Value.ToString()); } }
public void Init() { _organizations = new List<Organization> { new Organization{ Id = 1, Name = "Pos #1", StatusId = (byte)Status.Approved, ParentId = 0, CreatedAt = DateTime.Now }, new Organization{ Id = 2, Name = "Pos #2", StatusId = (byte)Status.Approved, ParentId = 0, CreatedAt = DateTime.Now }, }; Organization pos1 = _organizations.OrderBy(x => x.Id).First(); Organization pos2 = _organizations.OrderBy(x => x.Id).Skip(1).First(); _categories = new List<Category> { new Category { Id = 2, Name = "Light alcohol", OrganizationId = pos1.Id, ParentId = 0, StatusId = (byte)Status.Approved, CategoryTypeId = 1 }, new Category { Id = 2, Name = "Food", OrganizationId = pos1.Id, ParentId = 0, StatusId = (byte)Status.Approved, CategoryTypeId = 1 }, new Category { Id = 3, Name = "Men shoes", OrganizationId = pos2.Id, ParentId = 0, StatusId = (byte)Status.Approved, CategoryTypeId = 1 }, new Category { Id = 4, Name = "Women shoes", OrganizationId = pos2.Id, ParentId = 0, StatusId = (byte)Status.Approved, CategoryTypeId = 1 }, new Category { Id = 5, Name = "Children shoes", OrganizationId = pos2.Id, ParentId = 0, StatusId = (byte)Status.Approved, CategoryTypeId = 1 } }; Category lightAlcohol = _categories.First(x => x.Name.Contains("Light alcohol")); Category food = _categories.First(x => x.Name.Equals("Food")); _products = new List<Product> { new Product { Id = 1, CategoryId = lightAlcohol.Id, InternalCode = "internal_001", Name = "Beer", PosId = pos1.Id, Price = 10m, StatusId = (byte)Status.Approved, Uid = "uid_0001", UserId = "TestUser", CreatedAt = DateTime.Now }, new Product { Id = 2, CategoryId = food.Id, InternalCode = "internal_002", Name = "Cheese", PosId = pos1.Id, Price = 15m, StatusId = (byte)Status.Approved, Uid = "uid_0002", UserId = "TestUser", CreatedAt = DateTime.Now }, new Product { Id = 3, CategoryId = lightAlcohol.Id, InternalCode = "internal_003", Name = "Beer light", PosId = pos1.Id, Price = 5m, StatusId = (byte)Status.Approved, Uid = "uid_0003", UserId = "TestUser", CreatedAt = DateTime.Now } }; _organizationRepository = new Mock<IOrganizationRepository>(); _organizationRepository.Setup(x => x.Organizations) .Returns(_organizations.AsQueryable()); _categoryMock = new Mock<ICategoryRepository>(); _categoryMock.Setup(x => x.Categories) .Returns(_categories.AsQueryable()); _productRepository = new Mock<IProductRepository>(); _productRepository.Setup(x => x.Products) .Returns(_products.AsQueryable()); _categoryController = new CategoryController( _categoryMock.Object, _organizationRepository.Object, _productRepository.Object); }
public TreeBuilderQueue(Dictionary<byte, long> dictionary) { this.itemList = new List<QueueItem>(); foreach (var b in dictionary) { itemList.Add(new QueueItem(new TreeNode(b.Key), b.Value)); } itemList = itemList.OrderBy(i => i.Priority).ToList(); }
private static string FormatReasons(IList<string> reasons) { reasons = reasons.OrderBy(x => x.First()).ToList(); var formatted = new StringBuilder(); //ul is rendered by episerver foreach (var reason in reasons) { formatted.AppendFormat("<li>{0}</li>", reason); } return formatted.ToString(); }
public WarInitializer(IList<UnitData> unitDatas, Area area, IList<Tuple<int, IList<Unit>, Area>> conquerInfo, PhaseCreator phaseCreator, string gamepath) { _units = unitDatas; _area = area; _conquerInfo = conquerInfo; _conquerInfo.OrderBy(conquer => conquer.Item1); _phaseCreator = phaseCreator; _gamePath = gamepath; }
public IEnumerable<Pairing> Shuffle(IList<Player> players) { ValidatePlayerCount(players); var pairings = new List<Pairing>(); var shuffled = players.OrderBy(i => Guid.NewGuid()).ToList(); for (var i = 0; i < shuffled.Count; i += 2) { pairings.Add(new Pairing(shuffled[i], shuffled[i + 1])); } return pairings; }
public int Count(IList<Tribe> initialtribes) { Wall wall = new Wall(); IList<Tribe> tribes = initialtribes.OrderBy(t => t.Day).ToList(); int counter = 0; int lastday = -1; while (tribes.Count > 0) { var tribe = tribes.First(); tribes.RemoveAt(0); if (lastday != tribe.Day) { wall.NewDay(); lastday = tribe.Day; } if (wall.Attack(tribe.West, tribe.East, tribe.Strength)) counter++; tribe.NewDay(); if (!tribe.CanAttack()) continue; int n = tribes.Count; if (n == 0 || tribes[n - 1].Day <= tribe.Day) { tribes.Add(tribe); continue; } bool added = false; for (int k = 0; k < n; k++) { if (tribes[k].Day > tribe.Day) { tribes.Insert(k, tribe); added = true; break; } } if (!added) tribes.Add(tribe); } return counter; }
public async Task <IList <Product> > SortProducts(IList <Product> products, string sortOption) { switch (sortOption.ToLower()) { case ProductSortHelper.LowToHigh: return(products?.OrderBy(x => x.Price).ToList()); case ProductSortHelper.HighToLow: return(products?.OrderByDescending(x => x.Price).ToList()); case ProductSortHelper.Ascending: return(products?.OrderBy(x => x.Name).ToList()); case ProductSortHelper.Descending: return(products?.OrderByDescending(x => x.Name).ToList()); case ProductSortHelper.Recommended: return(await SortProductsRecommendedByShoppingHistory(products)); } return(products); }
public Calendar(IList <CrontabSchedule> schedules, IList <Booking> bookings = null) { Schedules = schedules?.OrderBy(s => s.GetNextOccurrence(DateTime.UtcNow)).ToList() ?? new List <CrontabSchedule>(); foreach (var booking in bookings) { if (!AddBooking(booking)) { throw new Exception($"Cannot initialize Calendar with booking {booking}"); } } Console.WriteLine("Calender initialized with the following schedules:"); Console.WriteLine(string.Join(Environment.NewLine, Schedules)); Console.WriteLine("___________________________________________"); Console.WriteLine(); }
public RO2(Model.PCDoubleImpactCheck _pcdic) { InitializeComponent(); if (_pcdic == null) { return; } details = pcdicdManager.SelectByPCDoubleICId(_pcdic.PCDoubleImpactCheckID); this.DataSource = details.OrderBy(d => d.PCDoubleImpactCheckDetailDate).ToList(); //this.DataSource = _pcdic.Detail; //CompanyInfo this.lblCompanyName.Text = BL.Settings.CompanyChineseName; switch (_pcdic.PCDoubleImpactCheckType) { case 0: this.lblDataName.Text = Properties.Resources.CSAcjcsd; //this.xtcHengWen.Visible = false; //this.xtcJiaRe.Visible = false; //this.TCattrHotL.Visible = false; //this.TCattrHotR.Visible = false; //this.TCattrCoolL.Visible = false; //this.TCattrCoolR.Visible = false; break; case 1: this.lblDataName.Text = Properties.Resources.BSENcjcsd; //this.xtcJIaoLian.Visible = false; //this.TCattrJiaoLianL.Visible = false; //this.TCattrJiaoLianR.Visible = false; break; case 2: this.lblDataName.Text = Properties.Resources.ASNZScjcsd; //this.xtcJIaoLian.Visible = false; //this.TCattrJiaoLianL.Visible = false; //this.TCattrJiaoLianR.Visible = false; //this.xtcHengWen.Visible = false; //this.xtcJiaRe.Visible = false; //this.TCattrHotL.Visible = false; //this.TCattrHotR.Visible = false; //this.TCattrCoolL.Visible = false; //this.TCattrCoolR.Visible = false; break; default: break; } //this.lblPriteDate.Text += DateTime.Now.ToShortDateString(); //Control this.lblANSIPCImpactCheckID.Text = _pcdic.PCDoubleImpactCheckID; this.lblANSIPCImpactCheckDate.Text = _pcdic.PCDoubleImpactCheckDate.HasValue ? _pcdic.PCDoubleImpactCheckDate.Value.ToShortDateString() : ""; this.lblInvoiceCusXOId.Text = _pcdic.InvoiceCusXOId; this.lblPronoteHeaderId.Text = _pcdic.PronoteHeaderId; this.lblProduct.Text = _pcdic.Product == null ? "" : _pcdic.Product.ToString(); this.lblEmployee0.Text = _pcdic.Employee == null ? "" : _pcdic.Employee.ToString(); this.RTDescript.Text = _pcdic.PCDoubleImpactCheckDesc; this.lblCheckStandard.Text = _pcdic.CheckStandard; this.lblChongJiLiDu.Text = _pcdic.PowerImpact; this.lblInvoiceXOQuantity.Text = _pcdic.InvoiceXOQuantity.HasValue ? _pcdic.InvoiceXOQuantity.ToString() : ""; this.lblPCDoubleImpactCheckCount.Text = _pcdic.PCDoubleImpactCheckCount.HasValue ? _pcdic.PCDoubleImpactCheckCount.ToString() : ""; this.lbl_productunit.Text = _pcdic.ProductUnit == null ? "" : _pcdic.ProductUnit.ToString(); //this.lbl_CustomerProductName.Text = _pcdic.Product == null ? "" : _pcdic.Product.CustomerProductName; if (_pcdic.Product != null) { if (string.IsNullOrEmpty(_pcdic.Product.CustomerProductName)) { this.lbl_CustomerProductName.Text = CommonHelp.GetCustomerProductNameByPronoteHeaderId(_pcdic.PronoteHeaderId, _pcdic.ProductId); } else { this.lbl_CustomerProductName.Text = _pcdic.Product.CustomerProductName; } } //Details #region ¸ü¸ÄÏêϸÏÔʾ foreach (Model.PCDoubleImpactCheckDetail detail in details) { foreach (var a in detail.GetType().GetProperties()) { if (a.Name.IndexOf("attr") > -1) { if (a.GetValue(detail, null) != null) { switch (a.GetValue(detail, null).ToString()) { case "0": a.SetValue(detail, "¡Ì", null); break; case "1": a.SetValue(detail, "¡÷", null); break; case "2": a.SetValue(detail, "X", null); break; default: break; } } } } } #endregion this.TCPCDoubleImpactCheckDetailDate.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_PCDoubleImpactCheckDetailDate, "{0:yyyy-MM-dd HH:mm:ss}"); //this.TCattrJiaoLianL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrJiaoLianL); //this.TCattrJiaoLianR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrJiaoLianR); this.TCattrJPUpL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrJPUpL); this.TCattrJPUpR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrJPUpR); this.TCattrJPDownL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrJPDownL); this.TCattrJPDownR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrJPDownR); this.TCattrJPLeftL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrJPLeftL); this.TCattrJPLeftR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrJPLeftR); this.TCattrJPRightL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrJPRightL); this.TCattrJPRightR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrJPRightR); this.TCattrBiZhong.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrBiZhong); //this.DlblBiZhong.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrBiZhong); this.TCattrShangLiangL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrShangLiangL); this.TCattrShangLiangR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrShangLiangR); this.TCattrJPZYL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrJPZYL); this.TCattrJPZYR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrJPZYR); this.TCattrS_SZhongL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrS_SZhongL); this.TCattrS_SZhongR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrS_SZhongR); this.TCattrS_SShangL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrS_SShangL); this.TCattrS_SShangR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrS_SShangR); this.TCattrS_SXiaL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrS_SXiaL); this.TCattrS_SXiaR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrS_SXiaR); //this.TCattrHotL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrHotL); //this.TCattrHotR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrHotR); //this.TCattrCoolR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrCoolL); //this.TCattrCoolR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrCoolR); this.TCEmployee.DataBindings.Add("Text", this.DataSource, "Employee." + Model.Employee.PROPERTY_EMPLOYEENAME); this.lblAttrHeat30m.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrHeat30m); this.xrLBanBie.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_PCDoubleImpactCheckBanBie); this.lblHML.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrHM500gL); this.lblHMR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrHM500gR); this.lblZhuiqiuL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrZhuiQiu68gL); this.lblZhuiqiuR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrZhuiQiu68gR); this.lblChuantouL.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrChuanTou44_2gL); this.lblChuantouR.DataBindings.Add("Text", this.DataSource, Model.PCDoubleImpactCheckDetail.PRO_attrChuanTou44_2gR); }
public async Task OnGetAsync(string sort) { Sort = sort; await AppUserService.Get(User); Homes = new List <HomeModel>(); var users = await DataContext.AppUsers.ToListAsync(); var homeRecords = await DataContext.HomeReviewHomes .Include(h => h.CreatedBy) .Include(h => h.ModifiedBy).ToListAsync(); foreach (var home in homeRecords) { var homeModel = new HomeModel { Id = home.Id, Available = home.Available, Finished = home.Finished, Address = home.Address, HouseNumber = home.HouseNumber, StreetName = home.StreetName, City = home.City, State = home.State, Zip = $"{home.Zip:00000}", Score = HomeService.HomeScore(home), CostScore = HomeService.CostScore(home), SpaceScore = HomeService.SpaceScore(home), BathroomsScore = HomeService.BathroomsScore(home), BedroomsScore = HomeService.BedroomsScore(home), Updated = home.Modified, Created = home.Created, UpdatedBy = home.ModifiedBy.FirstName, CreatedBy = home.CreatedBy.FirstName, UserScores = new List <UserScoreModel>() }; Homes.Add(homeModel); foreach (var user in users) { homeModel.UserScores.Add(new UserScoreModel { Name = user.FirstName, Score = HomeService.UserScore(home, user) }); } homeModel.BaseScore = HomeService.BaseScore(home); } switch (Sort) { default: case "score": Homes = Homes.OrderByDescending(o => o.Score).ToList(); break; case "updated": Homes = Homes.OrderByDescending(o => o.Updated).ToList(); break; case "created": Homes = Homes.OrderByDescending(o => o.Created).ToList(); break; case "address": Homes = Homes .OrderBy(o => o.City) .ThenBy(o => o.StreetName) .ThenBy(o => o.HouseNumber) .ToList(); break; } }
/// <summary> /// Find the method that supports the amount of parameters provided /// </summary> private static MethodInfo GetClosestMethod(IList <MethodInfo> methods, IList <ITokenParameter> tokenParameters) { if (methods.Count == 0) { return(null); } if (methods.Count == 1) { return(methods[0]); } var ordered = methods.OrderBy(m => m.GetParameters().Length); if (tokenParameters.Count == 0) { return(ordered.First()); } MethodInfo lastMethod = null; var compatibleMethods = new Dictionary <int, MethodInfo>(); foreach (var method in ordered) { lastMethod = method; var methodParameters = method.GetParameters(); var requiredParameters = methodParameters.Length; if (requiredParameters > 0 && IsParamsArray(methodParameters.Last())) { // Params array can be not provided requiredParameters--; } if (tokenParameters.Count < requiredParameters) { continue; } var matched = true; var exactMatches = 0; for (var i = 0; i < tokenParameters.Count; i++) { if (methodParameters.Length <= i) { // The method contains less parameters (and no params array) than provided matched = false; break; } var methodParameter = methodParameters[i]; var tokenParameterType = tokenParameters[i].GetParameterType(); // Match either the same parameter type matched = methodParameter.ParameterType == tokenParameterType; if (matched) { exactMatches++; } else if (IsParamsArray(methodParameter)) { matched = methodParameter.ParameterType == typeof(object[]) || methodParameter.ParameterType.GetElementType() == tokenParameterType; // The method has params array, no further parameters are going to be defined break; } else { if (IsNumeric(methodParameter.ParameterType) && IsNumeric(tokenParameterType)) { // Acount for implicit conversion of numeric values as an exact match exactMatches++; } else if (!methodParameter.ParameterType.GetTypeInfo().IsAssignableFrom(tokenParameterType)) { // Not a match break; } // Is assignable to the parameter type matched = true; } } if (matched) { compatibleMethods[exactMatches] = method; } } // Attempt to use the method with the higher number of matches or the last one return(compatibleMethods.OrderByDescending(kv => kv.Key).Select(kv => kv.Value).FirstOrDefault() ?? lastMethod); }
public IActionResult Index() { //return View(instituicoes); return(View(instituicoes.OrderBy(i => i.Nome))); }
public IEnumerable <string> GetHttpMethodConstraints() { return(_httpMethods.OrderBy(x => x)); }
/// <summary> /// Small Image /// </summary> /// <param name="images"></param> /// <returns></returns> public static ImageResponse GetSmallImage(this IList <ImageResponse> images) => images?.OrderBy(o => o.Height * o.Width)?.FirstOrDefault();
protected override bool GetData(DataTable table, object query) { bool result = false; int i = -1; Modes.BusinessLogic.IGenObject igo; table.Reset(); table.Locale = System.Globalization.CultureInfo.CurrentCulture; string [] args = ((string)query).Split(';'); //Logging.Logg().Debug("DbMCInterface::GetData () - " + query + "...", Logging.INDEX_MESSAGE.NOT_SET); switch (args[0]) { case "InitIGO": //InitIGO (arg); break; case "PPBR": table.Columns.Add("DATE_PBR", typeof(DateTime)); table.Columns.Add("WR_DATE_TIME", typeof(DateTime)); table.Columns.Add("PBR", typeof(double)); table.Columns.Add("Pmin", typeof(double)); table.Columns.Add("Pmax", typeof(double)); table.Columns.Add("PBR_NUMBER", typeof(string)); //table.Columns.Add("ID_COMPONENT", typeof(Int32)); ////Вариант №1 //PPBR_Record ppbr = null; //SortedList<DateTime, PPBR_Record> srtListPPBR = new SortedList<DateTime,PPBR_Record> (); //Вариант №2 DataRow [] ppbr_rows = null; DateTime date = DateTime.FromOADate(Double.Parse(args [2])); string [] idsInner = args[1].Split(','); bool valid = false; int idInner = -1; IList <PlanValueItem> listPVI = null; DateTime dateCurrent; for (i = 0; i < idsInner.Length; i++) { valid = Int32.TryParse(idsInner[i], out idInner); if (valid == false) { continue; } else { ; } igo = findIGO(idInner); if (igo == null) { igo = addIGO(idInner); } else { ; } if (!(igo == null)) { result = true; try { listPVI = m_MCApi.GetPlanValuesActual(date.LocalHqToSystemEx(), date.AddDays(1).LocalHqToSystemEx(), igo); } catch (Exception e) { Logging.Logg().Exception(e, @"DbMCInterface::GetData () - GetPlanValuesActual () ...", Logging.INDEX_MESSAGE.NOT_SET); Console.WriteLine(" ОШИБКА получения значений!"); needReconnect = true; result = false; } if (result == true) { if (listPVI.Count == 0) { Console.WriteLine(" Нет параметров генерации!"); } else { ; } } else { //ОШИБКА получения значений! break; } foreach (PlanValueItem pvi in listPVI.OrderBy(RRR => RRR.DT)) { //Console.WriteLine(" " + pvi.DT.SystemToLocalHqEx().ToString() + " " + // pvi.Type.ToString() + " [" + m_listPFI[pvi.ObjFactor].Description + "] " + // /*it.ObjName это id генерирующего объекта*/ // m_listPFI[pvi.ObjFactor].Name + " =" + pvi.Value.ToString()); dateCurrent = pvi.DT.SystemToLocalHqEx(); //Получение записи с другими параметрами за это время ////Вариант №1 //if (srtListPPBR.ContainsKey(dateCurrent)) // ppbr = srtListPPBR.First(item => item.Key == dateCurrent).Value; //else // ; //Вариант №2 if (table.Rows.Count > 0) { ppbr_rows = table.Select("DATE_PBR='" + dateCurrent.ToString() + "'"); } else { ; } //Обработка получения записи ////Вариант №1 //if (ppbr == null) //{ // ppbr = new PPBR_Record(); // ppbr.date_time = dateCurrent; // ppbr.wr_date_time = DateTime.Now; // ppbr.PBR_number = pvi.Type.ToString(); // //ppbr.idInner = igo.IdInner; //??? Для TEC5_TG36 2 объекта (TG34 + TG56), т.е. 2 IGO // //После добавления можно продолжать модифицировать экземпляр класса - в коллекции та же самая ссылка хранится. // srtListPPBR.Add(dateCurrent, ppbr); //} //else // ; //Вариант №2 if ((ppbr_rows == null) || (ppbr_rows.Length == 0)) { table.Rows.Add(new object[] { dateCurrent, DateTime.Now, 0.0, 0.0, 0.0, pvi.Type.ToString() /*, igo.IdInner*/ }); ppbr_rows = table.Select("DATE_PBR='" + dateCurrent.ToString() + "'"); } else { ; } ppbr_rows [0]["PBR_NUMBER"] = pvi.Type.ToString(); switch (m_listPFI[pvi.ObjFactor].Id) { case 0: //else.ppbr.pbr = pvi.Value; //Вариант №1 ppbr_rows [0]["PBR"] = (double)ppbr_rows [0]["PBR"] + pvi.Value; //Вариант №2 break; case 1: //ppbr.pmin = pvi.Value; //Вариант №1 ppbr_rows [0]["PMIN"] = (double)ppbr_rows [0]["PMIN"] + pvi.Value; //Вариант №2 break; case 2: //ppbr.pmax = pvi.Value; //Вариант №1 ppbr_rows [0]["PMAX"] = (double)ppbr_rows [0]["PMAX"] + pvi.Value; //Вариант №2 break; default: break; } } } else { result = false; //igo == null } } break; default: break; } return(result); }
/// <summary> /// 输出模型 /// </summary> /// <param name="quality"></param> /// <param name="item"></param> /// <param name="hasCollect"></param> /// <param name="consultationfile"></param> /// <param name="reply"></param> /// <param name="doctor"></param> /// <param name="eva"></param> /// <param name="serverid"></param> /// <param name="IIIness"></param> /// <param name="paramlist"></param> public QualityControlManageOutDetail(QualityControlManage quality, YaeherConsultation item, bool hasCollect, IList <ReplyDetail> consultationfile, IList <ReplyDetail> reply, YaeherUser doctor, IList <ConsultationEvaluation> eva, int serverid, int IIIness, List <SystemParameter> paramlist) { Id = quality.Id; Sex = JsonHelper.FromJson <YaeherPatientLeaguerInfo>(item.PatientJSON).Sex; QualityLevel = quality.QualityLevel; RepayIllnessDescription = quality.RepayIllnessDescription; ReplyState = quality.ReplyState; IsReturnVisit = item.IsReturnVisit; HasCollect = hasCollect; CreatedBy = item.CreatedBy; CreatedOn = item.CreatedOn; UserImage = doctor.UserImage; ConsultNumber = item.ConsultNumber; ConsultantID = item.ConsultantID; ConsultantName = item.ConsultantName; ConsultantJSON = item.ConsultantJSON; DoctorName = item.DoctorName; DoctorID = item.DoctorID; DoctorJSON = item.DoctorJSON; PatientID = item.PatientID; PatientName = item.PatientName; PatientJSON = item.PatientJSON; ConsultType = item.ConsultType; IIInessType = item.IIInessType; IIInessId = IIIness; IIInessJSON = item.IIInessJSON; PhoneNumber = item.PhoneNumber; PatientCity = item.PatientCity; IIInessDescription = item.IIInessDescription; InquiryTimes = item.InquiryTimes; ConsultState = item.ConsultState; OvertimeRemindTimes = item.OvertimeRemindTimes; Overtime = item.Overtime; RefundBy = item.RefundBy; RefundTime = item.RefundTime; RefundType = item.RefundType; RefundNumber = item.RefundNumber; RefundState = item.RefundState; RefundReason = item.RefundReason; RefundRemarks = item.RefundRemarks; RecommendDoctorName = item.RecommendDoctorName; RecommendDoctorID = item.RecommendDoctorID; QualityDoctor = quality.DoctorName; Age = item.Age; Replys = reply.OrderBy(t => t.CreatedOn).ToList(); Consultationfile = consultationfile.ToList(); TimeSpan ts = DateTime.UtcNow.Subtract(item.CreatedOn); if (ts.TotalMinutes >= 3 || Replys.Count > 0) { Canhargeback = false; } else { Canhargeback = true; } var replycount = reply.Where(t => t.Message != "" && t.Message != null && t.ReplyType == "inquiries").ToList(); ReplysCount = 2 - replycount.Count > 0 ? 2 - replycount.Count : 0; ConsulationStatusCode = item.ConsultState; ConsultState = paramlist.Find(t => t.Code == item.ConsultState).Name; if (item.ConsultState == "consulting") { CanReplys = true; } else { CanReplys = false; } if (item.ConsultState == "success" && !HasEvaluation) { CanEvaluation = true; } else { CanEvaluation = false; } if (item.ConsultState == "success" || item.ConsultState == "return") { CanDelete = true; } else { CanDelete = false; } if (ReplysCount < 1) { CanReplys = false; } HasEvaluation = item.IsEvaluate; ReturnVisit = item.ReturnVisit; EvaluationId = eva.Count > 0 ? eva[0].Id : 0; ServiceMoneyListID = serverid; HasAllergic = JsonHelper.FromJson <YaeherPatientLeaguerInfo>(item.PatientJSON).HasAllergic; AllergicHistory = JsonHelper.FromJson <YaeherPatientLeaguerInfo>(item.PatientJSON).AllergicHistory; }
/// <summary> /// 绑定日程 /// </summary> /// <param name="StandardPlan"></param> protected void BindStandardPlan(IList <MStandardPlan> StandardPlan) { this.richeng.DataSource = StandardPlan.OrderBy(p => p.PlanDay); this.richeng.DataBind(); }
public static void Split(Document doc, ElementId elemId) { document = doc; selectedElemId = elemId; selectedElem = document.GetElement(elemId); selectedElemSolid = GetUppermostSolid(selectedElem); try { // Acquire interfering elements IList <Element> interferingElems = GetInterferingElems(selectedElem); if (interferingElems.Count == 0) { return; } if (selectedElem is Wall) { IList <ElementId> inserts = (selectedElem as Wall).FindInserts(true, true, true, true); if (inserts.Count != 0) { return; } if (ModifiedProfile((Wall)selectedElem)) { return; } // Get hold of all solids involed in the clash IList <Solid> interferingSolids = GetInterferingElemsAsSolids(interferingElems); // Perform the boolean opeartions to get the resulting solid Solid resultingSolid = GetResultingSolid(selectedElemSolid, interferingSolids); // Find the face whose normal matches the wall's normal Face face = null; XYZ wallOrientation = ((Wall)selectedElem).Orientation; foreach (Face currFace in resultingSolid.Faces) { XYZ faceNormal = currFace .ComputeNormal(new UV(0, 0)).Normalize(); if (Math.Round( wallOrientation.DotProduct(faceNormal), 2) > 0.1) { face = currFace; break; } } if (face == null) { throw new ArgumentNullException("Face is null"); } // Get a set of curveloops from the face IList <CurveLoop> crvLoops = face.GetEdgesAsCurveLoops(); IList <CurveLoop> orderedCrvloops = (crvLoops.OrderBy(crvloop => { Curve crv = crvloop .Where(c => GetDirectionVector(c).Z == 1) .First(); return(crv.GetEndPoint(0).Z); })).ToList(); // Get Wall's properties Wall wall = (Wall)selectedElem; WallType wallType = wall.WallType; using (Transaction t = new Transaction(doc, "Create walls")) { t.Start(); for (int i = 0; i < orderedCrvloops.Count; i++) { // Select a curve Curve selectedCrv = orderedCrvloops[i].Where(crv => GetDirectionVector(crv).Z == 1).First(); double currWallHeight = selectedCrv.ApproximateLength; if (i == 0) { double offset = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET).AsDouble(); Wall.Create(doc, ((LocationCurve)wall.Location).Curve, wallType.Id, wall.LevelId, currWallHeight, offset, false, true); } else { Element intruder = interferingElems .ElementAt(i - 1); ElementId currLevelId = intruder.LevelId; double offset = intruder .get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM) .AsDouble(); Wall.Create(doc, ((LocationCurve)wall.Location).Curve, wallType.Id, currLevelId, currWallHeight, offset, false, true); } } doc.Delete(wall.Id); t.Commit(); } } else { List <Curve> crvs = new List <Curve>(); IDictionary <Curve, Level> crvsLvls = new Dictionary <Curve, Level>(); Curve currCrv = GetColumnAxis(selectedElem); ElementId prevElemId = interferingElems.ElementAt(0).LevelId; for (int i = 0; i < interferingElems.Count; i++) { Element currElem = interferingElems.ElementAt(i); Solid elemSolid = GetUppermostSolid(currElem); SolidCurveIntersection results = elemSolid.IntersectWithCurve (currCrv, new SolidCurveIntersectionOptions { ResultType = SolidCurveIntersectionMode.CurveSegmentsOutside }); if (results.SegmentCount == 2) { // if it is not the last segment if (i != interferingElems.Count - 1) { crvs.Add(results.GetCurveSegment(0)); currCrv = results.GetCurveSegment(1); crvsLvls.Add(results.GetCurveSegment(0), (Level)doc.GetElement(prevElemId)); } else { crvs.Add(results.GetCurveSegment(0)); crvs.Add(results.GetCurveSegment(1)); crvsLvls.Add(results.GetCurveSegment(0), (Level)doc.GetElement(prevElemId)); crvsLvls.Add(results.GetCurveSegment(1), (Level)doc.GetElement(currElem.LevelId)); } } else { currCrv = results.GetCurveSegment(0); } prevElemId = currElem.LevelId; } FamilySymbol columnType = ((FamilyInstance)selectedElem).Symbol; using (Transaction t = new Transaction(doc, "Split Column")) { t.Start(); foreach (Curve crv in crvsLvls.Keys) { doc.Create.NewFamilyInstance (crv, columnType, crvsLvls[crv], StructuralType.Column); } doc.Delete(selectedElem.Id); t.Commit(); } } } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { } catch (Exception ex) { TaskDialog.Show("Exception", string.Format("StackTrace:\n{0}\nMessage:\n{1}", ex.StackTrace, ex.Message)); } }
public DadJoke GetRandom() { return(_Jokes.OrderBy(j => Guid.NewGuid()).First()); }
public Task ProcessEntities(IList <IClientSpanProcess> processes, IList <IClientSpan> clientSpans) { var orderedProcesses = processes.OrderBy(x => x.SortNum).ToList(); return(Task.WhenAll(orderedProcesses.Select(x => x.Process(clientSpans)))); }
/// <summary> /// 取引終了時の在庫更新を行います。 /// </summary> /// <param name="parameters">パラメーター。</param> /// <param name="client">Cosmos DB クライアント。</param> /// <param name="log">ロガー。</param> /// <returns>非同期の操作を表すタスク。TResult パラメーターの値には、処理の結果が含まれます。</returns> /// <remarks>BOX で付与されたタイムスタンプ順に処理されます。</remarks> private static async Task <(BoxResponse, RepositoryResult)> UpdateClosingStocksAsync( IList <UpdateStocksParameter> parameters, DocumentClient client, ILogger log) { var terminalRepo = new TerminalRepository(client); var boxRepo = new BoxRepository(client); var skuRepo = new SkuRepository(client); var stockRepo = new StockRepository(client); var cartRepo = new CartRepository(new CartServiceApi(StaticHttpClient.Instance)); parameters = parameters .OrderBy(arg => arg.Timestamp) .ToArray(); foreach (var parameter in parameters) { // 在庫を設定します。 var setStocksResult = await stockRepo.SetStocksAsync( parameter.BoxId, "1", parameter.Items.Select(arg => (arg.SkuCode, arg.Quantity)).ToArray()); if (!setStocksResult.IsSuccess) { return(BoxResponseFactory.CreateError <BoxResponse>(setStocksResult), setStocksResult); } // ターミナルを取得します。 (var terminalResult, var terminal) = await terminalRepo.FindByBoxIdAsync(parameter.BoxId); if (!terminalResult.IsSuccess) { return(BoxResponseFactory.CreateError <BoxResponse>(terminalResult), terminalResult); } // BOX を取得します。 (var boxResult, var box) = await boxRepo.FindByBoxIdAsync(parameter.BoxId); if (!boxResult.IsSuccess) { return(BoxResponseFactory.CreateError <BoxResponse>(boxResult), boxResult); } // 取引開始時と比較して、在庫数に差異がある BOX 商品を取得します。 (var stockDifferencesResult, var stockReferrences) = await stockRepo.GetStockDifferencesAsync(parameter.BoxId); if (!stockDifferencesResult.IsSuccess) { return(BoxResponseFactory.CreateError <BoxResponse>(stockDifferencesResult), stockDifferencesResult); } // BOX 商品を POS 商品に変換し、 // 取引開始時と比較して、在庫数に差異がある POS 商品を抽出します。 var items = stockReferrences .Select(arg => (arg.SkuCode, arg.Quantity)) .ToArray(); (var posItemsResult, var posItems) = await BoxItemsToPosItemsAsync(terminal.CompanyCode, terminal.StoreCode, items, skuRepo); if (!posItemsResult.IsSuccess) { return(BoxResponseFactory.CreateError <BoxResponse>(posItemsResult), posItemsResult); } var changedPosItems = posItems .Where(arg => arg.Quantity != 0) .Select(arg => (arg.ItemCode, 0 < arg.Quantity ? 1 : 2, Math.Abs(arg.Quantity))) .ToArray(); if (changedPosItems.Any()) { // 取引を確定します。 var subtotalResult = await cartRepo.SubtotalAsync(box.CartId, changedPosItems); if (!subtotalResult.IsSuccess) { return(BoxResponseFactory.CreateError <BoxResponse>(subtotalResult), subtotalResult); } var createPaymentResult = await cartRepo.CreatePaymentsAsync(box.CartId, new[] { ("01", 0M) });
private void ReplaceEntities(Span span, string text, IList <TextEntity> entities) { var previous = 0; foreach (var entity in entities.OrderBy(x => x.Offset)) { if (entity.Offset > previous) { span.Inlines.Add(new Run { Text = text.Substring(previous, entity.Offset - previous) }); } if (entity.Length + entity.Offset > text.Length) { previous = entity.Offset + entity.Length; continue; } if (entity.Type is TextEntityTypeBold) { span.Inlines.Add(new Run { Text = text.Substring(entity.Offset, entity.Length), FontWeight = FontWeights.SemiBold }); } else if (entity.Type is TextEntityTypeItalic) { span.Inlines.Add(new Run { Text = text.Substring(entity.Offset, entity.Length), FontStyle = FontStyle.Italic }); } else if (entity.Type is TextEntityTypeCode) { span.Inlines.Add(new Run { Text = text.Substring(entity.Offset, entity.Length), FontFamily = new FontFamily("Consolas") }); } else if (entity.Type is TextEntityTypePre || entity.Type is TextEntityTypePreCode) { // TODO any additional span.Inlines.Add(new Run { Text = text.Substring(entity.Offset, entity.Length), FontFamily = new FontFamily("Consolas") }); } else if (entity.Type is TextEntityTypeUrl || entity.Type is TextEntityTypeEmailAddress || entity.Type is TextEntityTypePhoneNumber || entity.Type is TextEntityTypeMention || entity.Type is TextEntityTypeHashtag || entity.Type is TextEntityTypeCashtag || entity.Type is TextEntityTypeBotCommand) { var hyperlink = new Hyperlink(); var data = text.Substring(entity.Offset, entity.Length); hyperlink.Click += (s, args) => Entity_Click(entity.Type, data); hyperlink.Inlines.Add(new Run { Text = data }); //hyperlink.Foreground = foreground; span.Inlines.Add(hyperlink); if (entity.Type is TextEntityTypeUrl) { MessageHelper.SetEntityData(hyperlink, data); } } else if (entity.Type is TextEntityTypeTextUrl || entity.Type is TextEntityTypeMentionName) { var hyperlink = new Hyperlink(); object data; if (entity.Type is TextEntityTypeTextUrl textUrl) { data = textUrl.Url; MessageHelper.SetEntityData(hyperlink, textUrl.Url); ToolTipService.SetToolTip(hyperlink, textUrl.Url); } else if (entity.Type is TextEntityTypeMentionName mentionName) { data = mentionName.UserId; } hyperlink.Click += (s, args) => Entity_Click(entity.Type, null); hyperlink.Inlines.Add(new Run { Text = text.Substring(entity.Offset, entity.Length) }); //hyperlink.Foreground = foreground; span.Inlines.Add(hyperlink); } previous = entity.Offset + entity.Length; } if (text.Length > previous) { span.Inlines.Add(new Run { Text = text.Substring(previous) }); } }
public static void QuickShuffle <T>(this IList <T> list) { list.OrderBy(a => rng.Next()); }
protected override IList ExecuteCrawl(bool crawlAll) { IList list = new List <MeetInfo>(); string html = string.Empty; try { html = this.ToolWebSite.GetHtmlByUrl(SiteUrl, Encoding.UTF8); } catch (Exception ex) { return(list); } Parser parser = new Parser(new Lexer(html)); NodeList nodeList = parser.ExtractAllNodesThatMatch(new AndFilter(new TagNameFilter("table"), new HasAttributeFilter("bordercolor", "#222222"))); if (nodeList != null && nodeList.Count > 0) { TableTag table = nodeList[0] as TableTag; for (int i = 0; i < table.RowCount; i++) { string meetTime = string.Empty, prjName = string.Empty, meetName = string.Empty, place = string.Empty, builUnit = string.Empty; TableRow tr = table.Rows[i]; if (tr.GetAttribute("valign") == "top") { string meetstr = string.Empty; string temp = tr.Columns[1].ToPlainTextString().Replace("(Y)", "").Replace("(Y)", "").Replace("(一年)", "").Replace("(一年)", ""); string code = temp.Replace("(", "(").Replace(")", ")").GetRegexBegEnd("(", ")"); if (!string.IsNullOrEmpty(code)) { if (code.IsChina()) { meetstr = temp.Replace("(" + code + ")", "").Replace("(" + code + ")", "");//.Replace("(", "").Replace("(", "").Replace(")", "").Replace(")", ""); code = meetstr.Replace("(", "(").Replace(")", ")").GetRegexBegEnd("(", ")"); if (!string.IsNullOrEmpty(code)) { meetstr = meetstr.Replace("(" + code + ")", "").Replace("(" + code + ")", ""); } } else { meetstr = temp.Replace("(" + code + ")", "").Replace("(" + code + ")", ""); } } else { meetstr = temp; } string[] str = meetstr.Split(' '); prjName = str[0]; meetName = "开标会"; System.Text.RegularExpressions.Regex regDate = new System.Text.RegularExpressions.Regex(@"\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}"); meetTime = regDate.Match(meetstr).Value; if (string.IsNullOrEmpty(meetTime)) { meetTime = meetstr.GetDateRegex(); } MeetInfo info = ToolDb.GenMeetInfo("广东省", "深圳政府采购", string.Empty, string.Empty, prjName, place, meetName, meetTime, string.Empty, "深圳市政府采购龙岗分中心", SiteUrl, code, builUnit, string.Empty, string.Empty); list.Add(info); if (!crawlAll && list.Count >= this.MaxCount) { IList <MeetInfo> result = list as IList <MeetInfo>; // 删除 string bDate = result.OrderBy(x => x.BeginDate).ToList()[0].BeginDate.ToString().GetDateRegex("yyyy/MM/dd"); string eDate = Convert.ToDateTime(result.OrderByDescending(x => x.BeginDate).ToList()[0].BeginDate).AddDays(1).ToString().GetDateRegex("yyyy/MM/dd"); string sqlwhere = " where City='深圳政府采购' and InfoSource='深圳市政府采购龙岗分中心' and BeginDate>='" + bDate + "' and BeginDate<='" + eDate + "'"; string delMeetSql = "delete from MeetInfo " + sqlwhere; int countMeet = ToolDb.ExecuteSql(delMeetSql); return(list); } } } } if (list != null && list.Count > 0) { IList <MeetInfo> result = list as IList <MeetInfo>; // 删除 string bDate = result.OrderBy(x => x.BeginDate).ToList()[0].BeginDate.ToString().GetDateRegex("yyyy/MM/dd"), eDate = Convert.ToDateTime(result.OrderByDescending(x => x.BeginDate).ToList()[0].BeginDate).AddDays(1).ToString().GetDateRegex("yyyy/MM/dd"); string sqlwhere = " where City='深圳政府采购' and InfoSource='深圳市政府采购龙岗分中心' and BeginDate>='" + bDate + "' and BeginDate<='" + eDate + "'"; string delMeetSql = "delete from MeetInfo " + sqlwhere; int countMeet = ToolDb.ExecuteSql(delMeetSql); } return(list); }
// GET: Student public ActionResult Index() { //fetch students from the DB using Entity Framework here return(View(studentList.OrderBy(s => s.StudentId).ToList())); }
public void SaveChanges(IList <UnspentOutput> unspentOutputs, HashHeightPair oldBlockHash, HashHeightPair nextBlockHash, List <RewindData> rewindDataList = null) { int insertedEntities = 0; using (var batch = new WriteBatch()) { using (new StopwatchDisposable(o => this.performanceCounter.AddInsertTime(o))) { HashHeightPair current = this.GetTipHash(); if (current != oldBlockHash) { this.logger.Error("(-)[BLOCKHASH_MISMATCH]"); throw new InvalidOperationException("Invalid oldBlockHash"); } // Here we'll add items to be inserted in a second pass. List <UnspentOutput> toInsert = new List <UnspentOutput>(); foreach (var coin in unspentOutputs.OrderBy(utxo => utxo.OutPoint, new OutPointComparer())) { if (coin.Coins == null) { this.logger.Debug("Outputs of transaction ID '{0}' are prunable and will be removed from the database.", coin.OutPoint); batch.Delete(new byte[] { coinsTable }.Concat(coin.OutPoint.ToBytes()).ToArray()); } else { // Add the item to another list that will be used in the second pass. // This is for performance reasons: dBreeze is optimized to run the same kind of operations, sorted. toInsert.Add(coin); } } for (int i = 0; i < toInsert.Count; i++) { var coin = toInsert[i]; this.logger.Debug("Outputs of transaction ID '{0}' are NOT PRUNABLE and will be inserted into the database. {1}/{2}.", coin.OutPoint, i, toInsert.Count); batch.Put(new byte[] { coinsTable }.Concat(coin.OutPoint.ToBytes()).ToArray(), this.dBreezeSerializer.Serialize(coin.Coins)); } if (rewindDataList != null) { foreach (RewindData rewindData in rewindDataList) { var nextRewindIndex = rewindData.PreviousBlockHash.Height + 1; this.logger.Debug("Rewind state #{0} created.", nextRewindIndex); batch.Put(new byte[] { rewindTable }.Concat(BitConverter.GetBytes(nextRewindIndex)).ToArray(), this.dBreezeSerializer.Serialize(rewindData)); } } insertedEntities += unspentOutputs.Count; this.rocksDb.Write(batch); this.SetBlockHash(nextBlockHash); } } this.performanceCounter.AddInsertedEntities(insertedEntities); }
public void Sort(Func <T, object> func) { _collection = _collection.OrderBy(func).ToList(); }
public IActionResult Index() { var result = institutions.OrderBy(i => i.Name); return(View(result)); }
public void RaiseCallbackEvent(string eventArgument) { string type = string.Format("{0}_manager", eventArgument); IDictionary <string, string> data = null; IList <string> keys = null; switch (type) { case "admin_memory_cache_manager": data = CacheManager.GetPerformanceData(); break; case "admin_memory_keys_manager": keys = CacheManager.GetCacheKeys(); break; case "store_memory_cache_manager": data = UtilityService.GetCachePerformanceData(type); break; case "store_memory_keys_manager": keys = UtilityService.GetCacheKeys(type); break; case "service_memory_cache_manager": data = UtilityService.GetCachePerformanceData(type); break; case "service_memory_keys_manager": keys = UtilityService.GetCacheKeys(type); break; case "service_dache_cache_manager": data = UtilityService.GetCachePerformanceData(type); break; case "service_dache_keys_manager": keys = UtilityService.GetCacheKeys(type); break; default: break; } if (data != null) { StringBuilder sb = new StringBuilder(); foreach (var item in data) { sb.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", item.Key, item.Value); } _message = sb.ToString(); } if (keys != null) { keys = keys.OrderBy(x => x).ToList(); StringBuilder sb = new StringBuilder(); foreach (var key in keys) { sb.AppendFormat("<tr><td>{0}</td></tr>", key); } _message = sb.ToString(); } }
private void button2_Click(object sender, EventArgs e) { Hole_List = Hole_List.OrderBy(a => a.start).ToList(); Old_num = 0; for (int i = 0; i < Hole_List.Count; i++) { if (i == 0) { if (Hole_List[i].start > 0) { PS = new Process(); SG.sg_name = "Old Process " + Old_num.ToString(); SG.sg_size = Hole_List[i].start; Memory.Add(0, SG); PS.name = SG.sg_name; PS.sg_num = 1; PS.sg_alloc(); PS.Add_SG(SG); PS_List.Add(PS); Old_num++; } } else if (Hole_List[i].start > (Hole_List[i - 1].start + Hole_List[i - 1].size)) { PS = new Process(); SG.sg_name = "Old Process " + Old_num.ToString(); SG.sg_size = Hole_List[i].start - (Hole_List[i - 1].start + Hole_List[i - 1].size); Memory.Add((Hole_List[i - 1].start + Hole_List[i - 1].size), SG); PS.name = SG.sg_name; PS.sg_num = 1; PS.sg_alloc(); PS.Add_SG(SG); PS_List.Add(PS); Old_num++; } SG.sg_name = "Hole " + Hole_List[i].num.ToString(); SG.sg_size = Hole_List[i].size; Memory.Add(Hole_List[i].start, SG); if (i == Hole_List.Count - 1) { if ((Hole_List[i].start + Hole_List[i].size) < size) { PS = new Process(); SG.sg_name = "Old Process " + Old_num.ToString(); SG.sg_size = size - (Hole_List[i].start + Hole_List[i].size); Memory.Add((Hole_List[i].start + Hole_List[i].size), SG); PS.name = SG.sg_name; PS.sg_num = 1; PS.sg_alloc(); PS.Add_SG(SG); PS_List.Add(PS); Old_num++; } } } Memory_Layout(); if (PS_List.Any()) { label5.Text = "Memory Layout"; if (Hole_List.Count == 1) { if (Memory.Last().Value.sg_name.Contains("Hole")) { label5.Text = "Memory Compact"; } else { button6.Enabled = true; } } else { button6.Enabled = true; } label2.Visible = true; button3.Enabled = true; } else { label5.Text = "Memory Empty"; } textBox1.Enabled = false; button1.Visible = false; button5.Visible = true; groupBox2.Enabled = true; listBox1.Visible = false; button2.Visible = false; button3.Visible = true; checkedListBox1.Visible = true; for (int i = 0; i < PS_List.Count; i++) { checkedListBox1.Items.Insert(i, PS_List[i].name); } }
/// <summary>Generates a chemical proteoform hash for the specified proteoform.</summary> /// <param name="proForma">The ProForma.</param> /// <returns></returns> public IChemicalProteoformHash Generate(string proForma) { // Parse string into term ProFormaTerm originalProFormaTerm = this._proFormaParser.ParseString(proForma); // Check to see if this is only a sequence if (originalProFormaTerm.NTerminalDescriptors == null && originalProFormaTerm.CTerminalDescriptors == null && originalProFormaTerm.Tags == null && originalProFormaTerm.GlobalModifications == null && originalProFormaTerm.LabileDescriptors == null && originalProFormaTerm.TagGroups == null && originalProFormaTerm.UnlocalizedTags == null) { IProteoformGroup simpleGroup = this._proteoformGroupFactory.CreateProteoformGroup(originalProFormaTerm.Sequence); return(new ChemicalProteoformHash(originalProFormaTerm.Sequence, simpleGroup)); } // Create proteoform group (flattens all features into Ids) IProteoformGroup proteoformGroup = this._proteoformGroupFactory.CreateProteoformGroup(originalProFormaTerm, this._proteoformModificationLookup); ProFormaDescriptor?nTermDescriptor = this.CreateDescriptor(proteoformGroup.NTerminalModification); IList <ProFormaDescriptor>?nTermDescriptors = nTermDescriptor == null ? null : new[] { nTermDescriptor }; ProFormaDescriptor?cTermDescriptor = this.CreateDescriptor(proteoformGroup.CTerminalModification); IList <ProFormaDescriptor>?cTermDescriptors = cTermDescriptor == null ? null : new[] { cTermDescriptor }; IList <ProFormaTag>? tags = null; IList <ProFormaDescriptor>? labileDescriptors = null; IList <ProFormaUnlocalizedTag>? unlocalizedTags = null; IList <ProFormaTagGroup>? tagGroups = null; IList <ProFormaGlobalModification>?globalModifications = null; if (proteoformGroup.LocalizedModifications?.Count > 0) { foreach (var mod in proteoformGroup.LocalizedModifications) { ProFormaDescriptor?descriptor = this.CreateDescriptor(mod.ModificationDelta); if (descriptor != null) { tags ??= new List <ProFormaTag>(); tags.Add(new ProFormaTag(mod.ZeroBasedStartIndex, mod.ZeroBasedEndIndex, new[] { descriptor })); } } } if (proteoformGroup.UnlocalizedModifications?.Count > 0) { foreach (var mod in proteoformGroup.UnlocalizedModifications) { ProFormaDescriptor?descriptor = this.CreateDescriptor(mod.ModificationDelta); if (descriptor != null) { if (mod.IsLabile) { labileDescriptors ??= new List <ProFormaDescriptor>(); for (int i = 0; i < mod.Count; i++) { labileDescriptors.Add(descriptor); } } else { unlocalizedTags ??= new List <ProFormaUnlocalizedTag>(); unlocalizedTags.Add(new ProFormaUnlocalizedTag(mod.Count, new[] { descriptor })); } } } } if (proteoformGroup.ModificationGroups?.Count > 0) { foreach (var mod in proteoformGroup.ModificationGroups) { ProFormaDescriptor?descriptor = this.CreateDescriptor(mod.ModificationDelta); if (descriptor != null) { tagGroups ??= new List <ProFormaTagGroup>(); tagGroups.Add(new ProFormaTagGroup(mod.GroupName, descriptor.Key, descriptor.EvidenceType, descriptor.Value, mod.Members.Select(x => new ProFormaMembershipDescriptor(x.ZeroBasedStartIndex, x.ZeroBasedEndIndex, x.Weight)).ToList())); } } } if (proteoformGroup.GlobalModifications?.Count > 0) { foreach (var mod in proteoformGroup.GlobalModifications) { ProFormaDescriptor?descriptor = this.CreateDescriptor(mod.ModificationDelta); if (descriptor != null) { globalModifications ??= new List <ProFormaGlobalModification>(); globalModifications.Add(new ProFormaGlobalModification(new[] { descriptor }, mod.TargetAminoAcids)); } } } string?sequence = proteoformGroup.GetSequence(); if (sequence != null) { ProFormaTerm proFormaTerm = new(sequence, tags : tags?.OrderBy(t => t.Descriptors.First().Value).ToArray(), nTerminalDescriptors : nTermDescriptors, cTerminalDescriptors : cTermDescriptors, labileDescriptors : labileDescriptors, unlocalizedTags : unlocalizedTags, tagGroups : tagGroups, globalModifications : globalModifications); string hash = new ProFormaWriter().WriteString(proFormaTerm); return(new ChemicalProteoformHash(hash, proteoformGroup)); } throw new Exception("Cannot get amino acid sequence for the proteoform group."); }
public static List <CategoryTreeNodeViewModel> GetCategoryTreeNodesInHierarchy( bool enableMultilanguage, IList <Category> sitemapNodes, IList <Category> allNodes, List <Guid> languageIds) { var nodeList = new List <CategoryTreeNodeViewModel>(); foreach (var node in sitemapNodes.OrderBy(node => node.DisplayOrder)) { var nodeViewModel = new CategoryTreeNodeViewModel { Id = node.Id, Version = node.Version, Title = node.Name, DisplayOrder = node.DisplayOrder, ChildNodes = GetCategoryTreeNodesInHierarchy(enableMultilanguage, allNodes.Where(f => f.ParentCategory == node).ToList(), allNodes, languageIds), Macro = node.Macro }; // if (enableMultilanguage) // { // nodeViewModel.Translations = new List<SitemapNodeTranslationViewModel>(); // // node.Translations.Distinct() // .Select(t => new SitemapNodeTranslationViewModel // { // Id = t.Id, // LanguageId = t.Language.Id, // Title = t.Title, // UsePageTitleAsNodeTitle = t.UsePageTitleAsNodeTitle, // Url = t.Url, // Version = t.Version, // Macro = t.Macro // }) // .ToList() // .ForEach(nodeViewModel.Translations.Add); // // if (linkedPage != null) // { // // Setup default language. // if (!linkedPage.LanguageId.HasValue) // { // nodeViewModel.Url = linkedPage.Url; // if (nodeViewModel.UsePageTitleAsNodeTitle) // { // nodeViewModel.Title = linkedPage.Title; // } // } // else if (linkedPage.LanguageGroupIdentifier.HasValue) // { // // If non-default translation is added to sitemap, retrieving default page from page translations list // var defaultPageTranslation = pages.FirstOrDefault(p => p.LanguageGroupIdentifier.HasValue // && p.LanguageGroupIdentifier.Value == linkedPage.LanguageGroupIdentifier.Value // && (!p.LanguageId.HasValue || p.LanguageId.Value.HasDefaultValue())); // if (defaultPageTranslation != null) // { // nodeViewModel.Url = defaultPageTranslation.Url; // nodeViewModel.DefaultPageId = defaultPageTranslation.Id; // if (nodeViewModel.UsePageTitleAsNodeTitle) // { // nodeViewModel.Title = defaultPageTranslation.Title; // } // } // } // // // Setup other languages. // foreach (var languageId in languageIds) // { // var translationViewModel = nodeViewModel.Translations.FirstOrDefault(t => t.LanguageId == languageId); // if (translationViewModel == null) // { // translationViewModel = new SitemapNodeTranslationViewModel // { // Id = Guid.Empty, // LanguageId = languageId, // Title = linkedPage.Title, // Url = nodeViewModel.Url, // UsePageTitleAsNodeTitle = true, // Version = 0, // Macro = string.Empty // }; // nodeViewModel.Translations.Add(translationViewModel); // } // // var title = translationViewModel.Title; // var url = translationViewModel.Url ?? nodeViewModel.Url; // // if (linkedPage.LanguageId != null && linkedPage.LanguageId == languageId) // { // title = linkedPage.Title; // url = linkedPage.Url; // translationViewModel.PageId = linkedPage.Id; // } // else if (linkedPage.LanguageGroupIdentifier.HasValue) // { // // Get page translation. If not exists, retrieve default language's translation // var pageTranslation = pages.FirstOrDefault(p => p.LanguageGroupIdentifier.HasValue // && p.LanguageGroupIdentifier.Value == linkedPage.LanguageGroupIdentifier.Value // && p.LanguageId.HasValue // && p.LanguageId.Value == languageId); // // If page has translation, set it's id // if (pageTranslation != null) // { // translationViewModel.PageId = pageTranslation.Id; // } // // // If page translation does not exist, retrieve default language's translation // if (pageTranslation == null) // { // pageTranslation = pages.FirstOrDefault(p => p.LanguageGroupIdentifier.HasValue // && p.LanguageGroupIdentifier.Value == linkedPage.LanguageGroupIdentifier.Value // && (!p.LanguageId.HasValue || p.LanguageId.Value.HasDefaultValue())); // } // // if (pageTranslation != null) // { // title = pageTranslation.Title; // url = pageTranslation.Url; // } // } // // translationViewModel.Url = url; // if (translationViewModel.UsePageTitleAsNodeTitle) // { // translationViewModel.Title = title; // } // } // } // } nodeList.Add(nodeViewModel); } return(nodeList); }
protected bool Equals(TableDefinition other) { return(Columns.OrderBy(x => x.Name).SequenceEqual(other.Columns.OrderBy(x => x.Name)) && Equals(PrimaryKey, other.PrimaryKey) && string.Equals(Name, other.Name)); }
public void Cleanup() { if (TrackNumber != null && TrackNumber.Contains("/")) { TrackNumberTotal = TrackNumber; string[] parts = TrackNumber.Split('/'); TrackNumber = parts[0]; TrackTotal = parts[1]; } else if (Utils.IsNumeric(TrackNumber)) { TrackNumberTotal = TrackNumber; if (Utils.IsNumeric(TrackTotal)) { TrackNumberTotal += "/" + TrackTotal; } } if (DiscNumber != null && DiscNumber.Contains("/")) { DiscNumberTotal = DiscNumber; string[] parts = DiscNumber.Split('/'); DiscNumber = parts[0]; DiscTotal = parts[1]; } else if (Utils.IsNumeric(DiscNumber)) { DiscNumberTotal = DiscNumber; if (Utils.IsNumeric(DiscTotal)) { DiscNumberTotal += "/" + DiscTotal; } } if (Chapters != null && Chapters.Count > 0) { // Sort by start offset or time if (Chapters[0].UseOffset) { Chapters = Chapters.OrderBy(chapter => chapter.StartOffset).ToList(); } else { Chapters = Chapters.OrderBy(chapter => chapter.StartTime).ToList(); } // Auto-fill end offsets or times except for final chapter ChapterInfo previousChapter = null; foreach (ChapterInfo chapter in Chapters) { if (previousChapter != null) { if (chapter.UseOffset && 0 == previousChapter.EndOffset) { previousChapter.EndOffset = chapter.StartOffset; } else if (0 == previousChapter.EndTime) { previousChapter.EndTime = chapter.StartTime; } } previousChapter = chapter; } // Calculate duration of final chapter with duration of audio if (previousChapter != null && 0 == previousChapter.EndTime) { previousChapter.EndTime = (uint)Math.Round(DurationMs); } } }
public SessionsByTagTableViewSource(SessionListByTagViewController hostController, IList <Session> sessions) { _sessions = sessions.OrderBy(session => session.Starts).ToList(); _hostController = hostController; }
public List <Processo> GetAll() { List <Processo> processo = _processos.OrderBy(x => x.Escritorio.Nome).ThenBy(x => x.Numero).ToList(); return(processo); }