private static void SolvePart2() { var key = File.ReadAllText("Input.txt"); var password = new char[8]; var i = 0; using (var md5 = MD5.Create()) { while (password.Any(c => c == '\0')) { var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(key + i.ToString())); var hex = BitConverter.ToString(hash).Replace("-", ""); if (hex.Substring(0, 5) == "00000" && char.IsDigit(hex[5])) { var pos = int.Parse(hex[5].ToString()); if (pos < 8 && password[pos] == '\0') { password[pos] = hex[6]; } } i++; } } var s = password.Aggregate("", (current, c) => current + char.ToLower(c)); Console.WriteLine("Password = " + s); }
// reads the content of a request depending on its length private static string ReadContent(TextReader textReader, int contentLength) { var readBuffer = new char[contentLength]; textReader.Read(readBuffer, 0, readBuffer.Length); return(readBuffer.Aggregate(string.Empty, (current, ch) => current + ch)); }
/// <summary> /// Returns 80 characters of HTML from a specified URL. /// </summary> /// <param name="url">The URL to get the HTML from.</param> /// <param name="charCount">How many characters of the HTML to retrieve. Default is 80.</param> /// <returns>A specified number of characters of HTML from a specified URL.</returns> private static string GetHtmlFromUrl(string url, int charCount = 80) { var html = string.Empty; var req = (HttpWebRequest)WebRequest.Create(url); try { using (var resp = (HttpWebResponse)req.GetResponse()) { var isSuccess = (int)resp.StatusCode < 299 && (int)resp.StatusCode >= 200; if (isSuccess) { var responseStream = resp.GetResponseStream(); if (responseStream != null) { using (var reader = new StreamReader(responseStream)) { var cs = new char[charCount]; reader.Read(cs, 0, cs.Length); html = cs.Aggregate(html, (current, ch) => current + ch); } } } } } catch { return(string.Empty); } return(html); }
private string ReplaceSpecialChars(string old) { char[] chars = new char[] { ',', '.', '=', '(', ')', '!', '@', '#', '$', '%', '&', '~', '`', '+', ' ', '^', '*', '[', ']', '{', '}', '/', '?', ':', ';', '<', '>', '|' }; string newStr = chars.Aggregate(old, (c1, c2) => c1.Replace(c2, '_')); return(newStr); }
internal static String DecodeByte(String inputString) { Encoding encoding = Encoding.UTF8; Decoder decoder = encoding.GetDecoder(); String[] separator = { "-" }; String[] splittedInputString = inputString.Split(separator, StringSplitOptions.RemoveEmptyEntries); byte[] byteArray = new byte[splittedInputString.Length]; for (int i = 0; i < splittedInputString.Length; i++) { byteArray[i] = Convert.ToByte(splittedInputString[i]); } char[] charArray = new char[decoder.GetCharCount(byteArray, 0, byteArray.Length, true)]; String outputString = String.Empty; decoder.GetChars(byteArray, 0, byteArray.Length, charArray, 0, true); //for (int i = 0; i < charArray.Length; i++) //{ // outputString = outputString + charArray[i]; //} outputString = charArray.Aggregate(outputString, (current, t) => current + t); return(StringUtil.Rot13Transform(outputString)); }
private void renameStartButton_Click(object sender, EventArgs e) { //選択された行だけ対象に,文字を置換していく for (int i = 0; i < fileGridView.Rows.Count; i++) { int useCol = createdRadioButton.Checked ? 1 : 2; string beforePath = @fileGridView[0, i].Value.ToString(); string dirname = System.IO.Path.GetDirectoryName(beforePath) + "\\"; string ext = System.IO.Path.GetExtension(beforePath); string afterFileName = addedFileText.Text + fileGridView[useCol, i].Value.ToString() + ext; //文字削除 char[] removeChars = new char[] { ':', '/', ' ' }; afterFileName = removeChars.Aggregate(afterFileName, (s, c) => s.Replace(c.ToString(), "")); try { //実際にファイル名を変更する System.IO.File.Move(beforePath, dirname + afterFileName); } catch (IOException ex) { MessageBox.Show(beforePath + " >>> " + dirname + afterFileName + " --- " + ex.Message, "ファイル名変更時エラー", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2); } } }
public ScripterResult ScriptMigrationTargets(IEnumerable <SqlScript> migrationScripts) { Regex targetDbObjectRegex = new Regex(m_scrptingObjectRegEx, RegexOptions.IgnoreCase | RegexOptions.Multiline); List <ScriptObject> scriptObjects = new List <ScriptObject>(); foreach (SqlScript script in migrationScripts) { //extract db object target(s) from scripts MatchCollection matches = targetDbObjectRegex.Matches(script.Contents); foreach (Match m in matches) { string objectType = m.Groups[2].Value; ObjectTypeEnum type; if (Enum.TryParse <ObjectTypeEnum>(objectType, true, out type)) { ObjectActionEnum action = (ObjectActionEnum)Enum.Parse(typeof(ObjectActionEnum), m.Groups[1].Value, true); var scriptObject = new ScriptObject(type, action); if (string.IsNullOrEmpty(m.Groups[4].Value) && !string.IsNullOrEmpty(m.Groups[3].Value)) { //no schema specified scriptObject.ObjectName = m.Groups[3].Value; } else { scriptObject.ObjectSchema = m.Groups[3].Value; scriptObject.ObjectName = m.Groups[4].Value; } char[] removeCharacters = new char[] { '[', ']' }; scriptObject.ObjectSchema = removeCharacters.Aggregate(scriptObject.ObjectSchema, (c1, c2) => c1.Replace(c2.ToString(), "")); scriptObject.ObjectName = removeCharacters.Aggregate(scriptObject.ObjectName, (c1, c2) => c1.Replace(c2.ToString(), "")); scriptObjects.Add(scriptObject); } } } return(ScriptObjects(scriptObjects)); }
public static string GetFilteredText(string text, PaymentMethodType type) { if (type == PaymentMethodType.BankSlip && text != null) { char[] restrictedCharacters = new char[] { '@', '/', '\\', '-', '(', ')', ':', '_', '"', '<', '>', '\'', '!', '*', '°', '´', '+', '=', '`', '|', '?' }; string tmp = restrictedCharacters.Aggregate(text, (c1, c2) => c1.Replace(c2, ' ')); return(tmp); } return(text); }
static void Main(string[] args) { char[] characters = new char[] { 'h', 'e', 'l', 'l', 'o' }; StringBuilder mytext = characters.Aggregate(new StringBuilder(), (text, next) => text.Append(next)); Console.WriteLine(mytext); Console.ReadKey(); }
public static string RemoveNoNum(string str) { //ハイフンを除く char[] removeChars = new char[] { '-', '+', '.', ',', '/' }; //char[] removeChars = new char[] { '-' }; if (str == null || str == "") { return(""); } return(removeChars.Aggregate(str, (s, c) => s.Replace(c.ToString(), ""))); }
// reads the content of a request depending on its length private static string ReadContent(TextReader textReader, int contentLength) { var readBuffer = new char[contentLength]; var bytesRead = 0; while (bytesRead < contentLength) { bytesRead += textReader.Read(readBuffer, bytesRead, contentLength - bytesRead); } return(readBuffer.Aggregate(string.Empty, (current, ch) => current + ch)); }
public Problem0059() { var encryptedStrings = File.ReadAllText(@"resources\p059_cipher.txt").Split(','); var encrypted = new char[encryptedStrings.Length]; for (var i = 0; i < encrypted.Length; i++) { encrypted[i] = (char)int.Parse(encryptedStrings[i]); } var stopWatch = new Stopwatch(); stopWatch.Start(); long result = 0; // Solution: for (var a = 'a'; a <= 'z'; a++) { for (var b = 'a'; b <= 'z'; b++) { for (var c = 'a'; c <= 'z'; c++) { var decrypted = new char[encrypted.Length]; for (var i = 0; i < decrypted.Length; i++) { decrypted[i] = (char)(encrypted[i] ^ (i % 3 == 0 ? a : i % 3 == 1 ? b : c)); } var dec = new string(decrypted); if (!dec.Contains("Euler")) { continue; } // Console.WriteLine("\r" + a + b + c + "\t" + dec); result = decrypted.Aggregate(result, (current, ch) => current + ch); } } } stopWatch.Stop(); var elapsedTime = stopWatch.Elapsed.ToString(); Console.WriteLine("Result:\t" + result + "\tTime:\t" + (double.Parse(elapsedTime.Substring(elapsedTime.LastIndexOf(":") + 1, 2)) >= 1 ? double.Parse(elapsedTime.Substring(elapsedTime.LastIndexOf(":") + 1)) + " s" : double.Parse(elapsedTime.Substring(elapsedTime.IndexOf(".") + 1)) / 10_000 + " ms")); if (ProblemTest.DoBenchmark) { ProblemBenchmark.AddTime( 59, double.Parse(elapsedTime.Substring(elapsedTime.IndexOf(".") + 1)) / 10_000); } }
public static string RemoveSpecialCharacters(string inputString) { var retVal = string.Empty; var specialCharacters = new char[] { '`', '~', '!', '@', '#', '$', '%', '^', '&', '(', ')', '_', '-', '=', '+', '|', '\\', '{', '}', '[', ']', '"', '\'', ':', ';', '<', '>', '?', '/', ',', '.' }; inputString = specialCharacters.Aggregate(inputString, (current, chr) => current.Replace(chr.ToString(), "")); retVal = inputString.Trim(); return(retVal); }
public static bool IsDecimal(string str) { // Decimal型で許容できる数字以外の文字を消去する char[] removeChars = new char[] { '-', '+', '.', ',' }; string tempString = removeChars.Aggregate(str, (s, c) => s.Replace(c.ToString(), "")); // 符号、小数点を除いて、0~9の数字であればOK if (Regex.IsMatch(tempString, "^[0-9]+$")) { return(true); } return(false); }
public static string ToRegDecStr(string str) { //カンマを除く //char[] removeChars = new char[] { '-', '+', '.', ',' }; char[] removeChars = new char[] { ',' }; if (str == null || str == "") { return(""); } string rStr = removeChars.Aggregate(str, (s, c) => s.Replace(c.ToString(), "")); return(rStr); }
public static string ReverseString(string name) { var length = name.Length; var array = new char[length]; for (var i = 0; i < length; i++) { array[i] = name[i]; } Array.Reverse(array); var reversedString = array.Aggregate("", (current, item) => current + (char)item); return(reversedString); }
public string ParseSpecialCharacters(string value) { try { var specialCharacters = new char[] { '.', ',', '/', '-', '(', ')', ';', '%', '[', '*' }; var str = specialCharacters.Aggregate(value, (current, c) => current.Replace(c, ' ')); // parse consecutive white spaces to one str = Regex.Replace(str, @"\s+", " ").Trim(); return(str); } catch (Exception ex) { throw new Exception("ParseSpecialCharacters():" + ex.Message + ex.StackTrace); } }
public void A_UnfoldResourceAsyncSource_must_work_with_ByteString_as_well() { this.AssertAllStagesStopped(() => { var chunkSize = 50; var buffer = new char[chunkSize]; var p = Source.UnfoldResourceAsync(_open, reader => { var promise = new TaskCompletionSource <Option <ByteString> >(); var s = reader.Read(buffer, 0, chunkSize); promise.SetResult(s > 0 ? ByteString.FromString(buffer.Aggregate("", (s1, c1) => s1 + c1)).Slice(0, s) : Option <ByteString> .None); return(promise.Task); }, reader => { reader.Dispose(); return(Task.FromResult(NotUsed.Instance)); }) .RunWith(Sink.AsPublisher <ByteString>(false), Materializer); var c = this.CreateManualSubscriberProbe <ByteString>(); var remaining = ManyLines; Func <string> nextChunk = () => { if (remaining.Length <= chunkSize) { return(remaining); } var chunk = remaining.Take(chunkSize).Aggregate("", (s, c1) => s + c1); remaining = remaining.Substring(chunkSize); return(chunk); }; p.Subscribe(c); var sub = c.ExpectSubscription(); Enumerable.Range(0, 122).ForEach(i => { sub.Request(1); c.ExpectNext().ToString().Should().Be(nextChunk()); }); sub.Request(1); c.ExpectComplete(); }, Materializer); }
public static string ReplaceUnwantedCharacters(this string textFile) { //Ithink there is a way to use Environment.NewLine, //but probably I needed to change this solution to use it char[] separators = new char[] { '\r', '\n', }; var newString = new string(textFile.Where(c => ( char.IsLetter(c) || char.IsWhiteSpace(c) || char.IsSeparator(c)) && !char.IsDigit(c)) .ToArray()); //Aggregate applies a function to each item in the collection return(separators.Aggregate(newString, (str, cItem) => str.Replace(cItem, ' '))); }
public static string BuffortEncrypt(this string word, int key) { string encryptedWord = string.Empty; var wordArry = word.ToCharArray(); char[] newArry = new char[wordArry.Length]; for (int i = 0; i < wordArry.Length; i++) { int value = wordArry[i]; value -= 97; value = 26 - value + key; value = value % 26; value += 97; newArry[i] += (char)value; } encryptedWord = newArry.Aggregate(encryptedWord, (current, value) => current + value); return(encryptedWord.ToLower()); }
public static string GetAlias(string values) { if (string.IsNullOrEmpty(values)) { return(string.Empty); } var regex = new Regex("\\p{IsCombiningDiacriticalMarks}+"); string temp = values.Normalize(NormalizationForm.FormD); var converttext = regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D'); converttext = Regex.Replace(converttext, "[^a-zA-Z0-9_.]+", " ", RegexOptions.Compiled); var list = new char[] { ' ', '/', ',', '&', '\"', '?', '|', ':', '"', '`', '\\', ';', '~', '!', '@', '#', '$', '%', '^', '*', '(', ')', '\'', '_', '=', '+', '{', '}', '[', ']', '.', '>', '<' }; converttext = list.Aggregate(converttext, (current, schar) => current.Replace(schar, '-')); converttext = converttext.Replace("--", "-").Trim('.').TrimEnd('-').TrimStart('-'); return(converttext.ToLower()); }
/// <summary> /// 生成特定位数的唯一字符串 /// </summary> /// <param name="prefix">前缀编码</param> /// <returns></returns> public static string GenerateUniqueText(this string prefix) { prefix = string.IsNullOrEmpty(prefix) ? "" : prefix + "-"; int num = 8; System.Threading.Thread.Sleep(1); string randomResult = string.Empty; string readyStr = "0123456789abcdefghijklmnopqrstuvwxyz"; char[] rtn = new char[num]; Guid gid = Guid.NewGuid(); var ba = gid.ToByteArray(); for (var i = 0; i < num; i++) { rtn[i] = readyStr[((ba[i] + ba[num + i]) % 35)]; } var guid = rtn.Aggregate(randomResult, (current, r) => current + r); return(string.Format("{0}{1}-{2}", prefix, DateTime.Now.ToString("yyMMddHHmmssfff"), guid)); }
public void GetArrayLengths(int length, string word) { char[][] arrays = new char[length][]; decimal i = word.Length / (decimal)length; decimal floor = Math.Ceiling(i); for (int j = 0; j < length; j++) { if (j == 0) { arrays[j] = new char[(int)floor]; } else { arrays[j] = new char[(int)i]; } } int aggregate = arrays.Aggregate(0, (b, a) => b + a.Length); Assert.True(aggregate == word.Length); }
static void Main() { char[] separators = new char[] { '-', ',', '.', '!', '?' }; Func <string, string> replacer = x => separators.Aggregate(x, (c1, c2) => c1.Replace(c2, '@')); StreamReader reader = new StreamReader(@"..\..\..\..\Resources\text.txt"); using (reader) { int lineNumber = 0; string line = reader.ReadLine(); while (line != null) { if (lineNumber % 2 == 0) { line = String.Join(" ", line.Split(' ').Reverse()); Console.WriteLine(replacer(line)); } line = reader.ReadLine(); lineNumber++; } } }
/// <summary> /// Appends the specified path and returns the result. /// </summary> /// <param name="basePath">The path to be appended to.</param> /// <param name="relativePath">The path to append.</param> public static string AppendPath(this string basePath, string relativePath) { if (string.IsNullOrEmpty(relativePath)) { return(basePath); } char[] chars = new char[2]; chars[0] = '/'; chars[1] = '\\'; if (string.IsNullOrEmpty(basePath)) { //Match relative path to Device standard relativePath = relativePath.TrimStart(chars); return(chars.Aggregate(relativePath, (current, separator) => current.Replace(separator, Device.DirectorySeparatorChar))); } //Match relative path to base int index = basePath.Contains("/") || Device.DirectorySeparatorChar == '/' ? 0 : 1; return((basePath.TrimEnd(chars) + chars[index] + relativePath.TrimStart(chars)).Replace(chars[1 - index], chars[index])); }
static void Main(string[] args) { var path = Path.Combine("EvenLines", "text.txt"); var dir = Path.Combine("EvenLines", "output.txt"); var charsToReplace = new char[] { '-', ',', '.', '!', '?' }; char charForReplacing = '@'; using (var reader = new StreamReader(path)) { var line = ""; int counter = 0; while ((line = reader.ReadLine()) != null) { if (counter++ % 2 == 0) { var replacedString = charsToReplace .Aggregate(line, (x1, x2) => x1.Replace(x2, charForReplacing)) .Split() .ToList(); replacedString.Reverse(); using (var writer = new StreamWriter(dir, true)) { Console.Write(string.Join(" ", replacedString)); writer.Write(string.Join(" ", replacedString)); Console.WriteLine(); writer.WriteLine(); } } } } }
/// <summary> /// Convert report as excel document /// </summary> /// <returns></returns> /// 2019/07/13, Vinoth N, Initial Version private void DeliveryListGeneration() { string sheetName = ""; string resonForChange = ""; string msg = string.Empty; string location = string.Empty; Excel.Application excelapp = new Excel.Application(); Excel.Workbook workbook = null; this.Dispatcher.Invoke(() => { sheetName = t_POTag.Text ?? "non"; resonForChange = t_Reason.Text ?? ""; location = t_Location.Text; }); if (sheetName.Length < 30) { if (sheetName.Contains("[") || sheetName.Contains("]")) { char[] chars = new char[] { '[', ']', '/', '?', '*' }; sheetName = chars.Aggregate(sheetName, (c1, c2) => c1.Replace(c2, ' ')); sheetName = sheetName.Replace(" ", ""); } try { LogModel.Log("Report Generation Started"); string excelPath = System.Environment.CurrentDirectory.ToString(); if (excelPath.Contains(@"\bin\Debug")) { excelPath = excelPath.Remove((excelPath.Length - (@"\bin\Debug").Length)); } excelapp.Visible = false; workbook = excelapp.Workbooks.Open(excelPath + @"\\App_Data\\KLOC_Template.xls"); PrepareKLOCReport(workbook, sheetName, resonForChange); this.Dispatcher.Invoke(() => { using (System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog() { Filter = "XLS|*.xls|XLSX|*.xlsx", ValidateNames = true, FileName = "PRS Report", InitialDirectory = location }) { if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (Path.GetExtension(sfd.FileName) == ".xlsx") { workbook.SaveAs(sfd.FileName, Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlShared, Excel.XlSaveConflictResolution.xlUserResolution, Type.Missing, Type.Missing); } else { workbook.SaveAs(sfd.FileName); } msg = "Download Completed"; counterStatus.Content = msg; LogModel.Log(msg); } else { msg = "Download Cancelled"; StopGeneration(msg); } } }); } catch (Exception ex) { StopGeneration(ex.Message); LogModel.Log(ex.Message); LogModel.Log(ex.StackTrace); MessageBox.Show("Excel Template Not Found !"); } finally { CloseWorkSheet(excelapp, workbook); LogModel.Log("Report Generation Ended"); } } else { msg = "Excel sheet name length is exceeded: " + sheetName + ". Please change the project name then try..."; StopGeneration(msg); MessageBox.Show(msg); } }
private Searcher ImportCharacterByAngleSharp(string html, Searcher searcher) { var parser = new HtmlParser(); // HtmlParserクラスのParserメソッドを使用してパースする。 // Parserメソッドの戻り値の型はIHtmlDocument var doc = parser.ParseDocument(html); string[] dt; //キャラネームの取得 var name = doc.QuerySelector("h1").TextContent.Trim(); char[] removeChars = new char[] { ' ', ' ' }; string m_buff = removeChars.Aggregate(name, (s, c) => s.Replace(c.ToString(), "")); dt = m_buff.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); searcher.characterInfos.characterName = dt[0]; //キャラ能力値の取得 var status = doc.QuerySelectorAll("tr[id = status_total] td"); var charaStatus = new List <String>(); foreach (var row in status) { var nodes = row.TextContent; if (nodes == null) { continue; } m_buff = removeChars.Aggregate(nodes, (s, c) => s.Replace(c.ToString(), "")); charaStatus.Add(m_buff.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)[0]); } int num; searcher.characterInfos.HP = int.TryParse(charaStatus[8], out num) ? num : 0; searcher.characterInfos.MP = int.TryParse(charaStatus[9], out num) ? num : 0; searcher.characterInfos.SAN = int.TryParse(charaStatus[10], out num) ? num : 0; searcher.abilityValues.STR = int.TryParse(charaStatus[0], out num) ? num : 0; searcher.abilityValues.CON = int.TryParse(charaStatus[1], out num) ? num : 0; searcher.abilityValues.POW = int.TryParse(charaStatus[2], out num) ? num : 0; searcher.abilityValues.DEX = int.TryParse(charaStatus[3], out num) ? num : 0; searcher.abilityValues.APP = int.TryParse(charaStatus[4], out num) ? num : 0; searcher.abilityValues.SIZ = int.TryParse(charaStatus[5], out num) ? num : 0; searcher.abilityValues.INT = int.TryParse(charaStatus[6], out num) ? num : 0; searcher.abilityValues.EDU = int.TryParse(charaStatus[7], out num) ? num : 0; //技能の取得 foreach (var row in doc.QuerySelectorAll("div [id = skill] tr")) { var nodes = row.TextContent; if (nodes == null) { continue; } m_buff = removeChars.Aggregate(nodes, (s, c) => s.Replace(c.ToString(), "")); dt = m_buff.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); try { if (dt[0] == "種別" || dt[1] == "技能名" || dt[2] == "値") { continue; } var value = int.TryParse(dt[2], out var m) ? m : -1; if (value == -1) { continue; } searcher.SetSkill(new Skill(dt[1], value, dt[0])); } catch (Exception exc) { Console.WriteLine(exc.Message); } } return(searcher); }
private static string CleanFileName(string fileName) { var charToIgnore = new char[] { '\"' }; return(charToIgnore.Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty))); }