protected override List<IIndividual> selection(List<IIndividual> individuals) { var size = _iconfig.selectionSize; var pressure = 0.9999999; var minimalFitness = individuals.Aggregate(Double.MaxValue, (acc, next) => ((acc > getIndividualFitness(next)) ? getIndividualFitness(next) : acc)); var totalFitness = individuals.Aggregate(0.0, (acc, next) => getIndividualFitness(next)-minimalFitness*pressure + acc); var step = totalFitness / size; var start = _rand.NextDouble()*step; var indOut = new List<IIndividual>(); var threshold = 0.0; foreach (var ind in individuals) // they don't have to be sorted { /* * | | | | | | | | | * ^ ^ ^ ^ <- uniformly spaced * first one randomly chosen from [0, totalFitness / size] * then skip by totalFitness / size * less elitist than Roulette which promotes the best individuals the most */ while (start < threshold + getIndividualFitness(ind) - minimalFitness * pressure) { indOut.Add(ind.duplicate()); start += step; } threshold += getIndividualFitness(ind) - minimalFitness * pressure; } return indOut; }
public static float InputFloat(float min, float max, Func <float, float, float> funcSum = null, List <float> frequencies = null) { float num; while (!float.TryParse(Console.ReadLine(), out num) || num < min || num > max || funcSum != null && frequencies?.Count != 0 && num + frequencies?.Aggregate(funcSum) > 1) { if (num < min || num > max) { Console.WriteLine($"Введите число от {min} до {max}"); continue; } if (frequencies?.Count != 0 && funcSum != null && num + frequencies?.Aggregate(funcSum) > 1) { Console.WriteLine(frequencies?.Aggregate(funcSum)); Console.WriteLine( $"Введите число, чтобы сумма частот была не больше 1. Максимальное число для ввода: {Math.Round(1 - frequencies.Aggregate(funcSum), 3)}"); continue; } Console.WriteLine("Введите число. Если это дробное число, отделите дробную часть запятой"); } return(num); }
/// <summary> /// Gets the hero average damage to the opposing team. /// </summary> /// <param name="player">The player.</param> /// <param name="Enemies">The enemies.</param> /// <returns></returns> public static float GetHeroAvgDamage(AIHeroClient player, List<AIHeroClient> Enemies) { var totalEnemies = Enemies.Count(); if (totalEnemies == 0) { return -1; } var AADamage = Enemies.Aggregate(0, (current, s) => (int) (current + player.LSGetAutoAttackDamage(s) * 2)); var QDamage = Enemies.Aggregate(0, (current, s) => (int)(current + (player.GetSpell(SpellSlot.Q).IsReady() ? player.LSGetSpellDamage(s, SpellSlot.Q) : 0f))); var WDamage = Enemies.Aggregate(0, (current, s) => (int)(current + (player.GetSpell(SpellSlot.W).IsReady() ? player.LSGetSpellDamage(s, SpellSlot.W) : 0f))); var EDamage = Enemies.Aggregate(0, (current, s) => (int)(current + (player.GetSpell(SpellSlot.E).IsReady() ? player.LSGetSpellDamage(s, SpellSlot.E) : 0f))); var RDamage = Enemies.Aggregate(0, (current, s) => (int)(current + (player.GetSpell(SpellSlot.R).IsReady() ? player.LSGetSpellDamage(s, SpellSlot.R) : 0f))); var itemsDamage = 0f; foreach (var item in player.InventoryItems) { foreach (var hero in Enemies) { var itemID = item.Id; switch (itemID) { case ItemId.Bilgewater_Cutlass: itemsDamage += (float) player.GetItemDamage(hero, Damage.DamageItems.Bilgewater); break; case ItemId.Blade_of_the_Ruined_King: itemsDamage += (float) player.GetItemDamage(hero, Damage.DamageItems.Botrk); break; case ItemId.Hextech_Gunblade: itemsDamage += (float) player.GetItemDamage(hero, Damage.DamageItems.Hexgun); break; case ItemId.Frost_Queens_Claim: itemsDamage += (float) player.GetItemDamage(hero, Damage.DamageItems.FrostQueenClaim); break; case ItemId.Tiamat_Melee_Only: itemsDamage += player.IsMelee ? (float) player.GetItemDamage(hero, Damage.DamageItems.Tiamat) : 0f; break; case ItemId.Ravenous_Hydra_Melee_Only: itemsDamage += player.IsMelee ? (float) player.GetItemDamage(hero, Damage.DamageItems.Hydra) : 0f; break; case ItemId.Liandrys_Torment: itemsDamage += (float) player.GetItemDamage(hero, Damage.DamageItems.LiandrysTorment); break; } } } var totalDamage = AADamage + QDamage + WDamage + EDamage + RDamage + itemsDamage; return (float) totalDamage / totalEnemies; }
public static string Guess(List<char>secret, List<char> guess) { int index=0; string okLettOkPos= guess.Aggregate("",(x,y)=> x+=(secret[index++]==y?"p":"")); string okLettWrongPos= guess.Aggregate("",(x,y)=> x+=(Contains(secret,y)?"m":"")); string toReturn = okLettOkPos+okLettWrongPos; toReturn = toReturn.Substring(0,toReturn.Length-okLettOkPos.Length); return toReturn; }
/// <summary> /// Calculate Stock Price based on trades recorded in past 15 minutes /// </summary> /// <param name="stockSymbol"></param> /// <returns>Stock Price</returns> public double StockPrice(string stockSymbol) { List<Trade> validTrades = new List<Trade>(); validTrades.AddRange(Trades.Where(x => x.Stock.StockSymbol == stockSymbol && x.Timestamp > Trades.ElementAt(Trades.Count - 1).Timestamp.Subtract(new TimeSpan(0, 15, 0)))); if (validTrades.Count() <= 0) { Log.WarnFormat(Properties.Resources.SUPERSIMPLESTOCKS_ERR_003, stockSymbol); return 0; } return validTrades.Aggregate(0.0, (tot, x) => tot + (x.Price * x.Quantity)) / validTrades.Aggregate(0.0, (tot, x) => tot + x.Quantity); }
public Foo() { _numbers = new List<int>(); string s = _numbers[10].Format("{0}"); string s2 = _numbers.GetEnumerator().Current.Format("{0}"); string s3 = _numbers.Aggregate<int>(0, delegate(int accumulated, int item) { return accumulated + item; }).Format("{0}"); string s4 = _func(10).EncodeUriComponent(); Func<int, string> f2 = _func; f2(11).Trim(); Dictionary<string, int> d = new Dictionary<string, int>(); string s5 = jQuery.ExtendDictionary<string, int>(d, d)["abc"].Format("{0}"); int keys = d.Count; bool b = d.ContainsKey("abc"); d.Remove("abc"); foreach (KeyValuePair<string, int> de in d) { } jQuery.AjaxRequest<string>("http://example.com").Success(delegate(string html) { Script.Alert(html); }); string json = ""; Foo f = Json.ParseData<Foo>(json).Setup().Run().Cleanup(); string name = Document.GetElementById("nameTB").As<InputElement>().Value; }
public IPagedList <CleanRateView> GetPagedCleanRateView(int page, int pageSize, string queryName, out int count, List <Expression <Func <DataStatistics, bool> > > conditions = null) { var deviceModel = Repo <LampblackDeviceModelRepository>().GetAllModels().First().Id; var rater = (CleanessRate)PlatformCaches.GetCache($"CleanessRate-{deviceModel}").CacheItem; var hotels = Repo <HotelRestaurantRepository>().GetAllModels(); var dayStatics = conditions?.Aggregate( Repo <DataStatisticsRepository>() .GetModels(obj => obj.Type == StatisticsType.Day && obj.CommandDataId == CommandDataId.CleanerCurrent), (current, condition) => current.Where(condition)) .GroupBy(item => item.ProjectIdentity) ?? Repo <DataStatisticsRepository>() .GetModels(obj => obj.Type == StatisticsType.Day && obj.CommandDataId == CommandDataId.CleanerCurrent) .GroupBy(item => item.ProjectIdentity); var cleanRateView = (from dayStatic in dayStatics select new CleanRateView { HotelName = hotels.FirstOrDefault(obj => obj.Identity == dayStatic.Key).ProjectName, Failed = dayStatic.Count(obj => obj.DoubleValue <= rater.Fail), Worse = dayStatic.Count(obj => obj.DoubleValue > rater.Fail && obj.DoubleValue <= rater.Worse), Qualified = dayStatic.Count(obj => obj.DoubleValue > rater.Worse && obj.DoubleValue <= rater.Qualified), Good = dayStatic.Count(obj => obj.DoubleValue > rater.Good) }).OrderBy(view => view.HotelName).Where(ret => ret.HotelName != null); count = hotels.Count(); return(cleanRateView.ToPagedList(page, pageSize)); }
/// <summary> /// Calculate the GBCE All Share Index using the geometric mean of prices for all stocks /// </summary> /// <returns>GBCE All Share Index</returns> public double StocksGeometricMean() { List<Stock> validStocks = new List<Stock>(); validStocks.AddRange(Stocks.Where(x => StockPrice(x.StockSymbol) > 0)); return Math.Pow(validStocks.Aggregate(1.0, (tot, x) => tot * StockPrice(x.StockSymbol)), 1.0 / validStocks.Count()); }
private void DisplayAvgLoanBase() { var calcUtil = new LoanCalcUtil( 10000 * decimal.Parse(txtTotalLoanBase.Text.Trim()), int.Parse(cbxYears.Text), 0.01M * decimal.Parse(txtYearInterestRate.Text.Trim()), PayLoanType.AvgLoanBase, rbtnQuarterly.Checked ? PayCycleType.PerQuarter : PayCycleType.PerMonth); Dictionary<int, decimal> interestsDic = new Dictionary<int, decimal>(); List<string> cyclePayList = new List<string>(); decimal cycleInterest = 0.0M; decimal cycleLoanBase = calcUtil.TotalLoanBase / calcUtil.Cycles; for (int cycle = 0; cycle < calcUtil.Cycles; cycle++) { cycleInterest = calcUtil.CalcInterestForAvgLoanBase(cycle); interestsDic.Add(cycle, cycleInterest); string cyclePay = string.Format("第 {0} {1}: 本金({2:F2}),利息({3:F2}),共({4:F2})元;{5}", cycle + 1, calcUtil.PayCycle == PayCycleType.PerMonth ? "月" : "季", cycleLoanBase, cycleInterest, cycleLoanBase + cycleInterest, Environment.NewLine); cyclePayList.Add(cyclePay); } var totalInterests = interestsDic.Aggregate(0.0M, (seed, kvp) => { return seed + kvp.Value; }); txtInterestsForLoanBase.Text = totalInterests.ToString("F2"); string showText = cyclePayList.Aggregate(string.Empty, (seed, cyclePay) => { return seed + cyclePay; }); rtxtCyclePays.Text = showText; }
public async Task<IEnumerable<Channel>> GetEventsForDateAsync(DateTime start, IEnumerable<string> channels = null) { var channelUri = string.Empty; var hackingList = new List<string>(channels); var needsHack = false; // HACK because the API does not return an JSON array when there is only one channel if (hackingList.Count == 1) { hackingList.Add("5"); // Get Info channel (small overhead in data) needsHack = true; } if (hackingList.Count > 1) channelUri = hackingList.Aggregate("&channels=", (current, channel) => current + (channel + ",")); var urlBuilder = new UriBuilder(EndpointUri) { Query = string.Format("start={0}&duration={1}{2}", start.ToString(App.DateFormat), MinutesInDay, channelUri) }; var jsonStream = await Client.GetStreamAsync(urlBuilder.Uri); var events = new List<Channel>(EventDataMapper.MapEvents(jsonStream)); if(needsHack) events.Remove(events.Last()); // TODO: Possible bug source :) return events; }
public long Run () { var max = 20; var factors = new List <int> (); var products = new List <int> (); foreach (var n in Enumerable.Range (1, max)) { if (products.Contains (n)) continue; var newFactor = products .OrderByDescending (p => p) .Where (p => n % p == 0) .Select (p => n / p) .FirstOrDefault (); if (newFactor == 0) newFactor = n; products.AddRange (products.Select (p => newFactor * p).ToList ()); products.Add (newFactor); factors.Add (newFactor); } return factors.Aggregate ((a, b) => a * b); }
public void Execute() { // // Emptyメソッドは、文字通り空のシーケンスを作成するメソッドである。 // Unionする際や、Aggregateする際の中間値として利用されることが多い。 // Output.WriteLine("COUNT = {0}", Enumerable.Empty<string>().Count()); // // 指定されたシーケンスから合計値が100を超えているシーケンスのみを抽出. // Aggregateのseed値として、空のシーケンスを渡すためにEnumerable.Emptyを // 使用している。 // var sequences = new List<IEnumerable<int>> { Enumerable.Range(1, 10), Enumerable.Range(30, 3), Enumerable.Range(50, 2), Enumerable.Range(200, 1) }; var query = sequences.Aggregate( Enumerable.Empty<int>(), (current, next) => next.Sum() > 100 ? current.Union(next) : current ); foreach (var item in query) { Output.WriteLine(item); } }
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule() { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "validname", }; var clientValidationRules = new List<string> { _onlyOneEntityValidator.GetClientValidationRules(metadata,context).First().ValidationType, _cannotBeNotApplicable.GetClientValidationRules(metadata,context).First().ValidationType, _cannotContainNumbers.GetClientValidationRules(metadata,context).First().ValidationType, }; var regexPatterns = new List<string> { _onlyOneEntityValidator.Pattern, _cannotBeNotApplicable.Pattern, _cannotContainNumbers.Pattern, }; var errorMessages = new List<string> { _onlyOneEntityValidator.FormatErrorMessage(metadata.GetDisplayName()), _cannotBeNotApplicable.FormatErrorMessage(metadata.GetDisplayName()), _cannotContainNumbers.FormatErrorMessage(metadata.GetDisplayName()) }; rule.ValidationParameters.Add("clientvalidationrules", clientValidationRules.Aggregate((i, j) => i + "," + j)); rule.ValidationParameters.Add("regexpatterns", regexPatterns.Aggregate((i, j) => i + "," + j)); rule.ValidationParameters.Add("errormessages", errorMessages.Aggregate((i, j) => i + "," + j)); yield return rule; }
public void Validate() { IList<string> errorMessages = new List<string>(); foreach (var validator in Validators) { if (validator.Enable) { var isValidOptional = validator.Validate(); if(!isValidOptional) errorMessages.Add(validator.ErrorMessage); } else validator.IsValid = true; } if (IsOptional) { if (errorMessages.Count > 0) { _isValid = false; if (MessageBox.Show("Attenzione leggere i seguenti avvertimenti:" + Environment.NewLine + Environment.NewLine + errorMessages.Aggregate(string.Empty, (current, errorMessage) => current + (errorMessage + Environment.NewLine)) + Environment.NewLine + "Sei sicuro di voler continuare?", "Sfera", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.OK) _isValid = true; } else _isValid = true; } }
public ICollection <dynamic> RunPSScript(string script, bool quiet_exceptions = false, List <string> args = null) { try { ICollection <dynamic> r = this.Manager.RunScript(script, args?.Select(a => a as object).ToList()); if (r != null) { Debug("Executed PowerShell script {0} {1} on {2}.", script, args?.Aggregate((s1, s2) => s1 + s2), this.Manager.IpAddress); return(r); } else { if (!quiet_exceptions) { Error("Could not execute PowerShell script {0} {1} on {2}.", script, args?.Aggregate((s1, s2) => s1 + s2), this.Manager.IpAddress); } return(null); } } catch (Exception e) { if (!quiet_exceptions) { Error(e, "Could not execute PowerShell script {0} {1} on {2}.", script, args?.Aggregate((s1, s2) => s1 + s2), this.Manager.IpAddress); } return(null); } }
public static void ApplyImagesToEntities(List<EntityImageMap> mappings, IOrganizationService service) { foreach (var mapping in mappings) { if (mapping.ImageSize == 16) { mapping.Entity.IconSmallName = mapping.WebResourceName; } else { mapping.Entity.IconMediumName = mapping.WebResourceName; } var request = new UpdateEntityRequest { Entity = mapping.Entity }; service.Execute(request); } string parameter = mappings.Aggregate(string.Empty, (current, mapping) => current + ("<entity>" + mapping.Entity.LogicalName + "</entity>")); string parameterXml = string.Format("<importexportxml ><entities>{0}</entities></importexportxml>", parameter); var publishRequest = new PublishXmlRequest { ParameterXml = parameterXml }; service.Execute(publishRequest); }
public void JudgeOperate(Page page, int menuId, List<OperateEnum> operateTypes) { UserModel user = UserUtility.CurrentUser; try { AuthOperateBLL bll = new AuthOperateBLL(); ResultModel result = bll.JudgeOperate(user, menuId, operateTypes); if (result.ResultStatus != 0) { string oids = operateTypes.Aggregate(string.Empty, (current, operate) => current + (operate.ToString() + ",")); if (!string.IsNullOrEmpty(oids) && oids.IndexOf(',') > -1) oids = oids.Substring(0, oids.Length - 1); MenuBLL menuBLL = new MenuBLL(); result = menuBLL.Get(user, menuId); if (result.ResultStatus != 0) throw new Exception("获取菜单失败"); Menu menu = result.ReturnValue as Menu; if (menu != null) { string redirectUrl = string.Format("{0}/ErrorPage.aspx?t={1}&r={2}", DefaultValue.NfmtSiteName, string.Format("用户无{0}-{1}权限", menu.MenuName, oids), string.Format("{0}MainForm.aspx",NFMT.Common.DefaultValue.NfmtSiteName)); page.Response.Redirect(redirectUrl,false); } } } catch (Exception e) { log.ErrorFormat("用户{0},错误:{1}", user.EmpName, e.Message); page.Response.Redirect("/MainForm.aspx"); } }
/// <summary> /// Averages the specified vectors. /// </summary> /// <param Name="vectors">The vectors to average.</param> /// <returns>Average of the vectors</returns> public static Vector3 Average(List<Vector3> vectors) { Vector3 toReturn = vectors.Aggregate(Vector3.Zero, (current, vector) => current + vector); toReturn /= vectors.Count; return toReturn; }
public override int GetHashCode() { unchecked { var comparer = new KeyValuePairStringIntComparer(); var hashCode = (int)N11; hashCode = (hashCode * 397) ^ (int)N12; hashCode = (hashCode * 397) ^ (int)N13; hashCode = (hashCode * 397) ^ (int)N14; hashCode = (hashCode * 397) ^ (int)N21; hashCode = (hashCode * 397) ^ (int)N22; hashCode = (hashCode * 397) ^ (int)N23; hashCode = (hashCode * 397) ^ (int)N24; hashCode = (hashCode * 397) ^ _d11.GetHashCode(); hashCode = (hashCode * 397) ^ _d12.GetHashCode(); hashCode = (hashCode * 397) ^ _d13.GetHashCode(); hashCode = (hashCode * 397) ^ _d21.GetHashCode(); hashCode = (hashCode * 397) ^ _d22.GetHashCode(); hashCode = (hashCode * 397) ^ _d23.GetHashCode(); hashCode = (hashCode * 397) ^ TwoGramCount.GetHashCode(); hashCode = ReverseWordList?.Aggregate(hashCode, (current, count) => (current * 397) ^ comparer.GetHashCode(count)) ?? hashCode; hashCode = DataSet?.Aggregate(hashCode, (current, count) => (current * 397) ^ count.GetHashCode()) ?? hashCode; return(hashCode); } }
public Ordered(string restaurantUuid, List <OrderedItem> items) { this.RestaurantUuid = restaurantUuid; this.Items = items; this.Total = items?.Aggregate(0.0m, (acc, item) => acc + (item.Amount * item.UnitValue)) ?? 0.0m; }
public override void HandleCommand(IList<string> paramList, IrcUser user, bool isIngameCommand) { int i; // check if the params number 4, that the number/sides are integers, and that number and sides are both greater than 0 if (paramList.Count() == 3 && Int32.TryParse(paramList[1], out i) && Int32.TryParse(paramList[2], out i) && (Int32.Parse(paramList[1]) > 0) && (Int32.Parse(paramList[2]) > 0) && (Int32.Parse(paramList[1]) <= 4) && (Int32.Parse(paramList[2]) <= 100)) { var dice = Int32.Parse(paramList[1]); var sides = Int32.Parse(paramList[2]); var random = new Random(); var diceList = new List<int>(); for (var j = 0; j < dice; j++) { diceList.Add(random.Next(1, sides)); } var outputString = String.Format("Rolling a {0} sided die, {1} time{2}: {3}", sides, dice, (dice > 1) ? "s" : "", diceList.Aggregate("", (current, roll) => current + roll + " ").Trim()); Utils.SendChannel(outputString); } else { Utils.SendChannel("Usage: !dice <number 1-4 > <sides 1 - 100>"); } }
public static string ToString(List<string> result) { if (result.Count == 0) return ""; else return result.Aggregate((a, b) => a + b); }
protected override object GetValue(int rowIndex) { if (string.IsNullOrEmpty(stringValue)) { if (OwningRow.Index < 0) { return string.Empty; } tableAdaptor = (MySqlTableAdaptor)OwningColumn.Tag; var poinedRows = new List<DataRow>(); if (((DataRowView)OwningRow.DataBoundItem).Row[ColumnIndex + 1] != DBNull.Value) { poinedRows = tableAdaptor.GetObjectByIDs(new List<decimal> { (decimal)((DataRowView)OwningRow.DataBoundItem).Row[ColumnIndex + 1] }); } // Advanced string result = poinedRows.Aggregate(string.Empty, (current, dr) => current + (", " + dr["NAME"])); if (result.Length > 2) { stringValue = result.Substring(2); } } return stringValue; }
public IList <IApplicationModel> GetAll(string applicationName) { try { var storeData = new List <IApplicationModel>(); var endpoints = RedisMultiplexer.GetEndPoints(); var results = new List <string>(); foreach (var endpoint in endpoints) { var server = RedisMultiplexer.GetServer(endpoint); results.AddRange(server.Keys(pattern: $"{applicationName}:*").Select(key => Database.StringGet(key)).Select(dummy => (string)dummy)); } if (results.Any()) { var json = $"[{results?.Aggregate((prev, next) => $"{prev}, {next}")}]"; return(JsonConvert.DeserializeObject <IList <IApplicationModel> >(json, JsonConfiguration.Settings)); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(new List <IApplicationModel>()); }
public static int GetProcessIdByWindowTitle(string appTitle) { var processes = Process.GetProcesses().ToList(); var ws = processes.Where(p => p.ToString().Contains("WORD")).ToList(); foreach (var process1 in ws) { List<string> sList = new List<string>(); foreach (ProcessModule module in process1.Modules) { sList.Add(module.FileName); } sList.Sort(); var txt = sList.Aggregate("", (a, b) => a + "\r\n" + b); } var process = processes.SingleOrDefault(p => p.MainWindowTitle.Equals(appTitle)); if (process != null) return process.Id; return -1; }
public GridRow(IEnumerable<IGridRenderable> renderables, Padding pad = null) { Renderables = renderables.ToList(); Pad = pad ?? new Padding(0, 0); Width = Renderables.Aggregate(0, (x, y) => y.Width); Height = Renderables.OrderBy(x => x.Height).First().Height; }
public string[] Find(int[] sortedSource) { var foundHoles = new string[0]; var counter = 0; for (var i = 0; i < sortedSource.Length; i++) { var result = new List<int>(); var tempStr = string.Empty; if (i >= sortedSource.Length - 1) continue; if (sortedSource[i + 1] - sortedSource[i] <= 1) continue; var holeSize = (sortedSource[i + 1] - sortedSource[i]) - 1; result.Add(sortedSource[i] + 1); if (holeSize > 1) { result.Add(sortedSource[i] + holeSize); } tempStr = result.Aggregate(tempStr, (current, t) => current + $"{t}-"); Array.Resize(ref foundHoles, foundHoles.Length + 1); foundHoles[counter] = tempStr.Substring(0, tempStr.Length - 1); counter++; } return foundHoles; }
public bool Solve(out Dictionary<Tuple<int, int>, double> sol) { _basePlanValues = CalculateBasePlan(); _basePlan = _basePlanValues.Keys.ToList(); //Console.WriteLine("Base plan:\n{0}\n", _basePlan.Aggregate("", (acc, x) => String.Format("{0} ({1}, {2};)", acc, x.Item1, x.Item2))); for(int i =0; i < _iterationsCount; i++) { Console.WriteLine("Iteration #{0}\n", i); Console.WriteLine("Base plan:\n{0}\n", _basePlan.Aggregate("", (acc, x) => String.Format("{0} ({1}, {2};)", acc, x.Item1, x.Item2))); Step1CalculatePotencials(); Console.WriteLine("Potencials A:\n {0}\n", _aPotencials.Aggregate("", (a, x) => a + x + "; ")); Console.WriteLine("Potencials B:\n {0}\n", _bPotencials.Aggregate("", (a, x) => a + x + "; ")); Step2CalculateEstimations(); Console.WriteLine("Estimations:\n{0}\n", _estimations.ToString()); WriteCostMatrix(); if (Step3CheckForOptimum()) { sol = _basePlanValues; return true; } Step4GetPositiveEstimation(); double tet0; Tuple<int, int> tet0Point; Step5BuildCycle(out tet0, out tet0Point); Step6BuildNewBasePlanValues(tet0); Step7BuilNewBasePlan(tet0, tet0Point); } throw new Exception("iterations limit"); }
public OpenFileResult OpenFile(string customFilter, bool multiselect) { List<string> baseFilters = new List<string>(); if (!string.IsNullOrEmpty(customFilter)) { baseFilters.Add(customFilter); } baseFilters.Add(Resources.Translations.FilterAllSupported); baseFilters.Add(Resources.Translations.FilterAllFiles); string delimiter = "|"; string filter = baseFilters.Aggregate((i, j) => i + delimiter + j); OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = filter; dialog.FilterIndex = 1; dialog.Multiselect = multiselect; List<OpenedFile> openedFiles = new List<OpenedFile>(); if (dialog.ShowDialog() == true) { string[] fileNames = dialog.FileNames; foreach (var filePath in fileNames) { string fileName = Path.GetFileName(filePath); Stream stream = File.OpenRead(filePath); openedFiles.Add(new OpenedFile(stream, fileName)); } } return new OpenFileResult(openedFiles); }
public static INode CloneNode(this INode node, List<int> path, INode newRoot, INode[] newRoots, ISelectOutput result) { path.Clear(); while (true) { var rootIndex = Array.IndexOf(result.Roots, node); if (rootIndex != -1) { newRoot = newRoots[rootIndex]; break; } var p = node.Parent; if (p == null) { break; } path.Add(p.IndexOfChild(node)); node = p; } if (newRoot == null) { throw new InvalidOperationException("Something strange: a root of selected nodes is not listed in root array."); } path.Reverse(); newRoot = path.Aggregate(newRoot, (current, cNum) => current.Children[cNum]); return newRoot; }
public static List<int> GetAllPrimeFactors(this int number) { var factors = new List<int>(); var root = (int)Math.Sqrt(number); for (var j = 1; j <= root; j++) { if (number % j != 0) continue; if (j.IsPrime()) factors.Add(j); else if(j != number) factors.AddRange(j.GetAllPrimeFactors()); if ((number/j).IsPrime()) factors.Add(number/j); else if ((number / j) != number) factors.AddRange((number/j).GetAllPrimeFactors()); if (factors.Aggregate(1, (current, factor) => current*factor) == number) break; } return factors; }
public ReplayStats(IReplay replayer) { _replayer = replayer; _vectors = replayer.Vectors.ToList(); TotalSegments = _vectors.Count(); StartTime = _vectors[0].Time; EndTime = _vectors[TotalSegments - 1].Time; TotalTime = EndTime - StartTime; Velocities = new List<double>(); Velocities.Add(0); for (var i = 1; i < TotalSegments; i++) { var distance = _vectors[i].Vector.magnitude; var time = (_vectors[i].Time - _vectors[i - 1].Time).TotalMilliseconds; if (time == 0) Velocities.Add(0); else Velocities.Add(distance / time); } var sortedVelocities = Velocities.OrderBy(x => x).ToList (); MaxVelocity = sortedVelocities.Last(); MinVelocity = sortedVelocities.First(); TotalDistance = _vectors.Aggregate(0f, (x, y) => y.Vector.magnitude); AverageVelocity = Velocities.Aggregate(0f, (x, y) => (float)(x + y)) / Velocities.Count; }
public Sequence GetSequence(string sequence) { const string aminoAcidRegex = @"[" + AminoAcid.StandardAminoAcidCharacters + "]"; const string massRegex = @"\(\d+\.\d+\("; char[] parens = {'(', ')'}; if (!Regex.IsMatch(sequence, "(" + aminoAcidRegex + "|" + massRegex + ")+")) return null; var stdAaSet = StandardAminoAcidSet; var aaList = new List<AminoAcid>(); var matches = Regex.Matches(sequence, "(" + aminoAcidRegex + "|" + massRegex + ")"); AminoAcid aa = null; var mods = new List<Modification>(); foreach (Match match in matches) { var element = match.Value; if (element.Length == 0) continue; if (element.Length == 1 && char.IsLetter(element[0])) // amino acid { if (aa != null) { aa = mods.Aggregate(aa, (current, mod) => new ModifiedAminoAcid(current, mod)); aaList.Add(aa); mods.Clear(); } aa = stdAaSet.GetAminoAcid(element[0]); if (aa == null) throw new Exception("Unrecognized amino acid character: " + element[0]); // Console.WriteLine("{0} {1} {2}", aa.Residue, aa.Composition, aa.GetMass()); } else { element = element.Trim(parens); IList<Modification> modList; AminoAcid modAa; try { modList = Modifications[element].Item2; modAa = Modifications[element].Item1; } catch (KeyNotFoundException) { throw new Exception("Unrecognized modificaion mass: " + element); } // if (modList == null || modList.Count == 1) throw new Exception("Unrecognized modificaion mass: " + element); aa = modAa; mods.AddRange(modList); // Console.WriteLine("{0} {1} {2}", mod.Name, mod.Composition, mod.Composition.AveragineMass); } } if (aa != null) { aa = mods.Aggregate(aa, (current, mod) => new ModifiedAminoAcid(current, mod)); aaList.Add(aa); } return new Sequence(aaList); }
public static List<long> GetAllPrimeFactors(this BigInteger number) { var factors = new List<long>(); var root = (long)Math.Sqrt(Convert.ToDouble(number.ToString())); for (long j = 1; j <= root; j++) { if (number % j != 0) continue; if (j.IsPrime()) factors.Add(j); else if (j != number) factors.AddRange(j.GetAllPrimeFactors()); if ((number / j).IsPrime()) factors.Add(Convert.ToInt64((number / j).ToString())); else if ((number / j) != number) factors.AddRange((number / j).GetAllPrimeFactors()); if (factors.Aggregate<long, long>(1, (current, factor) => current * factor) == number) break; } return factors; }
public string GetAllCultures() { var list=new List<string>{DictionaryAttribute.DefaultLanguage}; list.AddRange(CultureInfo.GetCultures(CultureTypes.AllCultures).Select(info => new CultureDescription(info).ToString())); string s = list.Aggregate("", (current, list1) => current + (list1 + ";")); return s.TrimEnd(';'); }
/// <summary> /// <param name="locations">A 2D map of locations on the surface of earth. </param> /// </summary> public void FillElevationData(ref LatLonAlt[,] locations) { CultureInfo ci = new CultureInfo("en-US"); List<string> loc = new List<string>(); for (int J = 0; J < locations.GetLength(0); J++) { for (int I = 0; I < locations.GetLength(1); I++) { loc.Add(String.Format(ci, "{0:0.0000},{1:0.0000}", locations[I, J].Latitude, locations[I, J].Longitude)); } } var url = String.Format("http://maps.googleapis.com/maps/api/elevation/xml?sensor=false&locations={0}", loc.Aggregate((i, j) => i + "|" + j)); Console.WriteLine("Fetching elevation data from maps.googleapis.com..."); XmlDocument elevationData = new XmlDocument(); elevationData.Load(url); XmlNodeList xmlNodeList = elevationData.SelectNodes("/ElevationResponse/result/elevation"); var di = 0; // A local counter int x = 0; // the I-index of the matrix int y = 0; // the J-index of the matrix. foreach (XmlNode xmlNode in xmlNodeList) { // Update locations directly as we're spinning through all XML nodes. locations[x, y].Altitude = double.Parse(xmlNode.InnerText, ci.NumberFormat); di++; x = di % locations.GetLength(0); if (x == 0) y++; } }
/// <summary> /// 查询单个实体包含子结果集 /// </summary> /// <param name="predicateList"></param> /// <param name="includeNames"></param> /// <returns></returns> public async Task <TEntity> QueryEntityAsync(List <AprilPredicate <TEntity> > predicateList, List <string> includeNames) { var query = GetAll(); query = query.WhereIf(predicateList); includeNames?.Aggregate(query, (current, item) => current.Include(item)); return(await query.FirstOrDefaultAsync()); }
/// <summary> /// 根据条件插叙包含子结果集并排序 /// </summary> /// <param name="predicateList"></param> /// <param name="orderby"></param> /// <param name="includeNames"></param> /// <returns></returns> public async Task <List <TEntity> > QueryAsync(List <AprilPredicate <TEntity> > predicateList, string orderby, List <string> includeNames) { var query = GetAll(); query = query.WhereIf(predicateList); includeNames?.Aggregate(query, (current, item) => current.Include(item)); return(await query.OrderBy(orderby).ToListAsync()); }
/// <summary> /// 根据条件查询并包含子结果集 /// </summary> /// <param name="predicateListm"></param> /// <param name="includeNames"></param> /// <returns></returns> public IQueryable <TEntity> Query(List <AprilPredicate <TEntity> > predicateListm, List <string> includeNames) { var query = GetAll(); query = query.WhereIf(predicateListm); includeNames?.Aggregate(query, (current, item) => current.Include(item)); return(query); }
private string PrepareScopes() { var scopesString = _authenticationScopesList?.Aggregate((string arg1, string arg2) => { return(string.Concat(arg1, ",", arg2)); }); return(scopesString); }
public virtual void RunThroughPipeline(T data) { // Rebuilds library on fail if (_pipeList == null || _pipeList.Count == 0) { BuildPipelineLibrary(); } // Runs through out all translators _pipeList?.Aggregate(data, (current, processor) => processor.Translate(current)); }
protected override string LegendsDescription() { var timestring = base.LegendsDescription(); var competitorsString = Hfs_Competitor?.Aggregate("", (current, hf) => current + $"the {hf.Race.ToString().ToLower()} {hf}, "); competitorsString = competitorsString?.Trim().TrimEnd(',') ?? "UNKNOWN"; return ($"{timestring} {Entity} held a UNKNOWN competition in {Site.AltName} as part of {EventCollection.Name ?? "UNKNOWN"}. \nCompeting were {competitorsString}. \nThe {Hf_Winner?.Race.ToString().ToLower() ?? ""} {Hf_Winner} was the victor."); }
public IHttpActionResult Post(NewOrder data) { using (var context = new DatabaseContext()) { try { var client = data.ClientId != null?context.Clients.Find(data.ClientId) : null; var products = new List <OrderProduct>(); if (data.Products != null) { foreach (var orderProductInfo in data.Products) { var p = context.Products.Find(orderProductInfo.ProductId); if (p != null) { products.Add(new OrderProduct { Product = p, Amount = orderProductInfo.Amount, Date = DateTime.Now }); } else { return(BadRequest($"Produto {orderProductInfo.ProductId} não encontrado.")); } } } double value = products?.Aggregate(0.0, (sum, next) => sum + (next.Amount * next.Product.Price)) ?? 0; data.Discount = Math.Max(0, data.Discount); double totalValue = Math.Max(value - data.Discount, 0); var order = new Order() { Date = DateTime.Now, Client = client, Products = products, Value = value, Discount = data.Discount, TotalValue = totalValue }; order = context.Orders.Add(order); context.SaveChanges(); return(Ok <OrderInfo>(getInfo(order))); } catch (DbEntityValidationException validationException) { return(BadRequest(validationException.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage)); } } }
/// <summary> /// 获取分页包含子结果集 /// </summary> /// <param name="predicateList"></param> /// <param name="pageQueryEntity"></param> /// <param name="includeNames"></param> /// <returns></returns> public async Task <Tuple <List <TEntity>, int> > QueryAsync(List <AprilPredicate <TEntity> > predicateList, PageQueryEntity pageQueryEntity, List <string> includeNames) { var query = GetAll(); includeNames?.Aggregate(query, (current, item) => current.Include(item)); var totalCount = query.Count(); var data = await query .OrderBy(pageQueryEntity.Sorting) .PageBy(pageQueryEntity.SkipCount, pageQueryEntity.MaxResultCount) .ToListAsync(); return(new Tuple <List <TEntity>, int>(data, totalCount)); }
/// <summary> /// Represents a dominos menu item, like a pizza. /// </summary> /// <param name="code">The product code, (ex. a 12-in pizza's code is "14SCREEN".) This data will /// be returned as part of menu query requests.</param> /// <param name="quantity">How many of this product to order.</param> /// <param name="toppingModifiers">Some menu items can take modifiers. For example, a /// 14-in pizza can have topping modifiers that specify to add peperoni or sausage. In /// the pepperoni example, we ultimatly need to build a modifier JSON string that looks /// like "{C: {1/1: "1"}, P: {1/1: "1"}, X: {1/1: "1"}}}". So for a pepperoni pizza, the /// user would pass in a list with three strings: "C", "P", and "X". Topping specifications /// may be found via a menu query request.</param> public Product(string code, int quantity, List <string> toppingModifiers = null) { Code = code; Quantity = quantity; IsNew = true; Options = toppingModifiers?.Aggregate(new JObject(), (retval, modifierLabel) => { var modifier = new JObject(); modifier["1/1"] = "1"; // Unclear where this comes from, but I've never seen it be anything else. retval[modifierLabel] = modifier; return(retval); }); }
public void All_Fields_Are_Defined() { var assemblyContent = this.LoadAssemblyContent(); var notDefinedFields = new List <string>(); var employeeFields = this.GetAllNonPublicFields(assemblyContent); foreach (var field in _fields) { var instanceField = employeeFields.FirstOrDefault(f => f.Name.ToLower().Contains(field)); if (instanceField == null) { notDefinedFields.Add(field); } } if (notDefinedFields.Count == 0) { notDefinedFields = null; } Assert.IsNull(notDefinedFields, $"Fields: {notDefinedFields?.Aggregate((previous, next) => $"'{previous}', {next}")} are not defined."); }
public void All_Fields_Are_Defined() { var notDefinedFields = new List <string>(); var vehicleFields = _vehicleType.GetFields( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); foreach (var field in _fields) { var vField = vehicleFields.FirstOrDefault(f => f.Name.ToLowerInvariant().Contains(field)); if (vField == null) { notDefinedFields.Add(field); } } if (notDefinedFields.Count == 0) { notDefinedFields = null; } Assert.IsNull( notDefinedFields, $"Some field(s) is(are) not define: {notDefinedFields?.Aggregate((previous, next) => $"'{previous}', '{next}'")}"); }
/// <summary> /// Creates javascript string from column to be included in grid javascript /// </summary> /// <returns></returns> public override string ToString() { var script = new StringBuilder(); // Start column script.Append("{").AppendLine(); // Align if (_align.HasValue) { script.AppendFormat("align:'{0}',", _align.ToString().ToLower()).AppendLine(); } // Classes if (_classes.Count > 0) { script.AppendFormat("classes:'{0}',", string.Join(" ", (from c in _classes select c).ToArray())). AppendLine(); } // Columnname script.AppendFormat("name:'{0}',", Name).AppendLine(); // FirstSortOrder if (_firstSortOrder.HasValue) { script.AppendFormat("firstsortorder:'{0}',", _firstSortOrder.ToString().ToLower()).AppendLine(); } // FixedWidth if (_fixedWidth.HasValue) { script.AppendFormat("fixed:{0},", _fixedWidth.Value.ToString().ToLower()).AppendLine(); } // Formatters if (_formatter.HasValue && _formatter.Value.Value.IsMissing()) { script.AppendFormat("formatter:'{0}',", _formatter.Value.Key.ToString().ToLower()).AppendLine(); } if (_formatter.HasValue && !_formatter.Value.Value.IsMissing()) { script.AppendLine("formatter:'" + _formatter.Value.Key.ToString().ToLower() + "', formatoptions: {" + _formatter.Value.Value + "},"); } // Custom formatter if (!_customFormatter.IsMissing()) { script.AppendFormat("formatter:{0},", _customFormatter).AppendLine(); } if (_operButtons.Any()) { //script.Append("formatter:function (value, grid, rows, state){ return \"<p>" + string.Join("", _operButtons.Select(o => o.ToString())) + "</p>\" },").AppendLine(); script.Append("formatter:function (cellValue, options, rowObject){ return \"<p>" + string.Join("", _operButtons.Select(o => o.ToString())) + "</p>\" },").AppendLine(); } if (!_unFormat.IsMissing()) { script.AppendFormat(" unformat: {0},", _unFormat).AppendLine(); } if (!_dataInit.IsMissing()) { script.AppendFormat("dataInit: {0},", _dataInit).AppendLine(); } // Hidden if (_hidden.HasValue) { script.AppendFormat("hidden:{0},", _hidden.Value.ToString().ToLower()).AppendLine(); } //hidedlg if (_hidedlg.HasValue) { script.AppendFormat("hidedlg:{0},", _hidedlg.Value.ToString().ToLower()).AppendLine(); } // Key if (_key.HasValue) { script.AppendFormat("key:{0},", _key.Value.ToString().ToLower()).AppendLine(); } // Label if (!_label.IsMissing()) { script.AppendFormat("label:'{0}',", _label).AppendLine(); } // Resizable if (_resizeable.HasValue) { script.AppendFormat("resizable:{0},", _resizeable.Value.ToString().ToLower()).AppendLine(); } // Search if (_search.HasValue) { script.AppendFormat("search:{0},", _search.Value.ToString().ToLower()).AppendLine(); } // Sortable if (_sortable.HasValue) { script.AppendFormat("sortable:{0},", _sortable.Value.ToString().ToLower()).AppendLine(); } // Title if (_title.HasValue) { script.AppendFormat("title:{0},", _title.Value.ToString().ToLower()).AppendLine(); } // Width if (_width.HasValue) { script.AppendFormat("width:{0},", _width.Value).AppendLine(); } if (_colmenu.HasValue) { script.AppendFormat("colmenu:{0},", _colmenu.Value.ToString().ToLower()).AppendLine(); } // Editable if (_editable.HasValue) { script.AppendFormat("editable:{0},", _editable.Value.ToString().ToLower()).AppendLine(); } // Setup search options var searchOptions = new Dictionary <string, string>(); // SearchType if (_searchType.HasValue) { if (_searchType.Value == Searchtype.Text || _searchType.Value == Searchtype.Reference) { script.AppendLine("stype:'text',"); } if (_searchType.Value == Searchtype.Select) { script.AppendLine("stype:'select',"); } if (_searchOptions.Any()) { searchOptions.Add("sopt", string.Format("['{0}']", _searchOptions.Aggregate((current, next) => current + "', '" + next))); } else { searchOptions.Add("sopt", "['bw']"); } } // SearchType select if (_searchType == Searchtype.Select) { if (_searchTerms != null) { var emtpyOption = (_searchTerms.Any()) ? "fapany:任意;" : ":"; searchOptions.Add("value", "\"" + string.Format("{0}{1}", emtpyOption, string.Join(";", _searchTerms.Select(s => s.Key + ":" + s.Value).ToArray())) + "\""); } else { searchOptions.Add("value", "'fapany:任意'"); } } else if (_searchType == Searchtype.Reference) { searchOptions.Add("dataInit", "function(el){searchOptionReference(el,'" + _fapColumn.ColComment + "','" + _fapColumn.Fid + "','" + _fapColumn.RefType + "');}"); } // SearchType datepicker else if (_searchType == Searchtype.Datepicker) { string format = _searchDateFormat.IsMissing() ? "YYYY-MM-DD" : _searchDateFormat; if (format.EqualsWithIgnoreCase("yyyy-mm-dd")) { searchOptions.Add("dataInit", @"function(el){$(el).datepicker({format: 'yyyy-mm-dd',language: 'zh-CN', todayHighlight: true,autoclose: true})}"); } else if (format.EqualsWithIgnoreCase("yyyy-mm")) { //format = "YYYY-MM"; searchOptions.Add("dataInit", @"function(el){$(el).datepicker({format: 'yyyy-mm',language: 'zh-CN', autoclose: true, startView: 'months', maxViewMode: 'years', minViewMode: 'months'})}"); } else { searchOptions.Add("dataInit", @"function(el){$(el).datepicker({format: 'yyyy',language: 'zh-CN', autoclose: true, startView: 'years', maxViewMode: 'years', minViewMode: 'years'})}"); } } else if (_searchType == Searchtype.Datetimepicker) { string format = _searchDateFormat.IsMissing() ? "YYYY-MM-DD HH:mm:ss" : _searchDateFormat; if (format.EqualsWithIgnoreCase("HH:mm")) { searchOptions.Add("dataInit", @"function(el){$(el).datetimepicker({language:'zh-CN',startView:1,maxView:1,format:'hh:ii'}); // $(el).on('dp.change', // function (e) { // var sgrid = $('###gridid##')[0]; // sgrid.triggerToolbar();}); }"); } else { searchOptions.Add("dataInit", @"function(el){$(el).datetimepicker({language:'zh-CN',format:'yyyy-mm-dd hh:ii:ss'}); // $(el).on('dp.change', // function (e) { // var sgrid = $('###gridid##')[0]; // sgrid.triggerToolbar();}); }"); } } // SearchType if (_searchType.HasValue && !_defaultSearchValue.IsMissing()) { searchOptions.Add("defaultValue", "'" + _defaultSearchValue + "'"); } // Default value when no search type is set if ((!_searchType.HasValue && !_defaultSearchValue.IsMissing())) { searchOptions.Add("defaultValue", "'" + _defaultSearchValue + "'"); } // Clear search if (_clearSearch.HasValue) { searchOptions.Add("clearSearch", _clearSearch.Value.ToString().ToLower()); } // Search Option: sopt if (_searchOptions.Any() && !_searchType.HasValue) // When searchtype is set, searchoptions is already added { searchOptions.Add("sopt", "['" + _searchOptions.Aggregate((current, next) => current + "', '" + next) + "']"); } if (searchOptions.Any()) { script.AppendLine("searchoptions: { " + string.Join(", ", searchOptions.Select(x => x.Key + ":" + x.Value)) + " },"); } //edit type if (_editType.HasValue) { script.AppendFormat("edittype:'{0}',", _editType.Value.ToString().ToLower()).AppendLine(); } //edit options if (_editOptions != null) { script.AppendFormat("editoptions:{0},", _editOptions.ToString()).AppendLine(); } //edit rules if (_editRules != null) { script.AppendFormat("editrules:{0},", _editRules.ToString()).AppendLine(); } //edit form options if (_editFormOptions != null) { script.AppendFormat("formoptions:{0},", _editFormOptions.ToString()).AppendLine(); } if (_sortType.HasValue) { script.AppendFormat("sorttype:'{0}',", _sortType.ToString().ToLower()).AppendLine(); } // Index script.AppendFormat("index:'{0}'", _index).AppendLine(); // End column script.Append("}"); return(script.ToString()); }
public static void GetCreatureFlags(string creatureEntry) { DataSet unitFlagsDs = new DataSet(); string unitFlagsSqlQuery = "SELECT `npcflag`, `npcflag2`, `unit_flags`, `unit_flags2`, `dynamicflags`, `flags_extra`, `TypeFlags`, `TypeFlags2` FROM `creature_template` WHERE `entry` = " + creatureEntry + ";"; unitFlagsDs = SQLModule.DatabaseSelectQuery(unitFlagsSqlQuery); if (unitFlagsDs == null) { return; } if (unitFlagsDs.Tables["table"].Rows.Count == 0) { MessageBox.Show("Creature doesn't exists in your database!"); return; } long npcFlags = Convert.ToInt64(unitFlagsDs.Tables["table"].Rows[0][0].ToString()); long npcFlags2 = Convert.ToInt64(unitFlagsDs.Tables["table"].Rows[0][1].ToString()); long unitFlags = Convert.ToInt64(unitFlagsDs.Tables["table"].Rows[0][2].ToString()); long unitFlags2 = Convert.ToInt64(unitFlagsDs.Tables["table"].Rows[0][3].ToString()); long dynamicFlags = Convert.ToInt64(unitFlagsDs.Tables["table"].Rows[0][4].ToString()); long extraFlags = Convert.ToInt64(unitFlagsDs.Tables["table"].Rows[0][5].ToString()); long typeFlags = Convert.ToInt64(unitFlagsDs.Tables["table"].Rows[0][6].ToString()); long typeFlags2 = Convert.ToInt64(unitFlagsDs.Tables["table"].Rows[0][7].ToString()); List <long> npcFlagsList = new List <long>(); List <long> npcFlags2List = new List <long>(); List <long> unitFlagsList = new List <long>(); List <long> unitFlags2List = new List <long>(); List <long> unitFlags3List = new List <long>(); List <long> dynamicFlagsList = new List <long>(); List <long> extraFlagsList = new List <long>(); List <long> typeFlagsList = new List <long>(); List <long> typeFlags2List = new List <long>(); if (npcFlags != 0) { var flagsArray = Enum.GetValues(typeof(NpcFlags)); Array.Reverse(flagsArray); foreach (long flag in flagsArray) { if (npcFlags - flag >= 0) { npcFlagsList.Add(flag); npcFlags -= flag; } } } if (npcFlags2 != 0) { var flagsArray = Enum.GetValues(typeof(NpcFlags2)); Array.Reverse(flagsArray); foreach (long flag in flagsArray) { if (npcFlags2 - flag >= 0) { npcFlags2List.Add(flag); npcFlags2 -= flag; } } } if (unitFlags != 0) { var flagsArray = Enum.GetValues(typeof(UnitFlags)); Array.Reverse(flagsArray); foreach (long flag in flagsArray) { if (unitFlags - flag >= 0) { unitFlagsList.Add(flag); unitFlags -= flag; } } } if (unitFlags2 != 0) { var flagsArray = Enum.GetValues(typeof(UnitFlags2)); Array.Reverse(flagsArray); foreach (long flag in flagsArray) { if (unitFlags2 - flag >= 0) { unitFlags2List.Add(flag); unitFlags2 -= flag; } } } if (dynamicFlags != 0) { var flagsArray = Enum.GetValues(typeof(DynamicFlags)); Array.Reverse(flagsArray); foreach (long flag in flagsArray) { if (dynamicFlags - flag >= 0) { dynamicFlagsList.Add(flag); dynamicFlags -= flag; } } } if (extraFlags != 0) { var flagsArray = Enum.GetValues(typeof(FlagsExtra)); Array.Reverse(flagsArray); foreach (long flag in flagsArray) { if (extraFlags - flag >= 0) { extraFlagsList.Add(flag); extraFlags -= flag; } } } if (typeFlags != 0) { var flagsArray = Enum.GetValues(typeof(TypeFlags)); Array.Reverse(flagsArray); foreach (long flag in flagsArray) { if (typeFlags - flag >= 0) { typeFlagsList.Add(flag); typeFlags -= flag; } } } if (typeFlags2 != 0) { var flagsArray = Enum.GetValues(typeof(TypeFlags2)); Array.Reverse(flagsArray); foreach (long flag in flagsArray) { if (typeFlags2 - flag >= 0) { typeFlags2List.Add(flag); typeFlags2 -= flag; } } } npcFlagsList.Sort(); npcFlags2List.Sort(); unitFlagsList.Sort(); unitFlags2List.Sort(); unitFlags3List.Sort(); dynamicFlagsList.Sort(); extraFlagsList.Sort(); typeFlagsList.Sort(); typeFlags2List.Sort(); string outputText = ""; if (npcFlagsList.Count > 0) { outputText += "Creature has the following NpcFlags: \r\n"; outputText = npcFlagsList.Aggregate(outputText, (current, itr) => current + ((NpcFlags)itr + ": " + itr + "\r\n")); } else { outputText += "Creature doesn't have any NpcFlags!\r\n"; } if (npcFlags2List.Count > 0) { outputText += "Creature has the following NpcFlags2: \r\n"; outputText = npcFlags2List.Aggregate(outputText, (current, itr) => current + ((NpcFlags2)itr + ": " + itr + "\r\n")); } else { outputText += "Creature doesn't have any NpcFlags2!\r\n"; } if (unitFlagsList.Count > 0) { outputText += "Creature has the following UnitFlags: \r\n"; outputText = unitFlagsList.Aggregate(outputText, (current, itr) => current + ((UnitFlags)itr + ": " + itr + "\r\n")); } else { outputText += "Creature doesn't have any UnitFlags!\r\n"; } if (unitFlags2List.Count > 0) { outputText += "Creature has the following UnitFlags2: \r\n"; outputText = unitFlags2List.Aggregate(outputText, (current, itr) => current + ((UnitFlags2)itr + ": " + itr + "\r\n")); } else { outputText += "Creature doesn't have any UnitFlags2!\r\n"; } if (unitFlags3List.Count > 0) { outputText += "Creature has the following UnitFlags3: \r\n"; outputText = unitFlags3List.Aggregate(outputText, (current, itr) => current + ((UnitFlags3)itr + ": " + itr + "\r\n")); } else { outputText += "Creature doesn't have any UnitFlags3!\r\n"; } if (dynamicFlagsList.Count > 0) { outputText += "Creature has the following DynamicFlags: \r\n"; outputText = dynamicFlagsList.Aggregate(outputText, (current, itr) => current + ((DynamicFlags)itr + ": " + itr + "\r\n")); } else { outputText += "Creature doesn't have any DynamicFlags!\r\n"; } if (extraFlagsList.Count > 0) { outputText += "Creature has the following ExtraFlags: \r\n"; outputText = extraFlagsList.Aggregate(outputText, (current, itr) => current + ((FlagsExtra)itr + ": " + itr + "\r\n")); } else { outputText += "Creature doesn't have any ExtraFlags!\r\n"; } if (typeFlagsList.Count > 0) { outputText += "Creature has the following TypeFlags: \r\n"; outputText = typeFlagsList.Aggregate(outputText, (current, itr) => current + ((TypeFlags)itr + ": " + itr + "\r\n")); } else { outputText += "Creature doesn't have any TypeFlags!\r\n"; } if (typeFlags2List.Count > 0) { outputText += "Creature has the following TypeFlags2: \r\n"; outputText = typeFlags2List.Aggregate(outputText, (current, itr) => current + ((TypeFlags2)itr + ": " + itr + "\r\n")); } else { outputText += "Creature doesn't have any TypeFlags2!\r\n"; } MessageBox.Show(outputText); }
private Exp WhereConditional( ICollection <int> exceptIDs, String searchText, Guid responsibleID, int milestoneID, IEnumerable <String> tags, int contactID, DealMilestoneStatus?stageType, bool?contactAlsoIsParticipant) { var conditions = new List <Exp>(); var ids = new List <int>(); if (!String.IsNullOrEmpty(searchText)) { searchText = searchText.Trim(); var keywords = searchText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray(); if (keywords.Length > 0) { if (!BundleSearch.TrySelectOpportunity(searchText, out ids)) { conditions.Add(BuildLike(new[] { "tblDeal.title", "tblDeal.description" }, keywords)); } else if (ids.Count == 0) { return(null); } } } if (tags != null && tags.Any()) { ids = SearchByTags(EntityType.Opportunity, ids.ToArray(), tags); if (ids.Count == 0) { return(null); } } if (contactID > 0) { if (contactAlsoIsParticipant.HasValue && contactAlsoIsParticipant.Value) { var relativeContactsID = GetRelativeToEntity(contactID, EntityType.Opportunity, null).ToList(); if (relativeContactsID.Count == 0) { conditions.Add(Exp.Eq("tblDeal.contact_id", contactID)); } else { if (ids.Count > 0) { ids = relativeContactsID.Intersect(ids).ToList(); if (ids.Count == 0) { return(null); } } else { ids = relativeContactsID; } } } else { conditions.Add(Exp.Eq("tblDeal.contact_id", contactID)); } } if (0 < milestoneID && milestoneID < int.MaxValue) { conditions.Add(Exp.Eq("tblDeal.deal_milestone_id", milestoneID)); } if (responsibleID != Guid.Empty) { conditions.Add(Exp.Eq("tblDeal.responsible_id", responsibleID)); } if (stageType != null) { conditions.Add(Exp.Eq("tblDM.status", (int)stageType.Value)); } if (ids.Count > 0) { if (exceptIDs.Count > 0) { ids = ids.Except(exceptIDs).ToList(); if (ids.Count == 0) { return(null); } } conditions.Add(Exp.In("tblDeal.id", ids)); } else if (exceptIDs.Count > 0) { conditions.Add(!Exp.In("tblDeal.id", exceptIDs.ToArray())); } if (conditions.Count == 0) { return(null); } return(conditions.Count == 1 ? conditions[0] : conditions.Aggregate((i, j) => i & j)); }
/// <inheritdoc /> public IList <IGenome> Flatten() { IList <IGenome> result = new List <IGenome>(); return(_species.Aggregate(result, (current, species) => current.Union(species.Members).ToList())); }
// public TSelf Called ( string name ) => Do(p => p.Name = name); // public FuncPersonBuilder WorkAtAs(string position) => Do(w => w.Position = position); public TSubject Build() => actions.Aggregate(new TSubject(), (p, f) => f(p));
/// <summary> /// Backbone for <see cref="CountAsync(CancellationToken, int)"/>, <see cref="ToListAsync(CancellationToken)"/> and <see cref="ToListAndCountAsync(CancellationToken)"/> /// </summary> private async Task <(List <T> result, int count)> ToListAndCountInnerAsync(bool includeCount, int maxCount, CancellationToken cancellation) { var args = await _factory(cancellation); var conn = args.Connection; var sources = args.Sources; var userId = args.UserId; var userToday = args.UserToday; var localizer = args.Localizer; var i = args.Instrumentation; var logger = args.Logger; using var _ = i.Block("Query.ToListAndCountInnerAsync"); IDisposable block; block = i.Block("Get Descriptor"); var resultDesc = TypeDescriptor.Get <T>(); block.Dispose(); block = i.Block("Validate Paths and Props"); _orderby ??= (IsEntityWithKey() ? ExpressionOrderBy.Parse("Id desc") : throw new InvalidOperationException($"Query<{resultDesc.Type.Name}> was executed without an orderby clause")); // Prepare all the query parameters ExpressionSelect selectExp = _select; ExpressionExpand expandExp = _expand; ExpressionOrderBy orderbyExp = _orderby; ExpressionFilter filterExp = _filterConditions?.Aggregate( (e1, e2) => ExpressionFilter.Conjunction(e1, e2)); // To prevent SQL injection ValidatePathsAndProperties(selectExp, expandExp, filterExp, orderbyExp, resultDesc, localizer); // ------------------------ Step #1 block.Dispose(); block = i.Block("Prepare QueryInternals"); // Segment the paths of select and expand along the one-to-many relationships, each one-to-many relationship will // result in a new internal query for the child collection with the original query as its principal query var segments = new Dictionary <ArraySegment <string>, QueryInternal>(new PathEqualityComparer()); // Helper method for creating a an internal query, will be used later in both the select and the expand loops QueryInternal MakeFlatQuery(ArraySegment <string> previousFullPath, ArraySegment <string> subPath, TypeDescriptor desc) { QueryInternal principalQuery = previousFullPath == null ? null : segments[previousFullPath]; ArraySegment <string> pathToCollectionPropertyInPrincipal = previousFullPath == null ? null : subPath; if (principalQuery != null && desc.KeyType == KeyType.None) { // Programmer mistake throw new InvalidOperationException($"[Bug] Type {desc.Name} has no Id property, yet it is used as a navigation collection on another entity"); } string foreignKeyToPrincipalQuery = null; bool isAncestorExpand = false; if (principalQuery != null) { // This loop retrieves the entity descriptor that has the collection property TypeDescriptor collectionPropertyEntity = principalQuery.ResultDescriptor; int i = 0; for (; i < pathToCollectionPropertyInPrincipal.Count - 1; i++) { var step = pathToCollectionPropertyInPrincipal[i]; collectionPropertyEntity = collectionPropertyEntity.NavigationProperty(step).TypeDescriptor; } // Get the collection/Parent property string propertyName = pathToCollectionPropertyInPrincipal[i]; var property = collectionPropertyEntity.Property(propertyName); if (property is NavigationPropertyDescriptor navProperty && navProperty.IsParent) { foreignKeyToPrincipalQuery = "ParentId"; isAncestorExpand = true; } else if (property is CollectionPropertyDescriptor collProperty) { // Must be a collection then foreignKeyToPrincipalQuery = collProperty.ForeignKeyName; } else { throw new InvalidOperationException($"Bug: Segment along a property {property.Name} on type {collectionPropertyEntity.Name} That is neither a collection nor a parent"); } } if (isAncestorExpand) { // the path to parent entity is the path above minus the "Parent" var pathToParentEntity = new ArraySegment <string>( array: pathToCollectionPropertyInPrincipal.Array, offset: 0, count: pathToCollectionPropertyInPrincipal.Count - 1); // Adding this causes the principal query to always include ParentId in the select clause principalQuery.PathsToParentEntitiesWithExpandedAncestors.Add(pathToParentEntity); } // This is the orderby of related queries, and the default orderby of the root query var defaultOrderBy = ExpressionOrderBy.Parse( desc.HasProperty("Index") ? "Index" : desc.HasProperty("SortKey") ? "SortKey" : "Id"); // Prepare the flat query and return it var flatQuery = new QueryInternal { PrincipalQuery = principalQuery, IsAncestorExpand = isAncestorExpand, PathToCollectionPropertyInPrincipal = pathToCollectionPropertyInPrincipal, ForeignKeyToPrincipalQuery = foreignKeyToPrincipalQuery, ResultDescriptor = desc, OrderBy = defaultOrderBy }; return(flatQuery); }
private Exp WhereConditional( ICollection <int> exceptIDs, String searchText, int contactID, bool?isClosed, IEnumerable <String> tags) { var conditions = new List <Exp>(); var ids = new List <int>(); if (!String.IsNullOrEmpty(searchText)) { searchText = searchText.Trim(); var keywords = searchText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); if (keywords.Length > 0) { if (!BundleSearch.TrySelectCase(searchText, out ids)) { conditions.Add(BuildLike(new[] { "title" }, keywords)); } else if (!ids.Any()) { return(null); } } } if (contactID > 0) { var sqlQuery = new SqlQuery("crm_entity_contact") .Select("entity_id") .Where(Exp.Eq("contact_id", contactID) & Exp.Eq("entity_type", (int)EntityType.Case)); if (ids.Count > 0) { sqlQuery.Where(Exp.In("entity_id", ids)); } ids = Db.ExecuteList(sqlQuery).Select(item => Convert.ToInt32(item[0])).ToList(); if (ids.Count == 0) { return(null); } } if (isClosed.HasValue) { conditions.Add(Exp.Eq("is_closed", isClosed)); } if (tags != null && tags.Any()) { ids = SearchByTags(EntityType.Case, ids.ToArray(), tags); if (ids.Count == 0) { return(null); } } if (ids.Count > 0) { if (exceptIDs.Count > 0) { ids = ids.Except(exceptIDs).ToList(); if (ids.Count == 0) { return(null); } } conditions.Add(Exp.In("id", ids)); } else if (exceptIDs.Count > 0) { conditions.Add(!Exp.In("id", exceptIDs.ToArray())); } if (conditions.Count == 0) { return(null); } return(conditions.Count == 1 ? conditions[0] : conditions.Aggregate((i, j) => i & j)); }
public static async Task <bool> SendEmail(MailAddress onBehalfOf, List <string> toAddress, List <string> ccAddress, List <string> bccAddress, string subject, string htmlBody, string plainBody = null, List <string> attachments = null, bool ignoreError = false) { SmtpClient smtpClient = new SmtpClient { }; MailMessage message = new MailMessage(); try { message.From = new MailAddress(Common.Email.Email_Default); toAddress?.ForEach(address => message.To.Add(address)); ccAddress?.ForEach(address => message.CC.Add(address)); bccAddress?.ForEach(address => message.Bcc.Add(address)); message.Subject = subject?.Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " "); if (onBehalfOf != null) { message.ReplyToList.Add(onBehalfOf.Address); message.From = onBehalfOf; } if (plainBody != null) { message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainBody, System.Text.Encoding.UTF8, MediaTypeNames.Text.Plain)); } if (htmlBody != null) { message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(htmlBody, System.Text.Encoding.UTF8, MediaTypeNames.Text.Html)); } attachments?.ForEach(attachment => { if (File.Exists(attachment)) { Attachment data = new Attachment(attachment, MediaTypeNames.Application.Octet); ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = File.GetCreationTime(attachment); disposition.ModificationDate = File.GetLastWriteTime(attachment); disposition.ReadDate = File.GetLastAccessTime(attachment); message.Attachments.Add(data); } }); await Task.Run(() => smtpClient.Send(message)); message.Dispose(); return(true); } catch (Exception ex) { if (ignoreError == false) { string errorMessage = "Error sending email"; errorMessage += "\n" + "To: "; errorMessage = toAddress?.Aggregate(errorMessage, (current, address) => current + address); errorMessage += "\n" + "CC: "; errorMessage = ccAddress?.Aggregate(errorMessage, (current, address) => current + address); errorMessage += "\n" + "Bcc: "; errorMessage = bccAddress?.Aggregate(errorMessage, (current, address) => current + address); errorMessage += "\n" + "Subject: " + subject; errorMessage += "\n\n" + "HtmlBody: " + htmlBody; errorMessage += "\n\n" + "PlainBody: " + plainBody; errorMessage += "\n\n" + "Error: " + ex.Message; throw new Exception(errorMessage); } return(false); } }
/// <summary> /// Sets visual form elements to specific values based on setting variables. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Settings_Load(object sender, EventArgs e) { tbMaxWidth.Text = maxWidth.ToString(); tbMaxHeight.Text = maxHeight.ToString(); cbOnTop.Checked = onTop; tbTimer.Text = parentForm.CreateTimerString(hh, mm, ss, 2); if (hh == 0) { if (mm == 0) { if (ss == 15) { tTimerTrackBar.Value = 0; } else if (ss == 30) { tTimerTrackBar.Value = 1; } } else if (mm == 1) { if (ss == 0) { tTimerTrackBar.Value = 2; } else if (ss == 30) { tTimerTrackBar.Value = 3; } } else if (mm == 2) { if (ss == 0) { tTimerTrackBar.Value = 4; } else if (ss == 30) { tTimerTrackBar.Value = 5; } } else if (mm == 3) { tTimerTrackBar.Value = 6; } else if (mm == 5) { tTimerTrackBar.Value = 7; } else if (mm == 10) { tTimerTrackBar.Value = 8; } else if (mm == 15) { tTimerTrackBar.Value = 9; } else if (mm == 30) { tTimerTrackBar.Value = 10; } else { tTimerTrackBar.Value = 10; } } else if (hh == 1) { if (mm == 0) { tTimerTrackBar.Value = 11; } else if (mm == 30) { tTimerTrackBar.Value = 12; } else { tTimerTrackBar.Value = 11; } } else { tTimerTrackBar.Value = 12; } tbTimerBuffer.Text = timerBuffer.ToString(); cbCopy.Checked = copy; if (copy) { cbCopy.Text = "Copy"; } else { cbCopy.Text = "Cut"; } cbSearchAll.Checked = searchAll; tbExtensions.Text = ext?.Aggregate((a, b) => a + ", " + b); if (whitelist.Count > 0) { tbWhitelist.Text = whitelist?.Aggregate((a, b) => a + "\r\n" + b); } if (blacklist.Count > 0) { tbBlacklist.Text = blacklist?.Aggregate((a, b) => a + "\r\n" + b); } cbUseWhitelist.Checked = useWhitelist; cbUseBlacklist.Checked = useBlacklist; tbFileNameFilter.Text = fileNameFilter; tbListFileName.Text = fileListPath; tbListFileContents.Text = fileList; }
public RestaurantDevice GetDeviceIncludesByIdentity(long identity, List <string> includes) { var query = includes.Aggregate(EntitySet, (current, include) => current.Include(include)); return(query.SingleOrDefault(obj => obj.Identity == identity)); }
public static IQueryable <T> Where <T>(this IQueryable <T> query, List <Tuple <FilteringOption, Expression <Func <T, bool> > > > filterList) { return(filterList == null ? query : filterList.Aggregate(query, (current, filter) => current.Where(filter.Item2))); }
public override int GetHashCode() { return(selectors.Aggregate(37, (s, sel) => s * sel.GetHashCode())); }
/// <summary>Converts a value. </summary> /// <returns>A converted value. If the method returns null, the valid null value is used.</returns> /// <param name="value">The value produced by the binding source.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var result = _converters?.Aggregate(new[] { value }, (v, c) => _PerformConversion(c, v, targetType, parameter, culture)); return(result?[0]); }