private ConcurrentChatStatistics CalculateStatisticsFromMinuteDistribution(Dictionary<int, int> minuteDistribution) { var seed = new { Maximum = int.MinValue, ChatMinutes = 0.0, TotalMinutes = 0, }; var result = minuteDistribution.Aggregate(seed, (current, chats) => new { Maximum = Math.Max(current.Maximum, chats.Key), ChatMinutes = current.ChatMinutes + chats.Key * chats.Value, TotalMinutes = current.TotalMinutes + chats.Value }); var mean = result.ChatMinutes / result.TotalMinutes; var variance = minuteDistribution.Aggregate (0.0, (current, chats) => current + (chats.Key - mean) * (chats.Key - mean) * chats.Value) / result.TotalMinutes; return new ConcurrentChatStatistics { Maximum = result.Maximum, Mean = mean, StandardDeviation = Math.Sqrt(variance), PercentageByConcurrentChatCount = minuteDistribution .Select(kvp => new KeyValuePair<int, double>(kvp.Key, (double)kvp.Value / result.TotalMinutes)) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value) }; }
private string GetProcessArguments(ServiceInstance instance) { var configParameters = new Dictionary<string, string>(); configParameters.Add("log", instance.LogPath); configParameters.Add("db", instance.DbPath); configParameters.Add("run-projections", instance.RunProjections); if (!string.IsNullOrWhiteSpace(instance.InternalAddresses)) { configParameters.Add("int-http-prefixes", instance.InternalAddresses); } if (!string.IsNullOrWhiteSpace(instance.ExternalAddresses)) { configParameters.Add("ext-http-prefixes", instance.ExternalAddresses); } var externalIp = GetIp(instance.ExternalIP); configParameters.Add("ext-ip", externalIp); var internalIp = GetIp(instance.InternalIP); configParameters.Add("int-ip", internalIp); return configParameters.Aggregate("", (acc, next) => string.Format("{0} --{1} \"{2}\"", acc, next.Key, next.Value)); }
static void Main(string[] args) { Dictionary<int, int> triangles = new Dictionary<int, int>(); for (int p = 3; p < 1000; p++) { triangles.Add(p, 0); for (int a = 1; a < p; a++) for (int b = 1; b < p; b++) { if (a + b > 1000) break; int c = p - a - b; if ((a * a + b * b) == c * c) { triangles[p]++; } } } Console.WriteLine(triangles.Aggregate((l, r) => l.Value > r.Value ? l : r).Key); Console.Read(); }
protected static string ProcessVocabulary(string template, Dictionary<string, string> vocabulary) { return vocabulary.Aggregate(template, (current, vocabularyPair) => current.Replace(String.Format("{{{0}}}", vocabularyPair.Key), vocabularyPair.Value)); }
protected override object FindParameterValue(Match match, ICmsRenderer cmsRenderer, ICmsContext context, ITheme theme, Func<string, string> recurse) { var localizationNamespace = _findCurrentLocalizationNamespace.Find(); var key = !string.IsNullOrEmpty(localizationNamespace) ? string.Format("{0}:{1}", localizationNamespace, match.Groups["resource"].Value) : match.Groups["resource"].Value; var replacements = new Dictionary<string, string>(); var replacementsGroup = match.Groups["replacements"]; if (replacementsGroup != null && !string.IsNullOrEmpty(replacementsGroup.Value)) { var replacementsData = replacementsGroup .Value .Split(',') .Where(x => !string.IsNullOrEmpty(x)) .Select(x => x.Split(':')) .Where(x => x.Length > 1 && !string.IsNullOrEmpty(x[0]) && !string.IsNullOrEmpty(x[1])) .ToList(); foreach (var item in replacementsData) replacements[item[0]] = item[1]; } var localized = _localizeText.Localize(key, _findCultureForRequest.FindUiCulture()); localized = replacements.Aggregate(localized, (current, replacement) => current.Replace(string.Concat("{{", replacement.Key, "}}"), replacement.Value)); return recurse(localized); }
private static void Main(string[] args) { string[] strings = new string[int.Parse(Console.ReadLine())]; for (int i = 0; i < strings.Length; i++) { strings[i] = Console.ReadLine(); } Dictionary<string, int> Areas = new Dictionary<string, int>(); foreach (var item in strings) { if (Areas.ContainsKey(item)) { Areas[item]++; } else { Areas.Add(item, 1); } } for (int i = 0; i < Areas.Max(x => x.Value); i++) { Console.WriteLine(Areas.Aggregate((x, y) => y.Value > x.Value ? y : x).Key); } }
/// <summary> /// Sends the specified message to an SMTP server for delivery. /// </summary> /// <param name="recepientMails"> /// The mail addresses of the recepients. If multiple addresses are specified, /// they must be separated by the comma character /// </param> /// <param name="subject">The subject of the email</param> /// <param name="fileName">The name of the file that has the mail text</param> /// <param name="parameters">Parameters to pass in the mail text</param> public async Task<bool> SendMailAsync(string recepientMails, string subject, string fileName, Dictionary<string, string> parameters) { var filePath = HostingEnvironment.MapPath("~/Content/email_templates/"); try { string mailText; using (var streamReader = new StreamReader(filePath + fileName)) { mailText = streamReader.ReadToEnd(); } mailText = parameters.Aggregate(mailText, (current, item) => current.Replace(item.Key, item.Value)); _mail.To.Add(recepientMails); _mail.Subject = subject; _mail.Body = mailText; _mail.IsBodyHtml = true; await _smtpClient.SendMailAsync(_mail); return true; } catch { return false; } }
static void Main() { Console.Write("Enter a number N (size of array): "); int n = int.Parse(Console.ReadLine()); int[] numbers = new int[n]; Console.WriteLine("\nEnter a {0} number(s) to array: ", n); for (int i = 0; i < numbers.Length; i++) { Console.Write(" {0}: ", i + 1); numbers[i] = int.Parse(Console.ReadLine()); } // Adds numbers to dictionary Dictionary<int, int> frequents = new Dictionary<int, int>(); for (int i = 0; i < numbers.Length; i++) { if (!frequents.ContainsKey(numbers[i])) frequents.Add(numbers[i], 1); else frequents[numbers[i]]++; } // Get the key of the highest value var max = frequents.Aggregate((l, r) => l.Value > r.Value ? l : r).Key; // Print all array elements Console.WriteLine("\nArray's elements: {0}", string.Join(" ", numbers)); // Print all keys (numbers) with the highest value Console.WriteLine("\nMost frequent numbers: "); foreach (KeyValuePair<int, int> item in frequents) if (item.Value == frequents[max]) Console.WriteLine("{0} -> {1} times", item.Key, frequents[item.Key]); Console.WriteLine(); }
public static string CarregarMensagemHtml(string templateEmail, Dictionary<string, string> parametros) { var streamReaderHtml = File.OpenText(templateEmail); var textoHtml = new StringBuilder(); try { string linha = streamReaderHtml.ReadLine(); while (linha != null) { textoHtml.Append(linha); linha = streamReaderHtml.ReadLine(); } textoHtml = parametros.Aggregate(textoHtml, (current, parametro) => current.Replace(parametro.Key, parametro.Value)); } finally { streamReaderHtml.Close(); } return textoHtml.ToString(); }
private string GetParametersString(Dictionary <string, string> parameters) { var result = parameters?.Aggregate("", (k, n) => { return($"{n.Key}={n.Value}&"); }); result = result.Remove(result.Length - 1, 1); return(result); }
private void Track(Dictionary<string, string> values) { var request = (HttpWebRequest)WebRequest.Create(endpoint); request.Method = "POST"; request.KeepAlive = false; var postDataString = values .Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key, HttpUtility.UrlEncode(next.Value))) .TrimEnd('&'); // set the Content-Length header to the correct value request.ContentLength = Encoding.UTF8.GetByteCount(postDataString); // write the request body to the request using (var writer = new StreamWriter(request.GetRequestStream())) { writer.Write(postDataString); } // Send the response to the server var webResponse = (HttpWebResponse)request.GetResponse(); if (webResponse.StatusCode != HttpStatusCode.OK) { throw new HttpException((int)webResponse.StatusCode, "Google Analytics tracking did not return OK 200"); } webResponse.Close(); }
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 override void GenerateScripts(AgentSettings settings) { Trace.Entering(); CalculateServiceName(settings, _svcNamePattern, _svcDisplayPattern); try { string svcShPath = Path.Combine(IOUtil.GetRootPath(), _svcShName); // TODO: encoding? // TODO: Loc strings formatted into MSG_xxx vars in shellscript string svcShContent = File.ReadAllText(Path.Combine(IOUtil.GetBinPath(), _shTemplate)); var tokensToReplace = new Dictionary<string, string> { { "{{SvcDescription}}", ServiceDisplayName }, { "{{SvcNameVar}}", ServiceName } }; svcShContent = tokensToReplace.Aggregate( svcShContent, (current, item) => current.Replace(item.Key, item.Value)); //TODO: encoding? File.WriteAllText(svcShPath, svcShContent); var unixUtil = HostContext.CreateService<IUnixUtil>(); unixUtil.ChmodAsync("755", svcShPath).GetAwaiter().GetResult(); } catch (Exception e) { Trace.Error(e); throw; } }
public string GenerateToken(string sessionId, Dictionary<string, object> options) { var appSettings = ConfigurationManager.AppSettings; options.Add("session_id", sessionId); options.Add("create_time", (int) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds); options.Add("nonce", RandomNumber(0, 999999)); if (!options.ContainsKey(TokenPropertyConstants.Role)) { options.Add(TokenPropertyConstants.Role, "publisher"); } // Convert expire time to Unix Timestamp if (options.ContainsKey(TokenPropertyConstants.ExpireTime)) { var origin = new DateTime(1970, 1, 1, 0, 0, 0); var expireTime = (DateTime) options[TokenPropertyConstants.ExpireTime]; var diff = expireTime - origin; options[TokenPropertyConstants.ExpireTime] = Math.Floor(diff.TotalSeconds); } string dataString = options.Aggregate(string.Empty, (current, pair) => current + (pair.Key + "=" + HttpUtility.UrlEncode((pair.Value == null) ? "" : pair.Value.ToString()) + "&")); dataString = dataString.TrimEnd('&'); string sig = SignString(dataString, appSettings["opentok_secret"].Trim()); string token = string.Format("{0}{1}", appSettings["opentok_token_sentinel"], EncodeTo64(string.Format("partner_id={0}&sdk_version={1}&sig={2}:{3}", appSettings["opentok_key"], appSettings["opentok_sdk_version"], sig, dataString))); return token; }
public static string FixTrx(XDocument doc) { var replaceList = new Dictionary<Guid, Guid>(); var storageReplace = new Dictionary<string, string>(); FixEndDateBeforeStartDate(doc); var trx = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + doc; var unitTests = doc.Descendants(XName.Get("TestRun", Ns)) .Descendants(XName.Get("TestDefinitions", Ns)) .Single() .Descendants(XName.Get("UnitTest", Ns)); foreach (var unitTest in unitTests) { //Storage attribute from VSTest.Console is fully qualified, i.e c:\foo\bar.dll, but tcm requires just bar.dll var testMethod = unitTest.Descendants(XName.Get("TestMethod", Ns)).Single(); var storage = unitTest.Attribute("storage").Value; if (!storageReplace.ContainsKey(storage)) storageReplace.Add(storage, Path.GetFileName(storage)); //VSTest.Console.exe generates random Guids for test Ids, we need to generate a guid based on the test name using the same // algorithm as MSTest var className = testMethod.Attribute("className"); var name = testMethod.Attribute("name"); var id = new Guid(unitTest.Attribute("id").Value); if (!replaceList.ContainsKey(id)) replaceList.Add(id, CalcProperGuid(className.Value + "." + name.Value)); } trx = replaceList.Aggregate(trx, (current, replacement) => current.Replace(replacement.Key.ToString(), replacement.Value.ToString())); trx = storageReplace.Aggregate(trx, (current, replacement) => current.Replace(replacement.Key.ToString(), replacement.Value.ToString())); return trx; }
/// <summary> /// Compiles a list of parameters into a working query-string. /// </summary> /// <param name="parameters">Parameters to compile.</param> /// <returns>Compilled query-string.</returns> public static string BuildQueryString(Dictionary <string, string> parameters) { return(parameters?.Aggregate( "", (current, parameter) => current + ("&" + parameter.Key + "=" + HttpUtility.UrlEncode(parameter.Value))) .Substring(1)); }
public static string LoadHTMLMensage(string templateEmail, Dictionary<string, string> parameters) { var streamReaderHtml = File.OpenText(templateEmail); var htmlText = new StringBuilder(); try { var line = streamReaderHtml.ReadLine(); while (line != null) { htmlText.Append(line); line = streamReaderHtml.ReadLine(); } htmlText = parameters.Aggregate(htmlText, (current, parameter) => current.Replace(parameter.Key, parameter.Value)); } finally { streamReaderHtml.Close(); } return htmlText.ToString(); }
private string Replace(Dictionary<string, string> tokens, string value) { string val = tokens.Aggregate(value, (current, token) => Regex.Replace(current, token.Key, match => token.Value)); if ( this.functionTokenizers != null ) { val = this.functionTokenizers.Aggregate(val, (current, tokenizer) => tokenizer.TokenizeContent(current)); } return val; }
// REVIEW: Is there a standard and safe query parser and joiner? static string QueryJoin(Dictionary<string, string> queryParts) { return String.Join( "&", queryParts.Aggregate( new List<string>(), (list, kvp) => { list.Add(kvp.Key + "=" + kvp.Value); return list; } ).ToArray()); }
public LyraUri(string method, Dictionary <string, string> args) : base($"lyra://localhost{method}?" + args?.Aggregate(new StringBuilder(), (sb, kvp) => sb.AppendFormat("{0}{1} = {2}", sb.Length > 0 ? "&&" : "", kvp.Key, kvp.Value), sb => sb.ToString())) { // todo }
protected override Uri GetServiceLoginUrl(Uri returnUrl) { var dict = new Dictionary<string, string>(); dict["client_id"] = this.appId; dict["redirect_uri"] = returnUrl.AbsoluteUri; dict["response_type"] = "code"; var url = dict.Aggregate(AuthorizationEndpoint, (current, param) => current.AddQueryParam(param.Key, param.Value)); return new Uri(url); }
public string Clean(string content) { var itemsToBeCleaned = new Dictionary<string,string> { {"\t", "\\t"}, {"\r", "\\r"}, {"\n", "\\n"}, {"\"", "\\\""}, }; return itemsToBeCleaned.Aggregate(content, (current, item) => current.Replace(item.Key, item.Value)); }
private static void Track(HitType type, string category, string action, string label, int? value = null) { if (string.IsNullOrEmpty(category)) throw new ArgumentNullException("category"); if (string.IsNullOrEmpty(action)) throw new ArgumentNullException("action"); var request = (HttpWebRequest)WebRequest.Create("http://www.google-analytics.com/collect"); request.Method = "POST"; request.KeepAlive = false; var postData = new Dictionary<string, string> { { "v", "1" }, { "tid", trackingId }, { "cid", "555" }, { "t", type.ToString() }, { "ec", category }, { "ea", action }, }; if (!string.IsNullOrEmpty(label)) { postData.Add("el", label); } if (value.HasValue) { postData.Add("ev", value.ToString()); } var postDataString = postData .Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key, HttpUtility.UrlEncode(next.Value))) .TrimEnd('&'); request.ContentLength = Encoding.UTF8.GetByteCount(postDataString); using (var writer = new StreamWriter(request.GetRequestStream())) { writer.Write(postDataString); } try { var webResponse = (HttpWebResponse)request.GetResponse(); if (webResponse.StatusCode != HttpStatusCode.OK) { throw new HttpException((int)webResponse.StatusCode, "Google Analytics tracking did not return OK 200"); } webResponse.Close(); } catch (Exception ex) { Console.Out.WriteLine(ex.Message); } }
static void Main(string[] args) { int[] arrayToCheck = { 4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3 }; Dictionary<int, int> occurences = new Dictionary<int, int>(); for (int i = 0; i < arrayToCheck.Length; i++) { if (occurences.ContainsKey(arrayToCheck[i])) { occurences[arrayToCheck[i]]++; } else { occurences.Add(arrayToCheck[i], 1); } } int maxKey = occurences.Aggregate((l, r) => l.Value > r.Value ? l : r).Key; int maxValue = occurences.Aggregate((l,r) => l.Value > r.Value ? l : r).Value; Console.WriteLine("Number with maximum occurences: {0} and number of occurences: {1}", maxKey, maxValue); }
public static bool EspeakTTS(Word w, string lang, bool _generate_wav) { string espeak_binary_location = PamyaSettings.Instance.GetSetting("espeakbin"); Dictionary<string, string> eo_string_replace_dict = new Dictionary<string, string>(); eo_string_replace_dict.Add("Ĝ", "Gx"); //FIXME eo_string_replace_dict.Add("ĝ", "gx"); eo_string_replace_dict.Add("Ĥ", "Hx"); eo_string_replace_dict.Add("ĥ", "hx"); eo_string_replace_dict.Add("Ĵ", "Jx"); eo_string_replace_dict.Add("ĵ", "jx"); eo_string_replace_dict.Add("Ŝ", "Sx"); eo_string_replace_dict.Add("ŝ", "sx"); eo_string_replace_dict.Add("Ĉ", "Cx"); eo_string_replace_dict.Add("ĉ", "cx"); eo_string_replace_dict.Add("Ŭ", "Ux"); eo_string_replace_dict.Add("ŭ", "ux"); eo_string_replace_dict.Add("-", "_"); eo_string_replace_dict.Add(" ", "_"); eo_string_replace_dict.Add("!", "_"); eo_string_replace_dict.Add(",", "_"); var text = eo_string_replace_dict.Aggregate(w.Target, (current, value) => current.Replace(value.Key, value.Value)); if (File.Exists(espeak_binary_location) && (! _generate_wav)) { //ugly stuff for now System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = espeak_binary_location; startInfo.Arguments = "-v " + lang + " \"" + text + "\""; process.StartInfo = startInfo; process.Start(); return true; } else if (File.Exists(espeak_binary_location) && _generate_wav) { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = espeak_binary_location; startInfo.Arguments = "-w " + text + ".wav " + "-v " + lang + " \"" + text + "\""; startInfo.WorkingDirectory = PamyaDeck.Instance.CurrentDeckFolder; process.StartInfo = startInfo; process.Start(); w.SoundFileLocation = text + ".wav "; return true; } else { return false; } }
public async Task TestPostRequestWithCustomeHeadersAndBody() { using (var server = new HttpHost(TestPort)) { const string path = "/test/path?query=value"; var headers = new Dictionary<string, string> { { "custom-header-1", "custom-value-1" }, { "content-custom", "content-value" } }; const string contentType = "suave/test"; const string content = "string content"; var responseContent = new byte[] { 1, 2, 3 }; await server.OpenAsync(async request => { Assert.Equal(path, request.RequestUri.PathAndQuery); Assert.Equal(HttpMethod.Post, request.Method); Assert.True(headers.All(pair => request.Headers.First(s => s.Key == pair.Key).Value.First() == pair.Value)); Assert.Equal(contentType, request.Content.Headers.ContentType.ToString()); Assert.Equal(content, await request.Content.ReadAsStringAsync()); var response = new HttpResponseMessage { StatusCode = HttpStatusCode.Accepted, Content = new ByteArrayContent(responseContent) }; response.Headers.Add("server-custom", "server-value"); return response; }); using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, LocalHost + path); headers.Aggregate(request.Headers, (a, b) => { a.Add(b.Key, b.Value); return a; }); request.Content = new StringContent(content); request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); var response = await client.SendAsync(request); Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); Assert.Equal(responseContent, await response.Content.ReadAsByteArrayAsync()); Assert.Equal("server-value", response.Headers.First(s => s.Key == "server-custom").Value.First()); } } }
public override int GetHashCode() { unchecked { var hashCode = (int)TwoGramCount; hashCode = (hashCode * 397) ^ (int)N1PlusStarww; hashCode = (hashCode * 397) ^ NwwStarCount.GetHashCode(); hashCode = ThreeGramCounts?.Aggregate(hashCode, (current, threeGram) => (int)((((current * 397) ^ threeGram.Key) * 397) ^ threeGram.Value)) ?? hashCode; hashCode = MostLikelies?.Aggregate(hashCode, (current, count) => (current * 397) ^ count) ?? hashCode; return(hashCode); } }
protected VkWebCommand GetVkXmlCommand(string methodName, Dictionary<string, object> parameters, bool includeToken) { if (includeToken) { parameters.Add("access_token", AccessToken); } var uri = String.Format("https://api.vk.com/method/{0}.xml?app=1", methodName); uri = parameters.Aggregate(uri, (current, pair) => current + String.Format("&{0}={1}", pair.Key, pair.Value)); Logger.DebugFormat("XML Command: '{0}'", uri); return new VkWebCommand(methodName, uri); }
protected override string CreateClassWithOverridingParams(string className, string baseClassName, IEnumerable<string> nsImports, Dictionary<string, string> overidenParams) { return CreateCsharpConfigClassCode( overidenParams.Aggregate("", (acc, p) => acc + GetPublicOverrideStringPropertySnippet(p.Key, p.Value)) , className, baseClassName, false, nsImports ); }
static void Main(string[] args) { int numberOfrows= int.Parse(Console.ReadLine()); List<Employee> employeesList= new List<Employee>(); for (int i = 0; i < numberOfrows; i++) { string[] input = Console.ReadLine().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); var emp = new Employee(input[0], decimal.Parse(input[1]), input[2], input[3]); if (input.Length > 4) { if (input.Length > 5) { emp.mail = input[4]; emp.age = int.Parse(input[5]); } else { if (input[4].Contains("@")) { emp.mail = input[4]; } else { emp.age = int.Parse(input[4]); } } } employeesList.Add(emp); } Dictionary<string, decimal> result=new Dictionary<string, decimal>(); for (int i = 0; i < employeesList.Count; i++) { if (result.ContainsKey(employeesList[i].department)) { result[employeesList[i].department] += employeesList[i].salary; result[employeesList[i].department] /= 2.0m; } else { result.Add(employeesList[i].department, employeesList[i].salary); } } var max = result.Aggregate((l, r) => l.Value > r.Value ? l : r).Key; Console.WriteLine($"Highest Average Salary: {max}"); foreach (var r in employeesList.Where(x=>x.department.Equals(max)).OrderByDescending(x=>x.salary)) { Console.WriteLine("{0} {1:F2} {2} {3}",r.name,r.salary, r.mail, r.age); } }
public Builder EnterDiv(string id = null, string htmlClass = null, Dictionary<string, object> attributes = null) { var tag = "<div"; if (id != null) tag += String.Format(" id=\"{0}\"", id); if (htmlClass != null) tag += String.Format(" class=\"{0}\"", htmlClass); if (attributes != null) tag = attributes.Aggregate(tag, (current, attribute) => current + String.Format(" {0}=\"{1}\"", attribute.Key, attribute.Value)); tag += ">"; Html += tag; return this; }
public string LoadTemplate(string templateName, Dictionary<string, string> replacements = null) { var projectTemplateStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(GetType(), templateName); Debug.Assert(projectTemplateStream != null); string fileContent = new StreamReader(projectTemplateStream).ReadToEnd(); if (replacements != null) { fileContent = replacements.Aggregate(fileContent, (current, replacement) => current.Replace("{" + replacement.Key + "}", replacement.Value)); } return fileContent; }
public void MakeReplacements(Dictionary<string, string> replacements) { if(replacements == null) { return; } var stream = File.OpenText(WorkingDirectory + _testName + "\\script.txt" ); var script = stream.ReadToEnd(); stream.Close(); script = replacements.Aggregate(script, (current, replacement) => current.Replace("<!--" + replacement.Key + "-->", replacement.Value)); script = script.Replace("<!--SERVER-->", _server); File.WriteAllText(WorkingDirectory + _testName + "\\script.txt", script); }
public override int GetHashCode() { unchecked { var comparer = new KeyValuePairIntTwoStringInfoComparer(); var hashCode = (int)OneGramCount; hashCode = (hashCode * 397) ^ (int)N1PlusStarwStar; hashCode = (hashCode * 397) ^ (int)N1PlusStarw; hashCode = (hashCode * 397) ^ NwStarCount.GetHashCode(); hashCode = MostLikelies?.Aggregate(hashCode, (current, count) => (current * 397) ^ count) ?? hashCode; hashCode = TwoGrams?.Aggregate(hashCode, (current, twoGram) => (current * 397) ^ comparer.GetHashCode(twoGram)) ?? hashCode; return(hashCode); } }
public IReadOnlyDictionary<Vertex, Location> Plan([NotNull] Graph graph) { // create initial random locations for each vertex var currentLocations = CreateRandomLocations(graph); // loop until the number of iterations exceeds the hard limit const double terminationThreshold = TerminationThreshold * TerminationThreshold; for (var i = 0; i < MaximumIterations; ++i) { // the total displacement, used as a stop condition var totalDisplacement = 0.0D; // prepare the new positions var newLocations = new Dictionary<Vertex, Location>(currentLocations); // iterate over all vertices ... foreach (var vertex in graph.Vertices) { // obtain the vertex location var locationOf = currentLocations[vertex]; // and process against all other vertices var netForce = Vector.Zero; netForce += CalculateTotalRepulsion(graph, vertex, locationOf, currentLocations); netForce += CalculateTotalAttraction(graph, vertex, locationOf, currentLocations); // TODO: make use of force symmetry along edges here // finally, update the vertex' position locationOf += netForce; newLocations[vertex] = locationOf; // update the total displacement totalDisplacement += netForce.SquaredNorm(); } // calculate the center var center = newLocations.Aggregate(Vector.Zero, (vector, location) => vector + (Vector)location.Value) * (1D / currentLocations.Count); // adjust each node to prevent creep foreach (var location in newLocations) { currentLocations[location.Key] = location.Value - center; } // early exit if nodes don't move much anymore if (totalDisplacement < terminationThreshold) break; } return currentLocations; }
private async Task <T> Get <T>(string action, Dictionary <string, string> args) { var url = $"{action}/?" + args?.Aggregate(new StringBuilder(), (sb, kvp) => sb.AppendFormat("{0}{1}={2}", sb.Length > 0 ? "&" : "", kvp.Key, kvp.Value), sb => sb.ToString()); HttpResponseMessage response = await _client.GetAsync(url); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync <T>(); return(result); } else { throw new Exception("Web Api Failed."); } }
static async Task setPEVersionInfoAndIcon(string exePath, IPackage package, string iconPath = null) { var realExePath = Path.GetFullPath(exePath); var company = String.Join(",", package.Authors); var verStrings = new Dictionary <string, string>() { { "CompanyName", company }, { "LegalCopyright", package.Copyright ?? "Copyright © " + DateTime.Now.Year.ToString() + " " + company }, { "FileDescription", package.Summary ?? package.Description ?? "Installer for " + package.Id }, { "ProductName", package.Description ?? package.Summary ?? package.Id }, }; var args = verStrings.Aggregate(new StringBuilder("\"" + realExePath + "\""), (acc, x) => { acc.AppendFormat(" --set-version-string \"{0}\" \"{1}\"", x.Key, x.Value); return(acc); }); args.AppendFormat(" --set-file-version {0} --set-product-version {0}", package.Version.ToString()); if (iconPath != null) { args.AppendFormat(" --set-icon \"{0}\"", Path.GetFullPath(iconPath)); } // Try to find rcedit.exe string exe = findExecutable("rcedit.exe"); var processResult = await Utility.InvokeProcessAsync(exe, args.ToString(), CancellationToken.None); if (processResult.Item1 != 0) { var msg = String.Format( "Failed to modify resources, command invoked was: '{0} {1}'\n\nOutput was:\n{2}", exe, args, processResult.Item2); throw new Exception(msg); } else { Console.WriteLine(processResult.Item2); } }
public void GenerateScripts(AgentSettings settings) { Trace.Entering(); string serviceName; string serviceDisplayName; CalculateServiceName(settings, _svcNamePattern, _svcDisplayPattern, out serviceName, out serviceDisplayName); try { string svcShPath = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), _svcShName); // TODO: encoding? // TODO: Loc strings formatted into MSG_xxx vars in shellscript string svcShContent = File.ReadAllText(Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), _shTemplate)); var tokensToReplace = new Dictionary <string, string> { { "{{SvcDescription}}", serviceDisplayName }, { "{{SvcNameVar}}", serviceName } }; svcShContent = tokensToReplace.Aggregate( svcShContent, (current, item) => current.Replace(item.Key, item.Value)); //TODO: encoding? File.WriteAllText(svcShPath, svcShContent); var unixUtil = HostContext.CreateService <IUnixUtil>(); unixUtil.ChmodAsync("755", svcShPath).GetAwaiter().GetResult(); } catch (Exception e) { Trace.Error(e); throw; } }
private static void Track(Dictionary <string, string> values) { var request = (HttpWebRequest)WebRequest.Create(endpoint); request.Method = "POST"; request.KeepAlive = false; var postDataString = values .Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key, HttpUtility.UrlEncode(next.Value))) .TrimEnd('&'); // set the Content-Length header to the correct value request.ContentLength = Encoding.UTF8.GetByteCount(postDataString); // write the request body to the request using (var writer = new StreamWriter(request.GetRequestStream())) { writer.Write(postDataString); } try { // Send the response to the server var webResponse = (HttpWebResponse)request.GetResponse(); if (webResponse.StatusCode != HttpStatusCode.OK) { throw new HttpException((int)webResponse.StatusCode, "Google Analytics tracking did not return OK 200"); } webResponse.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } }
public void SwapItemsInSlots(GameObject slotOne, GameObject slotTwo, Item itemInSlotOne, Item itemInSlotTwo) { if (itemInSlotOne.stackable) { slotToStackableNameMap[slotTwo] = itemInSlotOne.ItemName; if (itemInSlotOne.stackable != itemInSlotTwo.stackable) { slotToStackableNameMap.Remove(slotOne); } } else { slotToNonStackableUuidMap[slotTwo] = itemInSlotOne.Uuid; if (itemInSlotOne.stackable != itemInSlotTwo.stackable) { slotToNonStackableUuidMap.Remove(slotOne); } } if (itemInSlotTwo.stackable) { slotToStackableNameMap[slotOne] = itemInSlotTwo.ItemName; if (itemInSlotOne.stackable != itemInSlotTwo.stackable) { slotToStackableNameMap.Remove(slotTwo); } } else { slotToNonStackableUuidMap[slotOne] = itemInSlotTwo.Uuid; if (itemInSlotOne.stackable != itemInSlotTwo.stackable) { slotToNonStackableUuidMap.Remove(slotTwo); } } Debug.Log("Stackables: " + slotToStackableNameMap.Aggregate("", (agg, x) => agg + x.Key.GetComponent <Slot>().id + ": " + x.Value + ", ")); Debug.Log("Nontackables: " + slotToNonStackableUuidMap.Aggregate("", (agg, x) => agg + x.Key.GetComponent <Slot>().id + ": " + InventoryController.instance.UUIDToName(x.Value) + ", ")); }
public static async Task Init(ComboBox comboBox = null) { Dictionary <string[], long> serversPings = new Dictionary <string[], long>(); foreach (Server server in serverList) { try { Ping p = new Ping(); PingReply replyEur = p.Send(server.host, 2000); serversPings[new string[] { server.name, server.host, server.pattern }] = replyEur.RoundtripTime; Logger.Log($"[Servers] Ping to {server.host}: {replyEur.RoundtripTime} ms", true); } catch (Exception e) { Logger.Log($"[Servers] Failed to ping {server.host}: {e.Message}", true); serversPings[new string[] { server.name, server.host, server.pattern }] = 10000; } } var closest = serversPings.Aggregate((l, r) => l.Value < r.Value ? l : r); Logger.Log($"[Servers] Closest Server: {closest.Key[0]} ({closest.Value} ms)", true); closestServer = new Server { name = closest.Key[0], host = closest.Key[1], pattern = closest.Key[2] }; if (comboBox != null) { for (int i = 0; i < comboBox.Items.Count; i++) { if (comboBox.Items[i].ToString() == closestServer.name) { comboBox.SelectedIndex = i; } } } }
static long CommonFactorCountSolve() { // find the common factors between the numbers 1 to 20 var factorCounts = Sequences.LongRange(1, 20).Select(n => Sequences.GetPrimeFactors(n).GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count())); // collect the maximum factor counts for each of the numbers; // for instance, 16 is 2^4, so the 2 factors of 20 (2*2*5) // are not necessary as they are already accounted for var maxCount = new Dictionary <long, int>(); foreach (var factor in factorCounts.SelectMany(factorCount => factorCount)) { maxCount[factor.Key] = maxCount.ContainsKey(factor.Key) ? Math.Max(maxCount[factor.Key], factor.Value) : factor.Value; } // compute the smallest number that is divisible by all numbers from 1 to 20, // ie, the number with the minimum number of factors shared by those numbers return(maxCount.Aggregate <KeyValuePair <long, int>, long>( 1, (current, factor) => current * (long)Math.Pow(factor.Key, factor.Value) )); }
new public void select_comm_method() { //creating a dictionary to link strings to corresponding SNR value Dictionary <string, float> types = new Dictionary <string, float>() { { "IR", SNR_IR }, { "RF", SNR_RF }, }; //gives max the string thats linked to the highest SNR value var max = types.Aggregate((l, r) => l.Value > r.Value ? l : r).Key; if (max == "IR") { IR = true; RF = false; } else { RF = true; IR = false; } Console.WriteLine("Quadcopter IRRF is now using {0} communication", max); //Console.WriteLine("IR:{0} RF:{1}",IR,RF); }
public async Task <string> GetCountryWithTheMostUniqueHolidays(int year) { var countryGlobalHolidaysCountDict = new Dictionary <string, int>(); foreach (var countryCode in Constants.CountryCodes) { var holidaysResult = await _holidaysService.GetHolidays(countryCode, year); if (holidaysResult.IsSuccess) { var globalHolidaysCount = holidaysResult.Value.Count(holidayInfo => holidayInfo.Global); countryGlobalHolidaysCountDict[countryCode] = globalHolidaysCount; } else { throw new ApplicationException($"Unable to get holidays for {countryCode}"); } } //I've assumed that country with the smallest number of global holidays will be the country with the most unique holidays var monthIndex = countryGlobalHolidaysCountDict.Aggregate((l, r) => l.Value > r.Value ? r : l).Key; return(monthIndex); }
static void Main(string[] args) { var arraySize = int.Parse(Console.ReadLine()); var list = new List <int>(); for (int i = 0; i < arraySize; i++) { list.Add(int.Parse(Console.ReadLine())); } var distinctArray = list.Distinct(); var dictionary = new Dictionary <int, int>(); foreach (var distinctNumber in distinctArray) { dictionary.Add(distinctNumber, list.Count(x => x == distinctNumber)); } var max = dictionary.Aggregate((l, r) => l.Value > r.Value ? l : r).Key; Console.WriteLine("{0} ({1} times)", max, dictionary[max]); }
/// <summary> /// Send an HTTP POST request /// </summary> /// <param name="url">base url</param> /// <param name="data">data to send in request</param> /// <param name="headers">HTTP Request headers</param> /// <param name="parameters">Url parameters to encode</param> /// <returns></returns> public static Task <HttpResponseMessage> Post(string url, string data = "", Dictionary <string, string> headers = null, Dictionary <string, string> parameters = null) { if (parameters != null) { url += parameters.Aggregate( new StringBuilder(), (sb, pair) => sb.AppendFormat("{0}={1}&", pair.Key, pair.Value), (sb) => sb.ToString()); } HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url); if (data != String.Empty) { request.Content = new StringContent(data, Encoding.UTF8); } foreach (KeyValuePair <string, string> p in headers) { request.Headers.Add(p.Key, p.Value); } request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/plain")); return(client.SendAsync(request)); }
/// <summary> /// transform a dictionary into the query string that is translated in byte array then /// </summary> /// <param name="items"></param> /// <returns></returns> public static byte[] PostBytes(Dictionary <string, string> items) { if (items == null || !items.Any()) { return(null); } var resultStringSeed = String.Empty; var queryString = items.Aggregate(resultStringSeed, (resultString, item) => String.Format("{0}&{1}={2}", resultString, Uri.EscapeDataString(item.Key), Uri.EscapeDataString(item.Value)) ) .Trim(new[] { '&' }); var bytes = Encoding.UTF8.GetBytes(queryString); return(bytes.Any() ? bytes : null); }
public bool Update(String tableName, Dictionary <String, String> data, String where) { var vals = ""; var returnCode = true; if (data.Count >= 1) { vals = data.Aggregate(vals, (current, val) => current + String.Format(" {0} = '{1}',", val.Key.ToString(), val.Value.ToString())); vals = vals.Substring(0, vals.Length - 1); } try { ExecuteNonQuery(String.Format("update {0} set {1} where {2};", tableName, vals, where)); } catch (Exception) { returnCode = false; } return(returnCode); }
public string SubstitutePlaceholders(string fileNameWithPath, DateTime dateTime, bool incrementIfExists = true, int numberSkip = 0, int autoNumberDigits = 0) { if (fileNameWithPath == null) { return(null); } // Most placeholders don't need a special case string result = Placeholders.Aggregate(fileNameWithPath, (current, ph) => current.Replace(ph.Key, ph.Value(dateTime))); // One does, however var match = NumberPlaceholderPattern.Match(result); if (match.Success) { result = NumberPlaceholderPattern.Replace(result, ""); result = SubstituteNumber(result, match.Index, match.Length - 3, numberSkip, true); } else if (autoNumberDigits > 0) { result = result.Insert(result.Length - Path.GetExtension(result).Length, "."); result = SubstituteNumber(result, result.Length - Path.GetExtension(result).Length, autoNumberDigits, numberSkip, incrementIfExists); } return(result); }
public static void Main() { var repetitions = new Dictionary <int, int>(); var numbers = File.ReadAllText("input.txt") .Split() .Select(int.Parse) .ToArray(); foreach (var number in numbers) { if (repetitions.ContainsKey(number)) { repetitions[number]++; } else { repetitions[number] = 1; } } File.WriteAllText("output.txt", repetitions .Aggregate((a, b) => a.Value >= b.Value ? a : b) .Key.ToString()); }
/// <summary>Allows the programmer to easily update rows in the DB.</summary> /// <param name="tableName">The table to update.</param> /// <param name="data">A dictionary containing Column names and their new values.</param> /// <param name="where">The where clause for the update statement.</param> /// <returns>An integer that represents the amount of rows updated, or -1 if the query failed.</returns> public int Update(String tableName, Dictionary <String, String> data, String where) { var sql = ""; var vals = ""; int returnCode; if (data.Count >= 1) { vals = data.Aggregate(vals, (current, val) => current + String.Format(" {0} = \"{1}\",", val.Key, val.Value)); vals = vals.Substring(0, vals.Length - 1); } try { sql = String.Format("update {0} set {1} where {2};", tableName, vals, where); returnCode = ExecuteNonQuery(sql); } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\nQuery: " + sql); returnCode = -1; } return(returnCode); }
public async Task <string> Add(Register user) { string retValue = string.Empty; try { if (string.IsNullOrEmpty(user.Id) && !string.IsNullOrEmpty(user.Email) && !string.IsNullOrEmpty(user.Password) && !string.IsNullOrEmpty(user.Username)) { var maxValue = _context.Aggregate((x, y) => int.Parse(x.Value.Id) > int.Parse(y.Value.Id) ? x : y).Value.Id; user.Id = (int.Parse(maxValue) + 1).ToString(); user.Active = true; if (_context.TryAdd(user.Username, user)) { retValue = user.Username; } } } catch (Exception e) { // log exception } return(retValue); }
protected override void Execute(CodeActivityContext executionContext) { var error = false; var errorMessage = String.Empty; var formula = Formula.Get <string>(executionContext); try { var parameters = new Dictionary <string, string>(); AddParameters(executionContext, parameters); var equation = parameters.Aggregate(formula, (c, p) => c.Replace(p.Key, String.Format(" {0} ", p.Value))); SetOutputValues(executionContext, Equation.Solve(equation)); } catch (Exception ex) { errorMessage = ex.Message; error = true; } Error.Set(executionContext, error); ErrorMessage.Set(executionContext, errorMessage); }
private string GetMostCommonClass(int[] rows) { Dictionary <string, int> dict = new Dictionary <string, int>(); foreach (string cls in classes) { dict.Add(cls, 0); } foreach (int row in rows) { foreach (string cls in classes) { if (dt.Rows[row][classColumn].ToString() == cls) { dict[cls]++; break; } } } return(dict.Aggregate((x, y) => x.Value > y.Value ? x : y).Key); }
private static IEnumerable <string> ReplacePlaceholders(IEnumerable <string> commands, Dictionary <string, string> placeholders) { Console.WriteLine("\t\tPlaceholders"); var output = commands; // Perform 10 iterations var iteration = 0; bool repeatLoop; do { iteration++; output = output.Select( expression => placeholders.Aggregate( expression, (result, s) => result.Replace(s.Key, s.Value) )); repeatLoop = output.Any(line => line.Contains("PLH")); }while (repeatLoop && iteration < 10); return(output); }
private static void HandleWeightedDiscounting(List <string> eligibleLineItemIDs, Dictionary <string, decimal> weightedLineItemDiscountsByPromoCode, OrderWorksheet order, decimal eligibleLineItemSubtotal, decimal totalDiscountedByOrderCloud) { foreach (string lineItemID in eligibleLineItemIDs) { weightedLineItemDiscountsByPromoCode.Add(lineItemID, 0M); // Initialize discount for this promo code at 0.00 LineItem lineItem = order.LineItems.FirstOrDefault(lineItem => lineItem.ID == lineItemID); // Determine amount of promo code discount to apply to this line item and round decimal lineItemRateOfSubtotal = lineItem.LineSubtotal / eligibleLineItemSubtotal; decimal weightedDiscount = Math.Round(lineItemRateOfSubtotal * totalDiscountedByOrderCloud, 2); weightedLineItemDiscountsByPromoCode[lineItemID] += weightedDiscount; } decimal totalWeightedDiscountApplied = weightedLineItemDiscountsByPromoCode.Sum(discount => discount.Value); if (totalDiscountedByOrderCloud != totalWeightedDiscountApplied) { // If a small discrepancy occurs due to rounding, resolve it by adding/subtracting the difference to the item that was discounted the most decimal difference = totalDiscountedByOrderCloud - totalWeightedDiscountApplied; string lineItemIDToApplyDiscountDifference = weightedLineItemDiscountsByPromoCode.Aggregate((x, y) => x.Value > y.Value ? x : y).Key; weightedLineItemDiscountsByPromoCode[lineItemIDToApplyDiscountDifference] += difference; } }
public void Should_add_cookies_to_the_request() { // Given var context = new BrowserContext(); var cookies = new Dictionary <string, string> { { "CookieName", "CookieValue" }, { "SomeCookieName", "SomeCookieValue" } }; // When context.Cookie(cookies); // Then IBrowserContextValues values = context; var cookieString = cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format("{0}={1};", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value))); Assert.Equal(1, values.Headers["Cookie"].Count()); Assert.Equal(cookieString, values.Headers["Cookie"].First()); }
protected async Task <T> GetAsync <T>(string action, Dictionary <string, string>?args = null) { var url = $"{action}/?" + args?.Aggregate(new StringBuilder(), (sb, kvp) => sb.AppendFormat("{0}{1}={2}", sb.Length > 0 ? "&" : "", kvp.Key, kvp.Value), sb => sb.ToString()); using var client = CreateClient(); HttpResponseMessage response = await client.GetAsync(url, _cancel.Token); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsAsync <T>(); return(result); } else { var resp = await response.Content.ReadAsStringAsync(); throw new Exception($"Web Api Failed for {url}, {resp}"); } }
public string AddRow(Row row, List <Col> cols) { _totalRows++; string result = null; if (_totalRows >= BootstrapMin) { result = _classCounts.Aggregate((l, r) => l.Value > r.Value ? l : r).Key; } var goalClass = row.GetGoals().First().RawValue; if (!_classCounts.ContainsKey(goalClass)) { _classCounts[goalClass] = 1; } else { _classCounts[goalClass] += 1; } return(result); }
/// <summary> /// Updates specific rows in the database. /// </summary> /// <param name="tableName">The table to update.</param> /// <param name="data">A dictionary containing Column names and their new values.</param> /// <param name="where">The where clause for the update statement.</param> /// <returns>A boolean true or false to signify success or failure.</returns> public bool Update(String tableName, Dictionary <String, String> data, String where) { string vals = ""; if (data.Count >= 1) { vals = data.Aggregate(vals, (current, val) => current + String.Format(" {0} = '{1}',", val.Key.ToString(CultureInfo.InvariantCulture), val.Value?.ToString(CultureInfo.InvariantCulture))); vals = vals.Substring(0, vals.Length - 1); } try { ExecuteNonQuery(String.Format("update {0} set {1} where {2};", tableName, vals, where)); return(true); } catch (Exception e) { throw new Exception($"SQLite Exception : {e.Message}"); } }