static void Main(string[] args) { var lectures = new Dictionary<string, Tuple<int, int>>(); int count = int.Parse(Console.ReadLine().Split(' ')[1]); for (int i = 0; i < count; i++) { var tokens = Console.ReadLine().Split(new[] { ' ', '-', ':' }, StringSplitOptions.RemoveEmptyEntries); lectures.Add(tokens[0], new Tuple<int, int>(int.Parse(tokens[1]), int.Parse(tokens[2]))); } int resCount = 0; int earliestFinish = 0; var sortedLectures = lectures.OrderBy(l => l.Value.Item2); foreach (var lecture in sortedLectures) { if (lecture.Value.Item1 >= earliestFinish) { earliestFinish = lecture.Value.Item2; resCount++; continue; } lectures.Remove(lecture.Key); } Console.WriteLine($"Lectures ({resCount}):"); foreach (var lecture in lectures.OrderBy(l => l.Value.Item2)) { Console.WriteLine($"{lecture.Value.Item1}-{lecture.Value.Item2} -> {lecture.Key}"); } }
public string Encode() { var values = new Dictionary<string, string>(); values.Add("bank_type", "WX"); values.Add("body", Body); if (!string.IsNullOrEmpty(Attach)) values.Add("attach", Attach); values.Add("partner", WxPayConfig.PARTER_ID); values.Add("out_trade_no", OutTradeNo); values.Add("total_fee", TotalFee.ToString()); values.Add("fee_type", FeeType.ToString()); values.Add("notify_url", string.IsNullOrEmpty(NotifyUrl)?WxPayConfig.NOTIFY_URL:NotifyUrl); values.Add("spbill_create_ip", SPBill_Create_IP); if (!string.IsNullOrEmpty(Time_Start)) values.Add("time_start", Time_Start); if (!string.IsNullOrEmpty(Time_End)) values.Add("time_expire", Time_End); values.Add("transport_fee", TransportFee.ToString()); values.Add("product_fee", ProductFee.ToString()); if (!string.IsNullOrEmpty(GoodsTag)) values.Add("goods_tag", GoodsTag); values.Add("input_charset", InputCharset); var signingStr = values.OrderBy(b => b.Key).Aggregate(new StringBuilder(), (s, b) => s.AppendFormat("{0}={1}&", b.Key, b.Value), s => s.ToString()).TrimEnd('&'); signingStr = string.Format("{0}&key={1}", signingStr, WxPayConfig.PARTER_KEY); var signedStr = Util.MD5_Encode(signingStr).ToUpper(); var resultStr = values.OrderBy(b => b.Key).Aggregate(new StringBuilder(), (s, b) => s.AppendFormat("{0}={1}&", b.Key,Util.UrlEncode(b.Value)), s => s.ToString()).TrimEnd('&'); return string.Format("{0}&sign={1}", resultStr, signedStr); }
public static string Distance() { Dictionary<string, double> distance; distance = new Dictionary<string,double>(); distance.Add("normal", CalculateDistance(0, 0)); distance.Add("up", CalculateDistance(0, -1)); distance.Add("down", CalculateDistance(0, 1)); distance.Add("left", CalculateDistance(-1, 0)); distance.Add("right", CalculateDistance(1, 0)); Console.WriteLine(distance.OrderBy(kvp => kvp.Value).First().Key); return distance.OrderBy(kvp => kvp.Value).First().Key; }
public static int[] GetRanked(int[] A, int ABegin, int ALength) { Dictionary<int, int> Dict = new Dictionary<int, int>(); for (int i = 0; i < ALength; i++) Dict.Add(i, A[i + ABegin]); Dictionary<int, int> Dict2 = new Dictionary<int, int>(); int index = 0; foreach (var item in Dict.OrderBy(pair => pair.Value)) Dict[item.Key] = index++; int[] ret = new int[ALength]; foreach (var item in Dict.OrderBy(pair => pair.Key)) { ret[item.Key] = item.Value; } return ret; }
public Dictionary<DateTime, decimal> Calculate() { var returnDictionary = new Dictionary<DateTime, decimal>(); if (this.signals.Any()) { returnDictionary.Add(this.signals.ElementAt(0).Date, this.startingEquity); var count = this.signals.Count(); for (var i = 0; i <= count - 2; i++) { var originalSignal = this.signals.ElementAt(i).SignalType; if (originalSignal == SignalType.TakeProfits) { returnDictionary.Add(this.signals.ElementAt(i + 1).Date, returnDictionary.OrderBy(d => d.Key).Last().Value); continue; } var startTradePrice = this.signals.ElementAt(i).Price; var finalTradePrice = this.signals.ElementAt(i + 1).Price; var percentageDifference = (finalTradePrice - startTradePrice)/startTradePrice; var percentageDifferenceToEquity = originalSignal == SignalType.Buy && percentageDifference > 0 || originalSignal == SignalType.Sell && percentageDifference < 0 ? Math.Abs(percentageDifference) : -Math.Abs(percentageDifference); var newEquityValue = returnDictionary.Last().Value + (returnDictionary.Last().Value*percentageDifferenceToEquity); returnDictionary.Add(this.signals.ElementAt(i + 1).Date, newEquityValue); } } return returnDictionary; }
internal static string GetOAuthHeader(Dictionary<string, string> parameters, string url, string comsumeSercret, string tokenSecret) { parameters = parameters.OrderBy(x => x.Key).ToDictionary(v => v.Key, v => v.Value); string concat = string.Empty; string OAuthHeader = "OAuth "; foreach (var key in parameters.Keys) { concat += key + "=" + parameters[key] + "&"; OAuthHeader += key + "=" + "\"" + parameters[key] + "\","; } concat = concat.Remove(concat.Length - 1, 1); concat = EncodeToUpper(concat); concat = "POST&" + EncodeToUpper(url) + "&" + concat; byte[] content = Encoding.UTF8.GetBytes(concat); HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(comsumeSercret + "&" + tokenSecret)); hmac.ComputeHash(content); string hash = Convert.ToBase64String(hmac.Hash); hash = hash.Replace("-", ""); OAuthHeader += "oauth_signature=\"" + EncodeToUpper(hash) + "\""; return OAuthHeader; }
static void Main() { string source = Console.ReadLine(); Dictionary<char, int> chars = new Dictionary<char, int>(); for (char i = 'a'; i <= 'z'; i++) { chars.Add(i, 0); } for (char i = 'A'; i <= 'Z'; i++) { chars.Add(i, 0); } foreach (char curr in source) { if (chars.ContainsKey(curr)) { chars[curr]++; } } var ordered = chars.OrderBy(x => x.Key); //to sort by the letter foreach (var item in ordered) { if (item.Value != 0) { Console.WriteLine("{0} -> {1} ", item.Key, item.Value); } } }
public string PrcessCoursesOutput(Dictionary<string, decimal> coursesCatalog) { var result = ""; var lastItemType = "none"; foreach(var resultPointer in coursesCatalog.OrderBy(p => p.Value)) { if (resultPointer.Value % 1 == 0) { if (lastItemType == "loop") { result = result.Substring(0, result.Length - 2); result += ", "; } result += resultPointer.Key + ", "; } else { result += resultPointer.Key + "- "; lastItemType = "loop"; } } result = result.Substring(0, result.Length - 2); if (result.Contains("-")) result = "Notice: A cricular reference was detected in the courses entered. " + result; return result; }
static void Main() { string input = "prela baba tri 4%^&!nedeli, ta izprela tri kadeli!"; string[] words = Regex.Split(input, @"[\W+0-9_~!@#$%^&*()_+,=-`/?.,<>\|'"";:]"); Dictionary<char, int> countchars = new Dictionary<char, int>(); for (int i = 0; i < words.Length; i++) { foreach (var character in words[i]) { if (countchars.ContainsKey(character)) { countchars[character]++; } else { countchars.Add(character, 1); } } } var sortedLetters = countchars.OrderBy(x => x.Key); foreach (var letter in sortedLetters) { Console.WriteLine("Letter --> {0} - Number --> {1}", letter.Key, letter.Value); } }
static void Main() { StreamReader reader = new StreamReader("someText.txt", Encoding.GetEncoding("UTF-8")); using (reader) { string text = reader.ReadToEnd(); char[] separateBy = { ' ', '.', ',', '!', '?' }; string[] values = text.ToLower().Split(separateBy, StringSplitOptions.RemoveEmptyEntries); Dictionary<string, int> dictionary = new Dictionary<string, int>(); foreach (var value in values) { int count = 0; if (dictionary.ContainsKey(value)) { count = dictionary[value]; } dictionary[value] = count + 1; } foreach (KeyValuePair<string, int> item in dictionary.OrderBy(key => key.Value)) { Console.WriteLine("{0} -> {1} times", item.Key, item.Value); } } }
public void LoadMatches(Dictionary<GameStats, List<GameStats>> games) { try { AllWrappers.Clear(); foreach(var set in games.OrderBy(x => x.Value.Count)) { var deck = DeckList.Instance.Decks.FirstOrDefault(d => d.DeckId == set.Key.DeckId); var tvi = new TreeViewItem { ItemTemplate = (DataTemplate)FindResource("DataTemplateCheckBox"), Header = $"[Original - Deck: {(deck != null ? deck.Name : "")}] : {GetMatchInfo(set.Key)} ({set.Value.Count} duplicate(s))", IsExpanded = true }; foreach(var game in set.Value) { try { var wrapper = new GameStatsWrapper(game); tvi.Items.Add(wrapper); AllWrappers.Add(wrapper); } catch(Exception e) { Log.Error(e); } } TreeViewGames.Items.Add(tvi); } } catch(Exception ex) { Log.Error(ex); } }
/// <summary>释放模版文件</summary> public static Dictionary<String, String> GetTemplates() { var ss = Assembly.GetExecutingAssembly().GetManifestResourceNames(); if (ss == null || ss.Length <= 0) return null; var dic = new Dictionary<String, String>(); //找到资源名 foreach (var item in ss) { if (item.StartsWith("XCoder.App.")) { ReleaseFile(item, "XCoder.exe.config"); } else if (item.StartsWith("XCoder.Template.")) { var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(item); var tempName = item.Substring("XCoder.Template.".Length); var buffer = new Byte[stream.Length]; var count = stream.Read(buffer, 0, buffer.Length); var content = Encoding.UTF8.GetString(buffer, 0, count); dic.Add(tempName, content); } } return dic.OrderBy(e => e.Key).ToDictionary(e => e.Key, e => e.Value); }
public static IEnumerable<KeyValuePair<string, string>> GetSpecialistList(AdGroup grp) { var list = new Dictionary<string, string>(); using (WindowsImpersonationContextFacade impersonationContext = new WindowsImpersonationContextFacade( nc)) { var domain = new PrincipalContext(ContextType.Domain); var group = GroupPrincipal.FindByIdentity(domain, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(grp)); if (group != null) { var members = group.GetMembers(true); foreach (var principal in members) { var userPrincipal = UserPrincipal.FindByIdentity(domain, principal.SamAccountName); if (userPrincipal != null) { var name = MainHelper.ShortName(userPrincipal.DisplayName); var sid = userPrincipal.Sid.Value; list.Add(sid, name); } } } return list.OrderBy(x => x.Value); } }
private static void CountWordsFromFile(string line) { var words = line.Trim().Split(new[] { ' ', '-', '.', ',', '!', '?' }); var meanWords = new Dictionary<string, int>(); foreach (var word in words) { if (word != string.Empty && word != "?" && word != "!" && word != "." && word != ",") { var lowerWord = word.ToLower(); if (meanWords.ContainsKey(lowerWord)) { meanWords[lowerWord]++; } else { meanWords.Add(lowerWord, 1); } } } var dict = meanWords.OrderBy(x => x.Value); foreach (var word in dict) { Console.WriteLine("{0} -> {1} times", word.Key, word.Value); } }
static void Main() { StreamReader reader = new StreamReader(@"../../words.txt"); using (reader) { string text = reader.ReadToEnd(); string[] words = text.Split(new char[] { '.', ',', '!', '?', '-', ' ' }, StringSplitOptions.RemoveEmptyEntries); Dictionary<string, int> occurs = new Dictionary<string, int>(); foreach (var word in words) { if (occurs.ContainsKey(word.ToLower())) { occurs[word.ToLower()]++; } else { occurs.Add(word.ToLower(), 1); } } var sortedOccurs = occurs.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value); // for this task cast to a Dictionary is not nessesary it works with return form lambda expressin key-value-pair too. foreach (var occur in sortedOccurs) { Console.WriteLine("{0} -> {1} times", occur.Key, occur.Value); } } }
static void Main() { var occurences = new Dictionary<string, int>(); var reader = new StreamReader("text.txt", Encoding.UTF8); using (reader) { var line = reader.ReadLine(); while (line != null) { string regexPattern = @"[^\p{L}]*\p{Z}[^\p{L}]*"; var currentLineWords = Regex.Split(line, regexPattern); foreach (var word in currentLineWords) { if (!occurences.ContainsKey(word.ToLower())) { occurences.Add(word.ToLower(), 1); } else { occurences[word.ToLower()]++; } } line = reader.ReadLine(); } } var sortedValues = occurences.OrderBy(kvp => kvp.Value); foreach (var item in sortedValues) { Console.WriteLine("{0} -> {1} times", item.Key, item.Value); } }
private static void Main(string[] args) { var reader = new StreamReader("..//..//text.txt", Encoding.UTF8); string[] words; using (reader) { words = reader.ReadToEnd() .Split(new[] { ' ', '.', '!', '?', '-', ',', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.ToLower()) .ToArray(); } var wordsDict = new Dictionary<string, int>(); for (int i = 0; i < words.Length; i++) { string word = words[i]; if (!wordsDict.ContainsKey(word)) { wordsDict[word] = 0; } wordsDict[word]++; } var sortedWords = wordsDict.OrderBy(x => x.Value); foreach (var i in sortedWords) { Console.WriteLine(i.Key + " -> " + i.Value + " times"); } }
private static string GetTypeKey(Dictionary<string, Type> fields) { string key = string.Empty; foreach (var field in fields.OrderBy(v => v.Key).ThenBy(v => v.Value.Name)) key += field.Key + ";" + field.Value.Name + ";"; return key; }
/// <summary> /// To do. Create a clever search algorithm. /// </summary> /// <param name="Word"></param> /// <param name="Collection"></param> /// <returns></returns> public string GetSimilar(string Word, List<string> Collection) { if (Word.IsNullOrEmpty()) { return Word; } Dictionary<string, int> keys = new Dictionary<string, int>(); /*foreach (string s in words.Keys) { if (s.EndsWith(Word)) { keys.Add(s, s.Length); } }*/ Collection.AsParallel().ForAll(s => { if (s.EndsWith(Word)) { keys.Add(s, s.Length); } }); if (!keys.Any() && Word.Length > 2) { return this.GetSimilar(Word.Substring(1), Collection); } string key = keys.OrderBy(val => val.Value).FirstOrDefault().Key; return key; }
internal static void Main() { var reader = new StreamReader(@"..\..\words.txt"); char[] separators = { ' ', '.', ',', '!', '?', '–' }; using (reader) { string all = reader.ReadToEnd(); string[] words = all.Split(separators, StringSplitOptions.RemoveEmptyEntries); var result = new Dictionary<string, int>(); for (int i = 0; i < words.Length; i++) { if (result.ContainsKey(words[i].ToLower())) { result[words[i].ToLower()]++; } else { result[words[i].ToLower()] = 1; } } foreach (var item in result.OrderBy(x => x.Value)) { Console.WriteLine("{0} -> {1} {2}", item.Key, item.Value, item.Value == 1 ? "time" : "times"); } } }
private void FillData() { conn = DBconnection.GetConnection(); if (conn.State.ToString() == "Closed") { conn.Open(); } Dictionary<string, string> UserListDictionary = new Dictionary<string, string>(); SqlCommand usrListCmd = new SqlCommand("SELECT x_id,fname,lname FROM [sms].[dbo].[user] as us INNER JOIN [sms].[dbo].[teacher] as teach ON us.x_id = teach.teach_id INNER JOIN [sms].[dbo].[person] as pr ON pr.id = teach.id WHERE Role='User'", conn); SqlDataReader dr = usrListCmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { int IndexXID = dr.GetOrdinal("x_id"); int IndexFname = dr.GetOrdinal("fname"); int IndexLname = dr.GetOrdinal("lname"); string UserXID = dr.GetString(IndexXID); string Fname = dr.GetString(IndexFname); string Lname = dr.GetString(IndexLname); UserListDictionary = UserListDictionary.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value); UserListDictionary.Add(UserXID, Fname + " " + Lname); } } usrList.DisplayMember = "Value"; usrList.ValueMember = "Key"; usrList.DataSource = new BindingSource(UserListDictionary, null); }
public string Get(string[] documentUris) { string prefix = "Content-Security-Policy: default-src 'none'"; string result = ""; cacheLock.EnterReadLock(); try { var dictsToMerge = rules.Where(x => documentUris.Contains(x.Key)).Select(x => x.Value); var mergedDict = new Dictionary<string, HashSet<string>>(); foreach (var dict in dictsToMerge) { foreach (var e in dict) { if (!mergedDict.ContainsKey(e.Key)) { mergedDict[e.Key] = new HashSet<string>(); } mergedDict[e.Key] = new HashSet<string>(mergedDict[e.Key].Concat(e.Value)); } } result = mergedDict.OrderBy(x => x.Key).Select(entry => ( entry.Value.OrderBy(x => x).Aggregate(entry.Key, (total, next) => (total + " " + next)) )).Aggregate(prefix, (total, next) => (total + "; " + next)); } finally { cacheLock.ExitReadLock(); } return result; }
public static void Main(string[] args) { using (var sr = new StreamReader("words.txt")) { IDictionary<string, int> wordsCount = new Dictionary<string, int>(); string[] words = GetWords(sr.ReadToEnd()); for (int i = 0; i < words.Length; i++) { string word = words[i].ToLower(); if (wordsCount.ContainsKey(word)) { wordsCount[word]++; } else { wordsCount[word] = 1; } } var wordsOrderedByOccurrences = wordsCount.OrderBy(x => x.Value); foreach (var word in wordsOrderedByOccurrences) { Console.WriteLine("{0} => {1} times", word.Key, word.Value); } } }
//public static char[, ,] cube; static void Main() { string[] rawDimentions = Console.ReadLine().Split(); int width = int.Parse(rawDimentions[0]); int height = int.Parse(rawDimentions[1]); int depth = int.Parse(rawDimentions[2]); char[, ,] cube = new char[width, height, depth]; for (int h = 0; h < height; h++) { string[] line = Console.ReadLine().Split(); for (int d = 0; d < depth; d++) { string token = line[d]; for (int w = 0; w < width; w++) { cube[w, h, d] = token[w]; } } } Dictionary<char, int> stars = new Dictionary<char, int>(); for (int h = 1; h < height - 1; h++) { for (int d = 1; d < depth - 1; d++) { for (int w = 1; w < width - 1; w++) { if (cube[w, h, d] == cube[w, h + 1, d] && cube[w, h, d] == cube[w, h - 1, d] && cube[w, h, d] == cube[w + 1, h, d] && cube[w, h, d] == cube[w - 1, h, d] && cube[w, h, d] == cube[w, h, d + 1] && cube[w, h, d] == cube[w, h, d - 1]) { if (stars.ContainsKey(cube[w, h, d])) { stars[cube[w, h, d]] += 1; } else { stars.Add(cube[w, h, d], 1); } } } } } int starsCount = 0; foreach (var star in stars) { starsCount += star.Value; } Console.WriteLine(starsCount); foreach (var star in stars.OrderBy(m => m.Key)) { Console.WriteLine("{0} {1}", star.Key, star.Value); } }
public static void Main() { var testString = "This is the TEXT. Text, text, text – THIS TEXT! Is this the text?"; var splitted = testString.Split(new char[] { ' ', ',', '.', '?', '!', ';', '–' }, StringSplitOptions.RemoveEmptyEntries) .Select(w => w.ToLower()) .ToList(); var result = new Dictionary<string, int>(); foreach (var word in splitted) { if (result.ContainsKey(word)) { result[word] += 1; } else { result[word] = 1; } } var ordered = result.OrderBy(x => x.Value).ToList(); foreach (var item in ordered) { Console.WriteLine("{0, 10} --> {1}", item.Key, item.Value); } }
static void Main(string[] args) { var text = new StreamReader("text.txt").ReadToEnd().ToLower(); // string regex = @"\b\w+\b"; // MatchCollectionollection words = Regex.Matches(text, regex); var words = text.Split(new char[] { '.', '!', '?', ';', ' ', ':', ',', '-' }, StringSplitOptions.RemoveEmptyEntries); var dictionary = new Dictionary<string, int>(); foreach (var item in words) { if (dictionary.ContainsKey(item)) { dictionary[item]++; } else { dictionary.Add(item, 1); } } foreach (var item in dictionary.OrderBy(x => x.Value)) { Console.WriteLine("{0} -> {1}", item.Key, item.Value); } Console.ReadKey(true); }
static void Main() { string text = "It’s your 10 digit Fido number 4%^&[email protected] ( for example [email protected] )."; string[] words = Regex.Split(text, @"[\W+0-9_~!@#$%^&*()_+,=-`/?.,<>\|'"";:]"); Dictionary<char, int> countchars = new Dictionary<char, int>(); for (int i = 0; i < words.Length; i++) { foreach (var character in words[i]) { if (countchars.ContainsKey(character)) { countchars[character]++; } else { countchars.Add(character, 1); } } } var sortedLetters = countchars.OrderBy(x => x.Key); foreach (var letter in sortedLetters) { Console.WriteLine("Letter --> {0} - Number --> {1}", letter.Key, letter.Value); } }
public static bool IsAnagram(string a, string b) { Dictionary<char, int> dictionary1 = new Dictionary<char, int>(); foreach (var chaR in a) { if (dictionary1.ContainsKey(chaR)) { dictionary1[chaR] += 1; } else { dictionary1.Add(chaR, 1); } } Dictionary<char, int> dictionary2 = new Dictionary<char, int>(); foreach (var chaR in b) { if (dictionary2.ContainsKey(chaR)) { dictionary2[chaR] += 1; } else { dictionary2.Add(chaR, 1); } } bool isEqual = dictionary1.OrderBy(r => r.Key).SequenceEqual(dictionary2.OrderBy(r => r.Key)); return isEqual; }
public static void Dump(Dictionary<string, ObjectMemoryCounters> objects, Dictionary<string, string> totals) { try { if (objects != null && _objectsLogger != null && _objectsLogger.IsInfoEnabled) { foreach (var omc in objects.Values) { var collector = new Dictionary<string, string>(); omc.FormatTo(collector); var data = collector.OrderBy(kvp => kvp.Key); CheckFirstObjectWrite(data); _objectsLogger.InfoFormat("{0};{1}", omc.Name, string.Join(";", data.Select(kvp => kvp.Value).ToArray())); } } if (totals != null && _mainLogger != null && _mainLogger.IsInfoEnabled) { var data = totals.OrderBy(kvp => kvp.Key); CheckFirstMainWrite(data); _mainLogger.Info(string.Join(";", data.Select(kvp => kvp.Value).ToArray())); } } catch { // don't care } }
public static void Main() { string[] specialSigns = { " ", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "+" }; string input = Console.ReadLine(); for (int i = 0; i < specialSigns.Length; i++) { input = input.Replace(specialSigns[i], string.Empty); } Dictionary<char, int> allLetters = new Dictionary<char, int>(); for (int i = 0; i < input.Length; i++) { if (allLetters.ContainsKey(input[i])) { allLetters[input[i]]++; } else { allLetters.Add(input[i], 1); } } var sortedLetters = allLetters.OrderBy(x => x.Key); foreach (var item in sortedLetters) { Console.WriteLine("Letter --> {0} - Number --> {1}", item.Key, item.Value); } }
/// <summary> /// Logs the best parameters. /// </summary> /// <param name="bestParameters">The best parameters.</param> /// <param name="bbobConfig">The bbob configuration.</param> /// <param name="pathToInstanceFolder">The path to instance folder.</param> private static void LogBestParameters( Dictionary <string, IAllele> bestParameters, BbobRunnerConfiguration bbobConfig, string pathToInstanceFolder) { var bestParamsConsole = string.Join( " ", bestParameters?.OrderBy(p => p.Key).Select(p => string.Format(CultureInfo.InvariantCulture, "{0}", (double)p.Value.GetValue())) ?? new string[0]); // evaluate the best found config on all instances. print commands to execute python + compute average performance var pythonCommand = string.Concat( bbobConfig.PythonBin, " ", bbobConfig.PathToExecutable, $" {bbobConfig.FunctionId} {"{0}"} ", bestParamsConsole); var instances = BbobUtils.CreateInstanceList(pathToInstanceFolder); Thread.Sleep(500); LoggingHelper.WriteLine(VerbosityLevel.Info, "################################################"); LoggingHelper.WriteLine(VerbosityLevel.Info, "Commands to evaluate parameters:"); var instanceResults = new List <double>(instances.Count); foreach (var instance in instances) { var bbobRunner = new BbobRunner(bbobConfig.FunctionId, bestParameters, bbobConfig.PythonBin, bbobConfig.PathToExecutable); var runTask = bbobRunner.Run(instance, new CancellationToken(false)); var currentResult = runTask.Result; // read instance id var instanceId = -1; using (var reader = File.OpenText(instance.Path)) { instanceId = int.Parse(reader.ReadLine()); } var finalCommand = string.Format(pythonCommand, instanceId); LoggingHelper.WriteLine(VerbosityLevel.Info, finalCommand, false); LoggingHelper.WriteLine(VerbosityLevel.Info, FormattableString.Invariant($"result={currentResult.Value}"), false); instanceResults.Add(currentResult.Value); } LoggingHelper.WriteLine(VerbosityLevel.Info, "################################################"); var averageResult = instanceResults.Any() ? instanceResults.Average() : double.NaN; if (!File.Exists("averageResults.csv")) { var header = string.Join(";", Enumerable.Range(0, instances.Count).Select(i => $"instance_{i}")) + ";average\r\n"; File.WriteAllText("averageResults.csv", header); } var averageInvariant = string.Format(CultureInfo.InvariantCulture, "{0}\r\n", averageResult); var resultLine = string.Join(";", instanceResults.Select(r => string.Format(CultureInfo.InvariantCulture, "{0}", r))); File.AppendAllText("averageResults.csv", string.Concat(resultLine, ";", averageInvariant)); LoggingHelper.WriteLine(VerbosityLevel.Info, FormattableString.Invariant($"Average Result={averageResult}")); }
/// <summary> /// Formats the parameters as enumerable. /// </summary> /// <param name="bestParameters">The parameters.</param> /// <returns>The enumerable.</returns> private static IEnumerable <string> FormatParametersAsEnumerable(Dictionary <string, IAllele> bestParameters) { return(bestParameters? .OrderBy(p => p.Key) .Select( p => string.Format( CultureInfo.InvariantCulture, "{0}", (double)p.Value.GetValue())) ?? new string[0]); }
public static List <ErrorData> OnInputValidating( Context context, SiteSettings ss, Dictionary <int, IssueModel> issueHash) { var errors = issueHash ?.OrderBy(data => data.Key) .SelectMany((data, index) => OnInputValidating( context: context, ss: ss, issueModel: data.Value, rowNo: index + 1)) .Where(data => data.Type != Error.Types.None).ToList() ?? new List <ErrorData>(); if (errors.Count == 0) { errors.Add(new ErrorData(type: Error.Types.None)); } return(errors); }
public int?Run() { //Find the best multicast server to use var serverId = -1; if (_group.ClusterId == -1) //-1 is default cluster { _cluster = _uow.ComServerClusterRepository.GetFirstOrDefault(x => x.IsDefault); if (_cluster == null) { return(null); } } else { _cluster = _uow.ComServerClusterRepository.GetById(_group.ClusterId); if (_cluster == null) { return(null); } } var availableMulticastServers = _uow.ComServerClusterServerRepository.GetMulticastClusterServers(_cluster.Id); if (!availableMulticastServers.Any()) { return(null); } var taskInUseDict = new Dictionary <int, int>(); foreach (var mServer in availableMulticastServers) { var counter = new ServiceActiveMulticastSession().GetAll() .Count(x => x.ComServerId == mServer.ComServerId); taskInUseDict.Add(mServer.ComServerId, counter); } if (taskInUseDict.Count == 1) { serverId = taskInUseDict.Keys.First(); } else if (taskInUseDict.Count > 1) { var orderedInUse = taskInUseDict.OrderBy(x => x.Value); if (taskInUseDict.Values.Distinct().Count() == 1) { //all multicast server have equal tasks - randomly choose one. var index = _random.Next(0, taskInUseDict.Count); serverId = taskInUseDict[index]; } else { //Just grab the first one with the smallest queue, could be a duplicate but will eventually even out on it's own serverId = orderedInUse.First().Key; } } return(serverId); }
static void Main(string[] args) { using (StreamReader sr = new StreamReader("input.txt")) { var lines = sr.ReadToEnd().Split("\n").OrderBy(x => x); var idRegex = new Regex(@"#(?<id>\d+)"); int asleepMinute = 0; int wakeUpMinute = 0; var asleepRegex = new Regex(@":(?<minute>\d+).*falls asleep"); var wakeUpRegex = new Regex(@":(?<minute>\d+).*wakes up"); string currentId = ""; var dict = new Dictionary <string, Sleep>(); foreach (var line in lines) { var matches = idRegex.Match(line); if (matches.Success) { currentId = matches.Groups["id"].Value; } else { var sleepMatches = asleepRegex.Match(line); if (sleepMatches.Success) { asleepMinute = int.Parse(sleepMatches.Groups["minute"].Value); } else { var wakeUpMatches = wakeUpRegex.Match(line); wakeUpMinute = int.Parse(wakeUpMatches.Groups["minute"].Value); var sleepTime = wakeUpMinute - asleepMinute; if (dict.ContainsKey(currentId)) { var sleep = dict[currentId]; sleep.SleepTime += sleepTime; for (int i = asleepMinute; i < wakeUpMinute; i++) { sleep.SleepMinutes[i]++; } } else { var sleepMinutes = new int[60]; for (int i = asleepMinute; i < wakeUpMinute; i++) { sleepMinutes[i]++; } dict.Add(currentId, new Sleep(sleepTime, sleepMinutes)); } } } } var foundGuard = dict.OrderBy(x => x.Value.SleepTime).Last(); int max = foundGuard.Value.SleepMinutes.Max(); int minuteMostAsleep = foundGuard.Value.SleepMinutes.ToList().FindIndex(x => x == max); Console.WriteLine($"Guard {foundGuard.Key}, sleep time {foundGuard.Value.SleepTime}, minute {minuteMostAsleep}"); Console.WriteLine($"Answer 1 = {int.Parse(foundGuard.Key)*minuteMostAsleep}"); //excercise 2 var guard2 = dict.OrderBy(x => x.Value.SleepMinutes.Max()).Last(); max = guard2.Value.SleepMinutes.Max(); minuteMostAsleep = guard2.Value.SleepMinutes.ToList().FindIndex(x => x == max); Console.WriteLine($"Guard {guard2.Key}, sleep time {guard2.Value.SleepTime}, minute {minuteMostAsleep}"); Console.WriteLine($"Answer 2 = {int.Parse(guard2.Key)*minuteMostAsleep}"); } }
public bool writeDTMFiles( string path ) { Console.WriteLine( "\nStart writing string file..." ); if ( File.Exists( path ) ) Console.WriteLine( "WARNING: SKUA-GOCAD file {0} exists! Overwriting!", path ); Stopwatch watch = new Stopwatch(); watch.Start(); // first: fileheader DateTime now = DateTime.Now; string startText = Path.GetFileNameWithoutExtension( path ) + "," + DateTime.Now.ToString( "dd-MMM-yy" ) + ",,\n"; string separatorLine = "0, 0.000, 0.000, 0.000,\n"; StringBuilder text = new StringBuilder( 4096 ); text.Append( startText + separatorLine.Replace( " 0.000,", " 0.000, 0.000," ) ); Dictionary<int, int> idDict = new Dictionary<int, int>(); try { var sortedDict = _StringDict.OrderBy( idx => idx.Key ).GroupBy( i => i.Value.ID ).OrderBy( i => i.First().Value.ID ); int lastID = sortedDict.First().First().Value.ID; int lineNr = 0; foreach ( var obj in sortedDict ) { foreach ( var lowerObj in obj ) { ++lineNr; if ( lastID != lowerObj.Value.ID ) { text.Append( separatorLine ); lastID = lowerObj.Value.ID; ++lineNr; } idDict[lowerObj.Key] = lineNr; text.Append( lowerObj.Value.ID + ", " + lowerObj.Value.Y + ", " + lowerObj.Value.X + ", " + lowerObj.Value.Z + ", \n" ); } } } catch ( Exception ex ) { Console.WriteLine( "An exception occured during var reading!" ); Console.WriteLine( ex.Message ); foreach ( string key in ex.Data.Keys ) Console.WriteLine( key + " - " + ex.Data[key] ); //Console.WriteLine( "Conversation line: \"" + line + "\"" ); return false; } text.Append( "0, 0.000, 0.000, 0.000,\n0, 0.000, 0.000, 0.000,END\n" ); File.WriteAllText( path + ".str", text.ToString() ); Console.WriteLine( "Finished exporting string file..." ); Console.WriteLine( "\nStart writing dtm file..." ); text.Clear(); text.Append( Path.GetFileNameWithoutExtension( path ) + ".str,;algorithm=standard;fields=x,y\n" ); text.Append( "0, 0.000, 0.000, 0.000, END\n" ); int trisolation = 1; int lastOID = -9999; foreach ( DTMObject dtm in _DTMList.OrderBy( i => i.objectNumber ) ) { if ( lastOID != dtm.objectNumber ) { trisolation = 1; lastOID = dtm.objectNumber; } text.Append( "OBJECT, " + dtm.objectNumber + ",\n" ); text.Append( "TRISOLATION, " + trisolation++ + ", neighbours=no,validate=false,algorithm=legacy\n" ); int triangleID = 1; foreach ( int[] values in dtm.objects.Values ) { if ( values.Length < 3 ) { Console.WriteLine( "Failure, less than 3 values! Skipping..." ); Console.WriteLine( values ); continue; } text.Append( triangleID + ", " + idDict[values[0]] + ", " + idDict[values[1]] + ", " + idDict[values[2]] + ",\n" ); triangleID++; } } text.Append( "END\n" ); File.WriteAllText( path + ".dtm", text.ToString() ); watch.Stop(); Console.WriteLine( "Finished exporting dtm file..." ); Console.WriteLine( "Time: {0} ms", watch.ElapsedMilliseconds ); return true; }
static void Main(string[] args) { Dictionary <string, string> bookStatus = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase) { { "Lots Of Programming Stuff", "IN" }, { "Even More on C#", "IN" }, { "Big Book of C#", "IN" }, { "Databases and More", "IN" }, { "SQL and You", "IN" }, { "Big Book of Outdated Code", "IN" }, { "Beginner's Guide to C#", "IN" }, { "Beginner's Database Handbook", "IN" }, { "C# Player's Guide", "IN" }, { "String Comparison Basics", "IN" }, }; Dictionary <string, string> StudentID = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase) { { "U123", "JIMMY JONES" }, { "U234", "JAMIE NOEL" }, { "U345", "SCOTT BRIDGES" }, { "U456", "ALEXANDER ZILL" }, { "U567", "WILFORD WILLIAMS" }, }; List <string> students = new List <string>(); students.Add("Jimmy Jones"); students.Add("Jamie Noel"); students.Add("Scott Bridges"); students.Add("Alexander Zill"); students.Add("Wilford Williams"); students = students.ConvertAll(d => d.ToUpper()); bool restart = true; { while (restart == true) { Header(); { Console.WriteLine("\nEnter Menu Item Number"); string menuItem = Console.ReadLine(); int userInput; userInput = NumberCheck(menuItem); int caseRestart = 0; while (caseRestart == 0) { switch (userInput) { case 1: do { Console.Clear(); Header(); Console.WriteLine("Student Names:\n"); StringBuilder names = new StringBuilder(); for (int i = 0; i < students.Count; i++) { students.Sort(); names.AppendLine(students[i]); } Console.WriteLine(names.ToString()); userInput = DoNext(menuItem); Console.Clear(); Header(); continue; }while (userInput == 1); break; case 2: do { Console.Clear(); Header(); Console.WriteLine("Available Resources:\n"); StringBuilder resources = new StringBuilder(); foreach (KeyValuePair <string, string> item in bookStatus.OrderBy(key => key.Key)) { if (item.Value == "IN") { resources.AppendLine(item.Key); } } Console.WriteLine(resources.ToString()); userInput = DoNext(menuItem); Console.Clear(); Header(); break; }while (userInput == 2); break; case 3: // student account do { Console.Clear(); Header(); Console.WriteLine("\nType In A Four Digit User Account Number From The List Below To Print Account Information\n\n"); StringBuilder account = new StringBuilder(); foreach (KeyValuePair <string, string> pair in StudentID.OrderBy(key => key.Key)) { account.AppendLine("User ID: " + pair.Key + " ** Name: " + pair.Value); } Console.WriteLine(account.ToString()); string userNameInput = Console.ReadLine(); NullOrWhiteSpace(userNameInput); userInput = NumberCheck(menuItem); string userNameInputUpper = userNameInput.ToUpper(); if (StudentID.ContainsKey(userNameInputUpper)) { if (bookStatus.ContainsValue(userNameInputUpper)) { Console.Clear(); Header(); Console.WriteLine("\nThe Following Items Are Checked Out:"); foreach (KeyValuePair <string, string> pair in bookStatus) { if (pair.Value == userNameInputUpper) { Console.WriteLine(pair.Key); } } StreamWriter writer = new StreamWriter("UserID" + userNameInputUpper + "_StudentAccount.txt"); using (writer) { writer.WriteLine("Bootcamp Resource Checkout System"); writer.WriteLine("Student Account For User ID: " + userNameInputUpper + ", " + StudentID[userNameInputUpper]); writer.WriteLine("\nChecked Out Resources:\n"); foreach (KeyValuePair <string, string> pair in bookStatus) { if (pair.Value == userNameInputUpper) { writer.WriteLine(pair.Key); } } } Console.Clear(); Console.WriteLine("\nFile Export Preview\n"); using (StreamReader sr = File.OpenText("UserID" + userNameInputUpper + "_StudentAccount.txt")) { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } Console.WriteLine("\nYour Student Account Was Successfully Exported.\nPress \"Y\" To Preview And Print A Summary Of All Library Resources.\nPress Any Other Key For The Main Menu\n"); { string restartAsString = Console.ReadLine(); userInput = NumberCheck(menuItem); if (restartAsString.Equals("Y", StringComparison.CurrentCultureIgnoreCase)) { StreamWriter writer2 = new StreamWriter("UserID" + userNameInputUpper + "_AvailableResources.txt"); using (writer2) { writer2.WriteLine("Bootcamp Resource Checkout System"); writer2.WriteLine("Resource List For User ID: " + userNameInputUpper + ", " + StudentID[userNameInputUpper]); writer2.WriteLine("\n\nUnavailable Resources:\n"); foreach (KeyValuePair <string, string> pair in bookStatus) { if (pair.Value != "IN") { writer2.WriteLine(pair.Key); } } writer2.WriteLine("\n\nAvailable Resources:\n"); foreach (KeyValuePair <string, string> pair in bookStatus) { if (pair.Value == "IN") { writer2.WriteLine(pair.Key); } } } Console.Clear(); Console.WriteLine("\nBootcamp Resource Book Summary\n"); using (StreamReader sr2 = File.OpenText("UserID" + userNameInputUpper + "_AvailableResources.txt")) { string s2 = ""; while ((s2 = sr2.ReadLine()) != null) { Console.WriteLine(s2); } } } else { Console.Clear(); Header(); userInput = DoNext(menuItem); Console.Clear(); Header(); break; } } } { Console.WriteLine(); StringBldrLine(); Console.WriteLine(); Console.WriteLine(); Header(); userInput = DoNext(menuItem); break; } } else { Console.Clear(); Header(); Console.WriteLine("\nYou Have No Books Checked Out"); userInput = DoNext(menuItem); Console.Clear(); Header(); break; } } else { Console.WriteLine("\nThat Is Not A Valid Entry"); userInput = DoNext(menuItem); Console.Clear(); Header(); break; } }while (userInput == 3); break; case 4: // checkout do { Console.Clear(); Header(); int booksOut = 1; if (bookStatus.ContainsValue("IN")) { Console.WriteLine("\nEnter User Account Nbr To Begin Checkout\n\n"); { foreach (KeyValuePair <string, string> pair in StudentID) { Console.WriteLine(pair.Key + " " + pair.Value); } string userNameInput = Console.ReadLine(); NullOrWhiteSpace(userNameInput); userInput = NumberCheck(menuItem); string userNameInputUpper = userNameInput.ToUpper(); foreach (KeyValuePair <string, string> pair in bookStatus) { if (pair.Value == userNameInputUpper) { booksOut = booksOut + 1; } } if (StudentID.ContainsKey(userNameInputUpper)) { if (booksOut <= 3) { Console.Clear(); Header(); Console.WriteLine("\n\nChoose A Book To Checkout"); foreach (KeyValuePair <string, string> item in bookStatus.OrderBy(key => key.Key)) { if (item.Value == "IN") { Console.WriteLine(item.Key); } } Console.WriteLine(); string userResourceInput = Console.ReadLine(); NullOrWhiteSpace(userResourceInput); userInput = NumberCheck(menuItem); string userResourceInputUpper = userResourceInput.ToUpper(); if ((bookStatus.ContainsKey(userResourceInput)) && (bookStatus[userResourceInputUpper] == "IN")) { Console.Clear(); Header(); Console.WriteLine("\nUser ID: " + userNameInputUpper + " has checked out \"" + userResourceInputUpper + "\"."); bookStatus[userResourceInputUpper] = userNameInputUpper; userInput = DoNext(menuItem); Console.Clear(); Header(); break; } else { Console.WriteLine("Error: Request Unavailable"); userInput = DoNext(menuItem); Console.Clear(); Header(); break; } } if (booksOut >= 3) { Console.WriteLine("\nUser ID: " + userNameInputUpper + " has checked out the maximum number of resources."); userInput = DoNext(menuItem); Console.Clear(); Header(); break; } } else { Console.WriteLine("\nThat Is Not A Valid Entry"); userInput = DoNext(menuItem); Console.Clear(); Header(); break; } } } else { Console.WriteLine("\nAll Resources Are Currently Unavailable"); userInput = DoNext(menuItem); Console.Clear(); Header(); break; } }while (userInput == 4); break; case 5: //Return do { Console.Clear(); Header(); Console.WriteLine("Enter User Account Nbr To Begin Checkout\n\n"); foreach (KeyValuePair <string, string> pair in StudentID) { Console.WriteLine(pair.Key + " " + pair.Value); } string userNameInput = Console.ReadLine(); NullOrWhiteSpace(userNameInput); userInput = NumberCheck(menuItem); string userNameInputUpper = userNameInput.ToUpper(); if (StudentID.ContainsKey(userNameInputUpper)) { if (bookStatus.ContainsValue(userNameInputUpper)) { Console.Clear(); Header(); Console.WriteLine("\nThe Following Items Are Checked Out:"); foreach (KeyValuePair <string, string> pair in bookStatus) { if (pair.Value == userNameInputUpper) { Console.WriteLine(pair.Key); } } { Console.WriteLine("\nEnter the Book Name You Want To Return"); string userResourceInput = Console.ReadLine(); NullOrWhiteSpace(userResourceInput); userInput = NumberCheck(menuItem); string userResourceInputUpper = userResourceInput.ToUpper(); if ((bookStatus.ContainsKey(userResourceInput)) && (bookStatus[userResourceInputUpper] == userNameInputUpper)) { Console.Clear(); Header(); Console.WriteLine("\nUser ID: " + userNameInputUpper + " has checked in \"" + userResourceInputUpper + "\"."); bookStatus[userResourceInputUpper] = "IN"; userInput = DoNext(menuItem); Console.Clear(); Header(); break; } else { Console.Clear(); Header(); Console.WriteLine("\nError: Request Unavailable"); userInput = DoNext(menuItem); Console.Clear(); Header(); break; } } } else { Console.Clear(); Header(); Console.WriteLine("\nYou Have No Books Checked Out"); userInput = DoNext(menuItem); Console.Clear(); Header(); break; } } Console.WriteLine("\nThat Is Not A Valid Entry"); userInput = DoNext(menuItem); Console.Clear(); Header(); break; }while (userInput == 5); break; case 6: { Console.WriteLine("\nAre you sure you want to exit? \nPress \"N\" to restart program\nPress any other key to exit"); string restartAsString = Console.ReadLine(); userInput = NumberCheck(menuItem); if (restartAsString.Equals("n", StringComparison.CurrentCultureIgnoreCase)) { caseRestart++; Console.Clear(); Header(); break; } else { Console.Clear(); Console.WriteLine("GoodBye"); Thread.Sleep(1000); Environment.Exit(0); } break; } default: { Console.WriteLine("\nThat is not a Valid Entry"); userInput = DoNext(menuItem); Console.Clear(); Header(); break; } } } } } } }
static void Main(string[] args) { Dictionary <string, List <string> > wordDef = new Dictionary <string, List <string> >(); string[] firstTokens = Console.ReadLine().Split(" | "); foreach (string item in firstTokens) { string[] tokens = item.Split(": "); string word = tokens[0]; string def = tokens[1]; if (!wordDef.ContainsKey(word)) { wordDef.Add(word, new List <string>()); wordDef[word].Add(def); } else { wordDef[word].Add(def); } } string[] wordTokens = Console.ReadLine().Split(" | "); foreach (string word in wordTokens) { if (wordDef.ContainsKey(word)) { Console.WriteLine(word); foreach (var kvp in wordDef) { string currWord = kvp.Key; List <string> defs = kvp.Value; if (currWord == word) { foreach (var def in defs.OrderByDescending(x => x.Length)) { Console.WriteLine($" -{def}"); } } } } } string last = Console.ReadLine(); if (last == "End") { return; } else { foreach (var kvp in wordDef.OrderBy(x => x.Key)) { Console.Write(kvp.Key + " "); } Console.WriteLine(); } }
static void Main(string[] args) { var regex = new Regex(@"[A-Z][a-z]+[a] [A-Z][a-z]+[a]"); var femalesStudentsPlaces = new Dictionary <string, int>(); var femalesStudentsScores = new Dictionary <string, int>(); var malesStudentsPlaces = new Dictionary <string, int>(); var malesStudentsScores = new Dictionary <string, int>(); string input; while ((input = Console.ReadLine()) != "end") { string[] studentData = input.Split("|").ToArray(); string studentName = studentData[0]; int place = int.Parse(studentData[1]); int scores = int.Parse(studentData[2]); if (!(femalesStudentsPlaces.ContainsKey(studentName)) && regex.IsMatch(studentName)) { femalesStudentsPlaces[studentName] = place; femalesStudentsScores[studentName] = scores; } else { malesStudentsPlaces[studentName] = place; malesStudentsScores[studentName] = scores; } } Console.WriteLine(); Console.WriteLine($"Female count: {femalesStudentsScores.Keys.Count}"); Console.WriteLine($"Female average score: {femalesStudentsScores.Values.Average()}"); Console.WriteLine($"Male count: {malesStudentsScores.Keys.Count}"); Console.WriteLine($"Male average score: {malesStudentsScores.Values.Average()}"); Console.WriteLine(); Console.WriteLine("Search by Name and Username: "******"The scores of {search} are: {malesStudentsScores[search]}"); Console.WriteLine($"The place of {search} is: {malesStudentsPlaces[search]} out of {malesStudentsPlaces.Keys.Count + femalesStudentsPlaces.Keys.Count}"); var sortedFemalesStudentsPlaces = femalesStudentsPlaces.OrderBy(kvp => kvp.Value).ThenBy(kvp => kvp.Key).ToDictionary(a => a.Key, b => b.Value); var sortedMalesStudentsPlaces = malesStudentsPlaces.OrderBy(kvp => kvp.Value).ThenBy(kvp => kvp.Key).ToDictionary(a => a.Key, b => b.Value); // foreach (var kvp in sortedFemalesStudentsPlaces) // { // Console.WriteLine(kvp.Key); // Console.WriteLine($"- Place: {kvp.Value}"); // Console.WriteLine($"- Total Scores: {femalesStudentsScores[kvp.Key]}"); // Console.WriteLine(); // } // foreach (var kvp in sortedMalesStudentsPlaces) // { // Console.WriteLine(kvp.Key); // Console.WriteLine($"- Place: {kvp.Value}"); // Console.WriteLine($"- Total Scores: {malesStudentsScores[kvp.Key]}"); // Console.WriteLine(); // } }
private HttpWebRequest PrepareAuthorizedRequestGet(string oauth_token, string oauth_token_secret, string oauth_consumer_key, string oauth_consumer_secret, string resource_url) { // NB: per gestire il POST bisogna aggiungere alla variabile dic anche i dati del body string httpMethod = "GET"; // normalizza l'url togliendo eventuali parametri da query string Uri urlToCall = new Uri(resource_url); var normalizedResourceUrl = String.Format("{0}{1}{2}{3}", urlToCall.Scheme, Uri.SchemeDelimiter, urlToCall.Authority, urlToCall.AbsolutePath); // estrae eventuali parametri da query string Dictionary <string, string> dic = new Dictionary <string, string>(); string queryString = urlToCall.Query; if (queryString.StartsWith("?")) { queryString = queryString.Substring(1); } string[] queryParameters = queryString.Split('&'); string[] arr = null; foreach (var kv in queryParameters) { arr = kv.Split('='); dic.Add(arr[0], arr[1]); } // aggiunge i parametri oauth dic.Add("oauth_consumer_key", oauth_consumer_key); var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString())); dic.Add("oauth_nonce", oauth_nonce); var oauth_signature_method = "HMAC-SHA1"; dic.Add("oauth_signature_method", oauth_signature_method); var timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString(); dic.Add("oauth_timestamp", oauth_timestamp); dic.Add("oauth_token", oauth_token); var oauth_version = "1.0"; dic.Add("oauth_version", oauth_version); // ordina tutti i parametri in ordine alfabetico per chiave var orderedDic = dic.OrderBy(x => x.Key).ToDictionary(k => k.Key, v => v.Value); StringBuilder sb = new StringBuilder(); foreach (var par in orderedDic) { sb.AppendFormat("{0}={1}&", par.Key, par.Value); } //elimina l'ultimo & var baseString = sb.ToString(); baseString = baseString.TrimEnd('&'); // completa la base string baseString = string.Concat(httpMethod.ToUpper(), "&", Uri.EscapeDataString(normalizedResourceUrl), "&", Uri.EscapeDataString(baseString)); var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret)); // compone l'header string oauth_signature; using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))) { oauth_signature = Convert.ToBase64String( hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString))); } var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " + "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " + "oauth_token=\"{4}\", oauth_signature=\"{5}\", " + "oauth_version=\"{6}\""; var authHeader = string.Format(headerFormat, Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp), Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_version) ); ServicePointManager.Expect100Continue = false; // crea la request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url); request.Headers.Add("Authorization", authHeader); request.Method = httpMethod.ToUpper(); return(request); }
public IEnumerable <LexiconLetter> AllLetters() { return(LettersByAlphabet .OrderBy(x => x.Key) .Select(x => x.Value)); }
private string HtmlHelp(string _url) { try { int number = 0; Dictionary <string, Tuple <string, MethodInfo, int, long> > dic = new Dictionary <string, Tuple <string, MethodInfo, int, long> >(_memberInfos); StringBuilder sb = new StringBuilder(); sb.Append("<!DOCTYPE html>"); sb.Append(@"<html lang = ""en"">"); sb.Append(@"<meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" />"); sb.Append(@"<head>"); sb.Append(@"<link href=""//echarts.baidu.com/echarts2/doc/asset/css/bootstrap.css"" rel=""stylesheet"">"); sb.Append(@" </head><body>"); sb.Append(@"<div class=""navbar navbar-default"" role=""navigation"" id=""head""> <div class=""container""><div class=""navbar - header"">UcAsp.NET</div></div></div>"); sb.Append(@"<div class=""panel-group"" id=""accordion"">"); lock (dic) { foreach (KeyValuePair <string, Tuple <string, MethodInfo, int, long> > kv in dic.OrderBy(o => o.Value.Item1)) { object[] clazz = kv.Value.Item2.DeclaringType.GetCustomAttributes(typeof(Restful), true); string clazzpath = string.Empty; string path = kv.Value.Item2.Name; object[] cattri = kv.Value.Item2.GetCustomAttributes(typeof(Restful), true); if (clazz != null && clazz.Length > 0) { if (null != cattri && cattri.Length > 0) { UcAsp.RPC.Restful rf = (UcAsp.RPC.Restful)cattri[0]; if (rf.NoRest) { continue; } if (rf.Path != null) { path = rf.Path.ToLower(); } } string apixml = kv.Value.Item2.Module.FullyQualifiedName.Replace(".dll", "") + ".xml"; string filename = kv.Value.Item2.DeclaringType.FullName + "." + kv.Value.Item2.Name; int len = kv.Value.Item2.GetParameters().Length; if (len > 0) { filename += "("; for (int i = 0; i < len; i++) { ParameterInfo _param = kv.Value.Item2.GetParameters()[i]; if (i != len - 1) { filename += _param.ParameterType.FullName + ","; } else { filename += _param.ParameterType.FullName; } } filename += ")"; } string helptxt = string.Empty; if (File.Exists(apixml)) { XmlDocument doc = new XmlDocument(); doc.Load(apixml); XmlNode xn = doc.SelectSingleNode("/doc/members/member[@name=\"M:" + filename + "\"]"); if (xn != null) { helptxt = xn.InnerText; } } number++; sb.Append(@"<div class=""panel panel-default""><div class=""panel-heading"">"); sb.AppendFormat(@"<!--div class=""list-group-item"">{0} </div--> <h4 class=""panel-title""><a href=""#collapse" + number + @""" data-toggle=""collapse"" data-parent=""#accordion"" ><h4>[{3}]</h4>{2} 方法名:{1} ", kv.Value.Item1, kv.Value.Item2.Name.Replace("<", "<").Replace(">", " >"), helptxt, number); ParameterInfo[] para = kv.Value.Item2.GetParameters(); sb.Append(@"("); for (int x = 0; x < para.Length; x++) { sb.AppendFormat("{0} {1}", Proxy.GetTypeName(para[x].ParameterType).Replace("<", "<").Replace(">", " >"), para[x].Name.Replace("<", "<").Replace(">", " >")); if (x != para.Length - 1) { sb.Append(","); } } sb.AppendFormat(" ) Method:POST 返回类型:{0}[自启动运行{1}次][{2}]</a>", Proxy.GetTypeName(kv.Value.Item2.ReturnType).Replace("<", "<").Replace(">", " >"), kv.Value.Item3, kv.Value.Item4); sb.Append(@"</h4></div><div id=""collapse" + number); sb.Append(@""" class=""panel-collapse collapse"">"); clazzpath = ((UcAsp.RPC.Restful)clazz[0]).Path.ToLower(); sb.Append(@"<div class=""list-group-item"">Example:Request Body JSON : <br /><font color=red style=""word-wrap:break-word"">{"); for (int xx = 0; xx < para.Length; xx++) { sb.AppendFormat("\"{0}\":", para[xx].Name); if (para[xx].ParameterType.FullName.ToString().StartsWith("System")) { sb.AppendFormat(para[xx].ParameterType.Name.ToString()); } else { sb.Append("{"); PropertyInfo[] ps = para[xx].ParameterType.GetProperties(); int pn = 0; foreach (PropertyInfo p in ps) { sb.Append("\"" + p.Name + "\":"); if (p.PropertyType.FullName.ToString().StartsWith("System")) { sb.AppendFormat(p.PropertyType.Name.ToString()); } else { sb.AppendFormat("value"); } if (pn != ps.Length - 1) { sb.Append(","); } pn++; } sb.Append("}"); } if (xx != para.Length - 1) { sb.Append(","); } } sb.Append(@"}</font><br />");//</div><div class=""list-group-item""> sb.AppendFormat(@"API URL<br />[1]:{0}/WEBAPI/{1}/{2}/<br /> </div> ", _url, clazzpath, path); sb.Append(@"</div></div>"); } } } sb.Append("</div>"); sb.Append(@"<script src =""//libs.baidu.com/jquery/2.1.1/jquery.min.js""></script>"); sb.Append(@"<script src=""//echarts.baidu.com/echarts2/doc/asset/js/bootstrap.min.js""></script>"); sb.Append("</body></html>"); return(sb.ToString()); } catch (Exception ex) { Console.WriteLine(ex); return(ex.StackTrace.ToString()); } }
public override string ToString() { StringBuilder res = new StringBuilder(); res.AppendLine("Installed Interpreters: " + _installedInterpreters); res.AppendLine(" v2.x: " + _installedV2); res.AppendLine(" v3.x: " + _installedV3); res.AppendLine("Debug Launches: " + _debugLaunchCount); res.AppendLine("Normal Launches: " + _normalLaunchCount); res.AppendLine("Debug Adapter Launch Timeouts: " + _debugAdapterLaunchTimeoutCount); res.AppendLine("Debug Adapter Attach Timeouts: " + _debugAdapterAttachTimeoutCount); res.AppendLine(); lock (_seenPackages) { if (_seenPackages.Any(p => p != null)) { res.AppendLine("Seen Packages:"); foreach (var package in _seenPackages) { if (package != null) { res.AppendLine(" " + package.Name); } } res.AppendLine(); } } lock (_analysisInfo) { if (_analysisInfo.Any(a => a != null)) { res.AppendLine("Completion DB analyses:"); foreach (var analysis in _analysisInfo) { if (analysis != null) { res.AppendLine(" {0} - {1}s".FormatInvariant(analysis.InterpreterId, analysis.AnalysisSeconds)); } } } } lock (_analysisAbnormalities) { if (_analysisAbnormalities.Any()) { res.AppendFormat("Analysis abnormalities ({0}):", _analysisAbnormalities.Count); res.AppendLine(); foreach (var abnormalExit in _analysisAbnormalities) { res.AppendLine(abnormalExit); } res.AppendLine(); } } lock (_analysisTiming) { lock (_analysisCount) { if (_analysisTiming.Any()) { res.AppendLine("Analysis timing:"); foreach (var kv in _analysisTiming.OrderBy(kv => kv.Key)) { long count; if (!_analysisCount.TryGetValue(kv.Key, out count)) { count = kv.Value.Item1; } res.AppendFormat(" {0} (count {5}, slow count {1}, {2} timeouts, max {3:N0}ms, mean {4:N2}ms)", kv.Key, kv.Value.Item1, kv.Value.Item4, kv.Value.Item2, (double)kv.Value.Item3 / kv.Value.Item1, count); res.AppendLine(); } res.AppendLine(); } } } return(res.ToString()); }
public IEnumerable <ActionDto> GetActions(IEnumerable <Guid> ids) { string entityName = typeof(TEntity).Name; Stopwatch sw = new Stopwatch(); sw.Start(); if (ids == null) { throw new ArgumentNullException(nameof(ids)); } var dbSet = _dataService.GetDbSet <TEntity>(); var currentUser = _userIdProvider.GetCurrentUser(); var role = currentUser.RoleId.HasValue ? _dataService.GetById <Role>(currentUser.RoleId.Value) : null; Log.Information("{entityName}.GetActions (Load role): {ElapsedMilliseconds}ms", entityName, sw.ElapsedMilliseconds); sw.Restart(); var actionDtos = new Dictionary <string, ActionInfo>(); var entities = dbSet.Where(x => ids.Contains(x.Id)).ToList(); Log.Information("{entityName}.GetActions (Load data from DB): {ElapsedMilliseconds}ms", entityName, sw.ElapsedMilliseconds); sw.Restart(); var singleActions = _serviceProvider.GetService <IEnumerable <IAppAction <TEntity> > >(); foreach (var action in singleActions) { string actionName = action.GetType().Name.ToLowerFirstLetter(); if ((role?.Actions != null && !role.Actions.Contains(actionName)) || actionDtos.ContainsKey(actionName)) { continue; } var validEntities = entities.Where(e => action.IsAvailable(e)); if (validEntities.Any() && ids.Count() == validEntities.Count()) { actionDtos[actionName] = ConvertActionToDto(action, actionName, ids); } } Log.Information("{entityName}.GetActions (Find single actions): {ElapsedMilliseconds}ms", entityName, sw.ElapsedMilliseconds); sw.Restart(); if (ids.Count() > 1) { var groupActions = _serviceProvider.GetService <IEnumerable <IGroupAppAction <TEntity> > >(); foreach (var action in groupActions) { string actionName = action.GetType().Name.ToLowerFirstLetter(); if ((role?.Actions != null && !role.Actions.Contains(actionName)) || actionDtos.ContainsKey(actionName)) { continue; } if (action.IsAvailable(entities)) { actionDtos[actionName] = ConvertActionToDto(action, actionName, ids); } } } Log.Information("{entityName}.GetActions (Find group actions): {ElapsedMilliseconds}ms", entityName, sw.ElapsedMilliseconds); var result = actionDtos.OrderBy(x => x.Value.OrderNumber) .Select(x => x.Value.Dto) .ToList(); return(result); }
/// <summary> /// /// </summary> /// <param name="otherRoom"></param> /// <param name="height"></param> /// <param name="path"></param> /// <param name="roughL"></param> /// <returns></returns> public bool AdjacentPathTo(RoomInfoElec otherRoom, double height, out PathExWall path, out double roughL) { ///Use the base class method to decide whether this two room ///are adjacent and get the needed info. bool boolResult = base.IsAdjacentTo(otherRoom, out List <Curve> adjCurves, out List <XYZ> normVectors, out List <double> widthList); ///If the two room are adjacent,calculate ///the intersect point of the two room fixtures centriod line. if (boolResult) { Curve c2c = Line.CreateBound (this.FixCentroid, otherRoom.FixCentroid); ///Store the endpoint for the useful area of adjacent curve. Dictionary <XYZ, Curve> vList = new Dictionary <XYZ, Curve>(); XYZ crossPt = new XYZ(); //The real crossing point on the center line. XYZ normVec = new XYZ(); //The normal vector double width = 0; //The width of the wall bool directLine = false; //If direct line exist. int n = widthList.Count; //Start iteration. for (int i = 0; i < n; i++) { Curve adjC = adjCurves[i]; ///Trunk line need 200mm space. double reserveW = UnitUtils .ConvertToInternalUnits (200, DisplayUnitType.DUT_MILLIMETERS); /// If curve is not long enough,go to next one. if (adjC.Length <= reserveW) { continue; } /// If curve is long enough,shorten each side 100mm. XYZ p1 = adjC.GetEndPoint(0); XYZ p2 = adjC.GetEndPoint(1); XYZ dir = (p2 - p1).Normalize(); XYZ p1new = p1 + 0.5 * reserveW * dir; XYZ p2new = p2 - 0.5 * reserveW * dir; Line adjCuse = Line.CreateBound(p1new, p2new); vList.Add(p1new, adjC); vList.Add(p2new, adjC); ///If intersect point found,stop searching. if (IsPlanIntersect(adjCuse, c2c, out XYZ iPt)) { crossPt = iPt; normVec = normVectors[i]; width = widthList[i]; directLine = true; break; } } ///If no directline is formed,while avaiable curve exist, ///which means vList is not empty,find the closet point. if (!directLine && (vList.Count > 0)) { ///Sort the dictionary by distance to the curve. var vListSorted = vList.OrderBy(v => c2c.Distance(v.Key)); int i = adjCurves.IndexOf(vListSorted.First().Value); crossPt = vListSorted.First().Key; normVec = normVectors[i]; width = widthList[i]; } /// Only when width != 0 ,a crossing path can be created. /// Width =0 means no available route is generated.Go false. if (width != 0) { //Create the crossing path. XYZ ptHere = crossPt + 0.5 * width * normVec; XYZ ptThere = crossPt - 0.5 * width * normVec; FixtureE crossPtHere = new FixtureE(ptHere, height, this.Room); FixtureE crossPtThere = new FixtureE(ptThere, height, otherRoom.Room); path = new PathExWall(crossPtHere, crossPtThere); roughL = width + (ptHere - FixCentroid).GetLength() + (ptThere - otherRoom.FixCentroid).GetLength(); return(true); } } path = null; roughL = 0; return(false); }
public LootHandler(Dictionary <double, List <object> > lootTable = null) { this._LootTable = lootTable?.OrderBy(a => a.Key).ToDictionary(a => a.Key, a => a.Value) ?? new Dictionary <double, List <object> >(); }
static void Main(string[] args) { Dictionary <string, int> junks = new Dictionary <string, int>(); Dictionary <string, int> materials = new Dictionary <string, int>() { { "shards", 0 }, { "fragments", 0 }, { "motes", 0 } }; bool isItemObtainable = false; while (!isItemObtainable) { string[] input = Console.ReadLine().Split(); int quantity = 0; for (int i = 0; i < input.Length; i++) { if (i % 2 != 0) // Material or Junk { string resource = input[i].ToLower(); if (materials.ContainsKey(resource)) // Material { materials[resource] += quantity; if (materials[resource] >= 250) { isItemObtainable = true; break; } } else // Junk { if (!junks.ContainsKey(resource)) { junks.Add(resource, 0); } junks[resource] += quantity; } } else // Quantity { quantity = int.Parse(input[i]); } } } KeyValuePair <string, int> kvp = materials.FirstOrDefault(v => v.Value >= 250); materials[kvp.Key] -= 250; string item = string.Empty; switch (kvp.Key) { case "shards": item = "Shadowmourne"; break; case "fragments": item = "Valanyr"; break; case "motes": item = "Dragonwrath"; break; } Console.WriteLine($"{item} obtained!"); foreach (var material in materials.OrderByDescending(m => m.Value).ThenBy(m => m.Key)) { Console.WriteLine($"{material.Key}: {material.Value}"); } foreach (var junk in junks.OrderBy(j => j.Key)) { Console.WriteLine($"{junk.Key}: {junk.Value}"); } }
static void Main(string[] args) { var keyMaterials = new Dictionary <string, int>(); keyMaterials.Add("shards", 0); keyMaterials.Add("fragments", 0); keyMaterials.Add("motes", 0); var junk = new Dictionary <string, int>(); string input = Console.ReadLine(); bool hasWinner = false; string winningMaterial = ""; while (true) { string[] splitedInput = input.Split(); for (int i = 0; i < splitedInput.Length; i += 2) { int currentMarks = int.Parse(splitedInput[i]); string currentMaterial = splitedInput[i + 1].ToLower(); bool isKeyMaterial = currentMaterial == "shards" || currentMaterial == "fragments" || currentMaterial == "motes"; if (isKeyMaterial) { keyMaterials[currentMaterial] += currentMarks; if (keyMaterials[currentMaterial] >= 250) { hasWinner = true; keyMaterials[currentMaterial] -= 250; winningMaterial = currentMaterial; break; } } if (!junk.ContainsKey(currentMaterial) && !isKeyMaterial) { junk[currentMaterial] = 0; } if (!isKeyMaterial) { junk[currentMaterial] += currentMarks; } } if (hasWinner) { break; } input = Console.ReadLine(); } if (winningMaterial == "shards") { Console.WriteLine($"Shadowmourne obtained!"); } else if (winningMaterial == "fragments") { Console.WriteLine($"Valanyr obtained!"); } else if (winningMaterial == "motes") { Console.WriteLine($"Dragonwrath obtained!"); } var orderedKeyMaterial = keyMaterials.OrderByDescending(x => x.Value).ThenBy(x => x.Key).ToDictionary(x => x.Key, y => y.Value); foreach (var material in orderedKeyMaterial) { Console.WriteLine($"{material.Key}: {material.Value}"); } var orderedJunkMaterials = junk.OrderBy(x => x.Key); foreach (var material in orderedJunkMaterials) { Console.WriteLine($"{material.Key}: {material.Value}"); } }
static void Main(string[] args) { var contests = new Dictionary <string, string>(); var candidates = new Dictionary <string, Dictionary <string, long> >(); string[] data = null; while (true) { data = Console.ReadLine().Split(':', StringSplitOptions.RemoveEmptyEntries); if (data[0] == "end of contests") { break; } string contest = data[0]; string password = data[1]; contests[contest] = password; } while (true) { data = Console.ReadLine().Split("=>", StringSplitOptions.RemoveEmptyEntries); if (data[0] == "end of submissions") { break; } string contest = data[0]; string password = data[1]; string username = data[2]; int points = int.Parse(data[3]); if (contests.ContainsKey(contest) && contests[contest] == password) { if (!candidates.ContainsKey(username)) { candidates.Add(username, new Dictionary <string, long>()); } if (!candidates[username].ContainsKey(contest)) { candidates[username].Add(contest, points); } if (points > candidates[username][contest]) { candidates[username][contest] = points; } } } var orderedCandidates = candidates .ToDictionary(k => k.Key, v => v.Value.OrderByDescending(x => x.Value) .ToDictionary(ks => ks.Key, vs => vs.Value)); KeyValuePair <string, Dictionary <string, long> > bestCandidate = orderedCandidates.First(); long bestPoints = bestCandidate.Value.Values.Sum(); Console.WriteLine($"Best candidate is {bestCandidate.Key} with total {bestPoints} points."); Console.WriteLine("Ranking:"); foreach (var userKVP in candidates.OrderBy(n => n.Key)) { string username = userKVP.Key; Dictionary <string, long> userContests = userKVP.Value; Console.WriteLine(username); foreach (var contestKVP in userContests.OrderByDescending(up => up.Value)) { Console.WriteLine($"# {contestKVP.Key} -> {contestKVP.Value}"); } } }
static Locate() // A static constructor runs exactly once and before the class or an instance of it is needed { RecipesByCategoryInOrder = RecipesByCategory.OrderBy(CategoryIndex).ThenBy(IndexWithinCategory).ToList(); }
private void DisplayHttpContextWalkerVB(wucCodeExplorerContext codeExplorerContext, string context) { StringBuilder sb = new StringBuilder(); Dictionary <string, Int32> matches = new Dictionary <string, Int32>(); var sourceCode = ""; // If a source file has been specified use it if (codeExplorerContext.teSourceFile.Text.Length > 0) { string fileNameAndPath = codeExplorerContext.teSourceFile.Text; if (!File.Exists(fileNameAndPath)) { sb.AppendLine(string.Format("File ({0}) does not exist. Check path and name.", fileNameAndPath)); goto PrematureExitBummer; } if ((Boolean)CodeExplorer.configurationOptions.ceListImpactedFilesOnly.IsChecked) { sb.AppendLine("Would Process these files ...."); sb.AppendLine(string.Format(" {0}", fileNameAndPath)); } else { sb.AppendLine(string.Format("Processing ({0}) ...", fileNameAndPath)); using (var sr = new StreamReader(fileNameAndPath)) { sourceCode = sr.ReadToEnd(); } var tree = VisualBasicSyntaxTree.ParseText(sourceCode); string pattern = string.Empty; VNCSW.VB.HttpContextCurrentInvocationExpression walker = null; walker = new VNCCA.SyntaxWalkers.VB.HttpContextCurrentInvocationExpression(context); walker.Messages = sb; walker.Matches = matches; walker.Visit(tree.GetRoot()); } } else { // Otherwise, go see if one or more files has been selected if (codeExplorerContext.cbeSourceFile.SelectedItems.Count > 0) { if ((Boolean)CodeExplorer.configurationOptions.ceListImpactedFilesOnly.IsChecked) { sb.AppendLine("Would Process these files ...."); } foreach (XElement file in codeExplorerContext.cbeSourceFile.SelectedItems) { string filePath = codeExplorerContext.teSourcePath.Text + wucCodeExplorerContext.GetFilePath(file); if (!File.Exists(filePath)) { sb.AppendLine(string.Format("ERROR File ({0}) does not exist. Check config file", filePath)); continue; } if ((Boolean)CodeExplorer.configurationOptions.ceListImpactedFilesOnly.IsChecked) { sb.AppendLine(string.Format(" {0}", filePath)); } else { sb.AppendLine(string.Format("Processing ({0}) ...", filePath)); using (var sr = new StreamReader(filePath)) { sourceCode = sr.ReadToEnd(); } var tree = VisualBasicSyntaxTree.ParseText(sourceCode); string pattern = string.Empty; VNCSW.VB.HttpContextCurrentInvocationExpression walker = null; walker = new VNCSW.VB.HttpContextCurrentInvocationExpression(context); walker.Messages = sb; walker.Matches = matches; walker.Visit(tree.GetRoot()); } } } } sb.AppendLine("Summary"); foreach (var item in matches.OrderBy(v => v.Key).Select(k => k.Key)) { sb.AppendLine(string.Format("Count: {0,3} {1} ", matches[item], item)); } PrematureExitBummer: CodeExplorer.teSourceCode.Text = sb.ToString(); }
private bool CheckBlockCollide(PlayerLocation location) { var bbox = GetBoundingBox(); var pos = location.ToVector3(); var coords = new BlockCoordinates( (int)Math.Floor(KnownPosition.X), (int)Math.Floor((bbox.Max.Y + bbox.Min.Y) / 2.0), (int)Math.Floor(KnownPosition.Z)); Dictionary <double, Block> blocks = new Dictionary <double, Block>(); for (int x = -1; x < 2; x++) { for (int z = -1; z < 2; z++) { for (int y = -1; y < 2; y++) { Block block = Level.GetBlock(coords.X + x, coords.Y + y, coords.Z + z); if (block is Air) { continue; } BoundingBox blockbox = block.GetBoundingBox() + 0.3f; if (blockbox.Intersects(GetBoundingBox())) { //if (!blockbox.Contains(KnownPosition.ToVector3())) continue; if (block is FlowingLava || block is StationaryLava) { HealthManager.Ignite(1200); continue; } if (!block.IsSolid) { continue; } blockbox = block.GetBoundingBox(); var midPoint = blockbox.Min + new Vector3(0.5f); blocks.Add(Vector3.Distance((pos - Velocity), midPoint), block); } } } } if (blocks.Count == 0) { return(false); } var firstBlock = blocks.OrderBy(pair => pair.Key).First().Value; BoundingBox boundingBox = firstBlock.GetBoundingBox(); if (!SetIntersectLocation(boundingBox, KnownPosition.ToVector3())) { // No real hit return(false); } // Use to debug hits, makes visual impressions (can be used for paintball too) var substBlock = new Stone { Coordinates = firstBlock.Coordinates }; Level.SetBlock(substBlock); // End debug block Velocity = Vector3.Zero; return(true); }
static Dictionary <int, float> GetTopValues(Dictionary <int, float> data, int amount) { return(data.OrderBy(v => v.Value).Reverse().Take(amount).ToDictionary(kv => kv.Key, kv => kv.Value)); }
private static string CalculateSignature(string url, string method, string body, string nonce, string timestamp, string consumerKey, string token, string consumerSecret, string tokenSecret, string callback = null) { var querystring = string.Empty; if (url.Contains("?")) { querystring = url.Substring(url.IndexOf("?") + 1); url = url.Substring(0, url.IndexOf("?")); } var parameterDict = new Dictionary <string, string> { { "oauth_consumer_key", consumerKey }, { "oauth_nonce", nonce }, { "oauth_signature_method", "HMAC-SHA1" }, { "oauth_timestamp", timestamp }, { "oauth_token", token }, { "oauth_version", "1.0" } }; if (!string.IsNullOrEmpty(callback)) { parameterDict.Add("oauth_callback", callback); } if (!string.IsNullOrEmpty(querystring)) { foreach (var qsParam in querystring.Split('&')) { parameterDict.Add(Uri.EscapeDataString(qsParam.Split('=')[0]), Uri.EscapeDataString(Uri.UnescapeDataString(qsParam.Split('=')[1]))); } } if (!string.IsNullOrEmpty(body)) { foreach (var param in body.Split('&')) { parameterDict.Add(Uri.EscapeDataString(param.Split('=')[0]), Uri.EscapeDataString(param.Split('=')[1])); } } var index = 0; var parameterString = new StringBuilder(); foreach (var param in parameterDict.OrderBy(i => i.Key)) { if (index > 0) { parameterString.Append("&"); } parameterString.AppendFormat("{0}={1}", param.Key, param.Value); index++; } var str = $"{method.ToUpper()}&{Uri.EscapeDataString(url)}&{Uri.EscapeDataString(parameterString.ToString())}"; var hmac = HMACSHA1(str, $"{consumerSecret}&{tokenSecret}"); return(Convert.ToBase64String(hmac)); }
public static void HandleFixBiotaEmoteDelay(Session session, params string[] parameters) { if (parameters.Length == 0) { CommandHandlerHelper.WriteOutputInfo(session, "This command is intended to be run while the world is in offline mode, or there are 0 players connected."); CommandHandlerHelper.WriteOutputInfo(session, "To run this fix, type fix-biota-emote-delay fix"); return; } var fix = parameters[0].Equals("fix", StringComparison.OrdinalIgnoreCase); CommandHandlerHelper.WriteOutputInfo(session, "Building weenie emote cache"); var weenieEmoteCache = BuildWeenieEmoteCache(); CommandHandlerHelper.WriteOutputInfo(session, $"Found {weenieEmoteCache.Count:N0} weenie templates w/ emote actions with delay 0"); using (var ctx = new ShardDbContext()) { CommandHandlerHelper.WriteOutputInfo(session, $"Finding biotas for these wcids"); var biotas = ctx.Biota.Where(i => weenieEmoteCache.ContainsKey(i.WeenieClassId)).ToList(); var distinct = biotas.Select(i => i.WeenieClassId).Distinct(); var counts = new Dictionary <uint, uint>(); foreach (var biota in biotas) { if (!counts.ContainsKey(biota.WeenieClassId)) { counts[biota.WeenieClassId] = 1; } else { counts[biota.WeenieClassId]++; } } CommandHandlerHelper.WriteOutputInfo(session, $"Found {biotas.Count} biotas matching {distinct.Count()} distinct wcids"); foreach (var kvp in counts.OrderBy(i => i.Key)) { CommandHandlerHelper.WriteOutputInfo(session, $"{kvp.Key} - {(WeenieClassName)kvp.Key} ({kvp.Value})"); } if (!fix) { CommandHandlerHelper.WriteOutputInfo(session, $"Dry run completed"); return; } var totalUpdated = 0; foreach (var biota in biotas) { bool updated = false; var query = from emote in ctx.BiotaPropertiesEmote join action in ctx.BiotaPropertiesEmoteAction on emote.Id equals action.EmoteId where emote.ObjectId == biota.Id && action.Delay == 1.0f select new { Emote = emote, Action = action }; var emoteActions = query.ToList(); foreach (var emoteAction in emoteActions) { var emote = emoteAction.Emote; var action = emoteAction.Action; // ensure this delay 1 should be delay 0 var hash = CalculateEmoteHash(emote); var weenieEmotes = weenieEmoteCache[biota.WeenieClassId]; if (!weenieEmotes.TryGetValue(hash, out var list)) { //CommandHandlerHelper.WriteOutputInfo(session, $"Skipping emote for {biota.WeenieClassId} not found in hash list"); continue; } if (!list.Contains(action.Order)) { //CommandHandlerHelper.WriteOutputInfo(session, $"Skipping emote for {biota.WeenieClassId} not found in action list"); continue; } // confirmed match, update delay 1 -> 0 action.Delay = 0.0f; updated = true; } if (updated) { CommandHandlerHelper.WriteOutputInfo(session, $"Fixed shard object {biota.Id:X8} of type {biota.WeenieClassId} - {(WeenieClassName)biota.WeenieClassId}"); totalUpdated++; } } ctx.SaveChanges(); CommandHandlerHelper.WriteOutputInfo(session, $"Completed successfully, fixed {totalUpdated} shard items"); } }
public void Start() { if (CancelToken == null) { CancelToken = new CancellationTokenSource(); Task.Run(async() => { string Json; JObject Trivia = null; Send(Channel, "Welcome to the trivia! To win, you need " + PointLimit + " points"); while (!CancelToken.IsCancellationRequested && !Points.ContainsValue(PointLimit)) { try { Question = string.Empty; while (Question == string.Empty) { Json = "http://jservice.io/api/random?count=1".WebResponse(); Trivia = JObject.Parse(Json.Substring(1, Json.Length - 2)); Question = Trivia["question"].ToString().Trim(); } Answer = RemoveHtml.Replace(Trivia["answer"].ToString(), string.Empty).Replace("\\", "").Replace("(", "").Replace(")", "").Trim('"'); if (Answer.StartsWith("a ")) { Answer = Answer.Substring(2); } else if (Answer.StartsWith("an ")) { Answer = Answer.Substring(3); } $"{Question.Compact()} | {Answer}".Log(); } catch (Exception Ex) { $"Trivia Exception {Ex}".Log(); continue; } await Task.Delay(100); Send(Channel, Question); this.Winner = null; for (int i = 0; i < 60; i++) { await Task.Delay(500); if (this.Winner != null) { if (!Points.ContainsKey(this.Winner.Id)) { Points.Add(this.Winner.Id, 0); } Points[this.Winner.Id]++; break; } if (i == 20) { Send(Channel, "Hint: `" + HardHint + "`"); } else if (i == 40) { Send(Channel, "Hint: `" + EasyHint + "`"); } } if (this.Winner == null) { Send(Channel, "Time's up! The answer was `" + this.Answer + "`"); } } await Task.Delay(250); string SendStr = "End of the trivia"; KeyValuePair <ulong, int> Winner = Points.OrderBy(u => u.Value).LastOrDefault(); if (Winner.Value != 0) { Db.AddPoints(Winner.Key, Winner.Value); try { SendStr += ", " + Channel.GetUser(Winner.Key).Mention + " won with " + Winner.Value + " point(s) - added " + Winner.Value + " extra pairs of glasses!"; } catch { SendStr += " - did the winner leave the channel?"; } } Points.Clear(); Send(Channel, SendStr); CancelToken = null; }); } }
private (IEnumerable <string> toDel, IEnumerable <string> toAdd, IEnumerable <string> toUpd) ResolveValueDiffs( Dictionary <string, ArgumentRegValue> oldState, Dictionary <string, ArgumentRegValue> newState) { if (oldState == null && newState == null) { return(RegUtil.EmptyStrings, RegUtil.EmptyStrings, RegUtil.EmptyStrings); } else if (oldState == null) { return(RegUtil.EmptyStrings, newState.Keys, RegUtil.EmptyStrings); } else if (newState == null) { return(oldState.Keys, RegUtil.EmptyStrings, RegUtil.EmptyStrings); } else { // Comparing entries in sorted key order var osEnts = oldState?.OrderBy(kv => kv.Key).ToArray(); var nsEnts = newState?.OrderBy(kv => kv.Key).ToArray(); var toDel = new List <string>(); var toUpd = new List <string>(); var toAdd = new List <string>(); var osNdx = 0; var nsNdx = 0; while (osNdx < osEnts.Length && nsNdx < nsEnts.Length) { var ose = osEnts[osNdx]; var nse = nsEnts[nsNdx]; var cmp = string.Compare(ose.Key, nse.Key); if (cmp < 0) { toDel.Add(ose.Key); ++osNdx; } else if (cmp > 0) { toAdd.Add(nse.Key); ++nsNdx; } else { if (ose.Value.Type != nse.Value.Type || ose.Value.Value != nse.Value.Value || ose.Value.ValueBase64 != nse.Value.ValueBase64 || (!ose.Value.Values?.SequenceEqual(nse.Value.Values) ?? false)) { toUpd.Add(ose.Key); } ++osNdx; ++nsNdx; } } while (osNdx < osEnts.Length) { toDel.Add(osEnts[osNdx++].Key); } while (nsNdx < nsEnts.Length) { toAdd.Add(nsEnts[nsNdx++].Key); } return(toDel, toAdd, toUpd); } }
static void Main(string[] args) { var input = Console.ReadLine(); var contestsByPassword = new Dictionary <string, string>(); while (input != "end of contests") { var tokens = input .Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); var contest = tokens[0]; var password = tokens[1]; if (!contestsByPassword.ContainsKey(contest)) { contestsByPassword[contest] = password; } input = Console.ReadLine(); } var usersByContests = new Dictionary <string, Dictionary <string, double> >(); input = Console.ReadLine(); while (input != "end of submissions") { var tokens = input .Split(new string[] { "=>" }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); var contest = tokens[0]; var password = tokens[1]; var user = tokens[2]; var points = double.Parse(tokens[3]); if (contestsByPassword.ContainsKey(contest)) { if (contestsByPassword[contest] == password) { if (!usersByContests.ContainsKey(user)) { usersByContests[user] = new Dictionary <string, double>(); } if (!usersByContests[user].ContainsKey(contest)) { usersByContests[user][contest] = points; } else { if (usersByContests[user][contest] < points) { usersByContests[user][contest] = points; } } } } input = Console.ReadLine(); } foreach (var user in usersByContests.OrderByDescending(e => e.Value.Values.Sum())) { Console.WriteLine($"Best candidate is {user.Key} with total {user.Value.Values.Sum()} points."); break; } Console.WriteLine("Ranking:"); foreach (var user in usersByContests.OrderBy(k => k.Key)) { Console.WriteLine(user.Key); foreach (var contest in user.Value.OrderByDescending(v => v.Value)) { Console.WriteLine($"# {contest.Key} -> {contest.Value}"); } } }
/// <summary> /// Return number appended to key name for current calendar key /// </summary> /// <param name="maxSet">The set number of the last contiguous run of ID sets (to aid defragmentation).</param> /// <returns>The set number, if it exists</returns> private static int?getKeySet(AppointmentItem ai, out int maxSet) { String returnSet = ""; int? returnVal = null; maxSet = 0; if (OutlookOgcs.Calendar.Instance.EphemeralProperties.PropertyExists(ai, EphemeralProperty.PropertyName.KeySet) && OutlookOgcs.Calendar.Instance.EphemeralProperties.PropertyExists(ai, EphemeralProperty.PropertyName.MaxSet)) { Object ep_keySet = OutlookOgcs.Calendar.Instance.EphemeralProperties.GetProperty(ai, EphemeralProperty.PropertyName.KeySet); Object ep_maxSet = OutlookOgcs.Calendar.Instance.EphemeralProperties.GetProperty(ai, EphemeralProperty.PropertyName.MaxSet); maxSet = Convert.ToInt16(ep_maxSet ?? ep_keySet); if (ep_keySet != null) { returnVal = Convert.ToInt16(ep_keySet); } return(returnVal); } Dictionary <String, String> calendarKeys = new Dictionary <string, string>(); UserProperties ups = null; try { ups = ai.UserProperties; for (int p = 1; p <= ups.Count; p++) { UserProperty up = null; try { up = ups[p]; if (up.Name.StartsWith(calendarKeyName)) { calendarKeys.Add(up.Name, up.Value.ToString()); } } finally { up = (UserProperty)OutlookOgcs.Calendar.ReleaseObject(up); } } } finally { ups = (UserProperties)OutlookOgcs.Calendar.ReleaseObject(ups); } try { //For backward compatibility, always default to key names with no set number appended if (calendarKeys.Count == 0 || (calendarKeys.Count == 1 && calendarKeys.ContainsKey(calendarKeyName) && calendarKeys[calendarKeyName] == Settings.Instance.UseGoogleCalendar.Id)) { maxSet = -1; return(returnVal); } foreach (KeyValuePair <String, String> kvp in calendarKeys.OrderBy(k => k.Key)) { Regex rgx = new Regex("^" + calendarKeyName + "-*(\\d{0,2})", RegexOptions.IgnoreCase); MatchCollection matches = rgx.Matches(kvp.Key); if (matches.Count > 0) { int appendedNos = 0; if (matches[0].Groups[1].Value != "") { appendedNos = Convert.ToInt16(matches[0].Groups[1].Value); } if (appendedNos - maxSet == 1) { maxSet = appendedNos; } if (kvp.Value == Settings.Instance.UseGoogleCalendar.Id) { returnSet = (matches[0].Groups[1].Value == "") ? "0" : matches[0].Groups[1].Value; } } } if (!string.IsNullOrEmpty(returnSet)) { returnVal = Convert.ToInt16(returnSet); } } finally { OutlookOgcs.Calendar.Instance.EphemeralProperties.Add(ai, new EphemeralProperty(EphemeralProperty.PropertyName.KeySet, returnVal)); OutlookOgcs.Calendar.Instance.EphemeralProperties.Add(ai, new EphemeralProperty(EphemeralProperty.PropertyName.MaxSet, maxSet)); } return(returnVal); }
public override string GetVideoUrl(VideoInfo video) { string data; if (video.Other is string && !string.IsNullOrWhiteSpace(video.GetOtherAsString())) { data = video.GetOtherAsString(); } else { data = GetWebData(video.VideoUrl); } Regex r = new Regex(@"<tr class=""linkTr"">.*?""linkQuality[^>]*>(?<q>[^<]*)<.*?linkHiddenUrl[^>]*>(?<u>[^<]*)<.*?</tr", RegexOptions.Singleline); Dictionary <string, string> d = new Dictionary <string, string>(); List <Hoster.HosterBase> hosters = Hoster.HosterFactory.GetAllHosters(); foreach (Match m in r.Matches(data)) { string u = m.Groups["u"].Value; Hoster.HosterBase hoster = hosters.FirstOrDefault(h => u.ToLowerInvariant().Contains(h.GetHosterUrl().ToLowerInvariant())); if (hoster != null) { string format = hoster.GetHosterUrl() + " [" + m.Groups["q"].Value + "] " + "({0})"; int count = 1; while (d.ContainsKey(string.Format(format, count))) { count++; } d.Add(string.Format(format, count), u); } } d = d.OrderBy((p) => { return(p.Key); }).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); video.PlaybackOptions = d; if (d.Count == 0) { return(""); } if ((video as LosMoviesVideoInfo).TrackingInfo == null) { (video as LosMoviesVideoInfo).TrackingInfo = new TrackingInfo() { VideoKind = VideoKind.Movie, Title = video.Title, Year = GetRelesaseYear(data), ID_IMDB = GetImdbId(data) }; } //sh.SetSubtitleText(video, GetTrackingInfo, false); string latestOption = (video is LosMoviesVideoInfo) ? (video as LosMoviesVideoInfo).LatestOption : ""; if (string.IsNullOrEmpty(latestOption)) { return(d.First().Value); } if (d.ContainsKey(latestOption)) { return(d[latestOption]); } return(d.First().Value); }