private CopyTo ( int sourceIndex, char destination, int destinationIndex, int count ) : void | ||
sourceIndex | int | |
destination | char | |
destinationIndex | int | |
count | int | |
return | void |
private void OnSerialize() { if (mJsonText == null) { mJsonText = new System.Text.StringBuilder(); } mJsonText.Clear(); JsonSerializer serializer = new JsonSerializer(); System.IO.StringWriter writer = new System.IO.StringWriter(mJsonText); JsonTextWriter jsonTextWriter = new JsonTextWriter(writer); serializer.Serialize(jsonTextWriter, Data); var charbuffer = System.Buffers.ArrayPool <Char> .Shared.Rent(mJsonText.Length); mJsonText.CopyTo(0, charbuffer, 0, mJsonText.Length); try { var bytes = System.Buffers.ArrayPool <byte> .Shared.Rent(mJsonText.Length * 6); var len = System.Text.Encoding.UTF8.GetBytes(charbuffer, 0, mJsonText.Length, bytes, 0); mJsonData = new ArraySegment <byte>(bytes, 0, len); } finally { System.Buffers.ArrayPool <char> .Shared.Return(charbuffer); } }
internal string GeneratePassword(string userName) { // Create array of 10 letters based on last name, first name var builder = new StringBuilder(); builder.Append(userName); if (builder.Length < 10) { builder.Append("qwertyuiopas"); } var chars = new char[10]; builder.CopyTo(0, chars, 0, 10); builder.Length = 0; // Create 6 digit random number to pick letters var seed = Utility.GetRandom(999999); // Pick letter for each digit for (int i = 0; i < 6; i++) { int digit; seed = Math.DivRem(seed, 10, out digit); builder.Append(chars[digit]); } // Append another 5 digit random number builder.Append(Utility.GetRandom(99999)); return builder.ToString(); }
public static SqlString Substring(this ISqlString source, int offset, int count) { if (source == null || source.IsNull) return SqlString.Null; var en = source.GetEnumerator(); var sb = new StringBuilder(count); int index = -1; while (en.MoveNext()) { if (++index < offset) continue; sb.Append(en.Current); if (index == count - 1) break; } #if PCL var s = sb.ToString(); return new SqlString(s); #else var chars = new char[count]; sb.CopyTo(0, chars, 0, count); return new SqlString(chars); #endif }
public static string Encode(byte[] plaintext) { ContractsCommon.NotNull(plaintext, "plaintext"); ContractsCommon.ResultIsNonNull<string>(); var plaintextArr = new byte[plaintext.Length + 1]; Array.Copy(plaintext, 0, plaintextArr, 1, plaintext.Length); Array.Reverse(plaintextArr); var workingValue = new BigInteger(plaintextArr); StringBuilder sb = new StringBuilder(plaintext.Length * 138 / 100 + 1); while (workingValue.CompareTo(BigInteger.Zero) > 0) { BigInteger remainder; workingValue = BigInteger.DivRem(workingValue, Base, out remainder); sb.Append(Alphabet[(int)remainder]); } Contract.Assert(workingValue.Sign >= 0); //sb.Insert(0, Alphabet[(int)workingValue]); for (int i = 0; i < plaintext.Length && plaintext[i] == 0; ++i) { sb.Append(Alphabet[0]); } var retVal = new char[sb.Length]; sb.CopyTo(0, retVal, 0, sb.Length); Array.Reverse(retVal); return new string(retVal); }
internal bool PrecedesVowel(StringBuilder sb) { if (sb.Length == 0) return false; char c; int start = -1; int end = 0; for (int i = 0; i < sb.Length; i++) { c = sb[i]; if (start == -1) { if (Char.IsWhiteSpace(c) || Char.IsSeparator(c)) continue; // Must be padding, skip it if (!Char.IsLetterOrDigit(c)) continue; start = i; if (i == sb.Length - 1) end = start + 1; // Word is one character long } else { end = i; if (!Char.IsLetterOrDigit(c)) break; if (i == sb.Length - 1) end++; // Consume character if it's the last one in the buffer } } if (start == -1) return false; var buffer = new char[end - start]; sb.CopyTo(start, buffer, 0, end - start); return _rules.Check(new string(buffer)); }
public static StringBuilder AppendBuilder(this StringBuilder sb, StringBuilder append) { var size = append.Length; int pos = 0; var buf = new char[4096]; while (size > 0) { int len = size > 4096 ? 4096 : size; append.CopyTo(pos, buf, 0, len); sb.Append(buf, 0, len); pos += 4096; size -= 4096; } return sb; }
public LexicalAnalizer(string solutionFile) { StringBuilder data = new StringBuilder(); using (StreamReader reader = new StreamReader(solutionFile)) { data.Append(reader.ReadToEnd()); } if (data.Length > 0) { data.Append("\n"); data = data.Replace("\r", ""); // remove the /r, for easy parsing char[] arr = new char[data.Length]; data.CopyTo(0, arr, 0, data.Length); tokenData = Tokenize(arr); } }
static int ReplaceEntity(StringBuilder sb, int i) { int start = i; while (++i < sb.Length && sb[i] != ';') ; if (i == sb.Length) throw new ArgumentException("Could not find closing ';' for '&' at position " + start + "."); int length = i - start + 1; char[] chars = new char[length]; sb.CopyTo(start, chars, 0, length); if (chars[1] != '#') // ignore numeric entities { var entity = new string(chars); string numericCode; if (entityMap.TryGetValue(entity, out numericCode)) { sb.Remove(start, length); sb.Insert(start, numericCode); } } return i; }
static public int CopyTo(IntPtr l) { try { System.Text.StringBuilder self = (System.Text.StringBuilder)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); System.Char[] a2; checkArray(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); System.Int32 a4; checkType(l, 5, out a4); self.CopyTo(a1, a2, a3, a4); pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
private void button2_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(richTextBox1.TextLength); sb.Append(richTextBox1.Text); richTextBox1.Text = ""; int idx = 0; int amount = Math.Min((int)numericUpDown1.Value, sb.Length); char[] ar = new char[(int)numericUpDown1.Value]; while (sb.Length >= (idx + amount)) { sb.CopyTo(idx, ar, 0, amount); richTextBox1.AppendText(new string(ar) + "\n"); Array.Clear(ar, 0, ar.Length); idx = idx + amount; if (sb.Length > idx) { amount = Math.Min((int)numericUpDown1.Value, sb.Length - idx); } } }
private void appendStb(string str) { lock (stb) { if (lineCount >= 100) { char[] cbuf = new char[1]; for (var i = 0; i < stb.Length; i++) { stb.CopyTo(i, cbuf, 0, 1); if (cbuf[0] == '\n') { stb.Remove(0, i + 1); break; } } lineCount--; } stb.AppendLine(str); lineCount++; } }
public static void CopyTo(string value, int sourceIndex, char[] destination, int destinationIndex, int count, char[] expected) { var builder = new StringBuilder(value); builder.CopyTo(sourceIndex, destination, destinationIndex, count); Assert.Equal(expected, destination); }
public unsafe Task<string[]> ShowFileDialogAsync(FileDialog dialog, IWindowImpl parent) { var hWnd = parent?.Handle?.Handle ?? IntPtr.Zero; return Task.Factory.StartNew(() => { var filters = new StringBuilder(); foreach (var filter in dialog.Filters) { var extMask = string.Join(";", filter.Extensions.Select(e => "*." + e)); filters.Append(filter.Name); filters.Append(" ("); filters.Append(extMask); filters.Append(")"); filters.Append('\0'); filters.Append(extMask); filters.Append('\0'); } if (filters.Length == 0) filters.Append("All files\0*.*\0"); filters.Append('\0'); var filterBuffer = new char[filters.Length]; filters.CopyTo(0, filterBuffer, 0, filterBuffer.Length); var defExt = (dialog as SaveFileDialog)?.DefaultExtension; var fileBuffer = new char[256]; dialog.InitialFileName?.CopyTo(0, fileBuffer, 0, dialog.InitialFileName.Length); string userSelectedExt = null; fixed (char* pFileBuffer = fileBuffer) fixed (char* pFilterBuffer = filterBuffer) fixed (char* pDefExt = defExt) fixed (char* pInitDir = dialog.InitialDirectory) fixed (char* pTitle = dialog.Title) { var ofn = new UnmanagedMethods.OpenFileName() { hwndOwner = hWnd, hInstance = IntPtr.Zero, lCustData = IntPtr.Zero, nFilterIndex = 0, Flags = UnmanagedMethods.OpenFileNameFlags.OFN_EXPLORER | UnmanagedMethods.OpenFileNameFlags.OFN_HIDEREADONLY, nMaxCustFilter = 0, nMaxFile = fileBuffer.Length - 1, nMaxFileTitle = 0, lpTemplateName = IntPtr.Zero, lpfnHook = IntPtr.Zero, lpstrCustomFilter = IntPtr.Zero, lpstrDefExt = new IntPtr(pDefExt), lpstrFile = new IntPtr(pFileBuffer), lpstrFileTitle = IntPtr.Zero, lpstrFilter = new IntPtr(pFilterBuffer), lpstrInitialDir = new IntPtr(pInitDir), lpstrTitle = new IntPtr(pTitle), }; ofn.lStructSize = Marshal.SizeOf(ofn); if ((dialog as OpenFileDialog)?.AllowMultiple == true) ofn.Flags |= UnmanagedMethods.OpenFileNameFlags.OFN_ALLOWMULTISELECT; if (dialog is SaveFileDialog) ofn.Flags |= UnmanagedMethods.OpenFileNameFlags.OFN_NOREADONLYRETURN | UnmanagedMethods.OpenFileNameFlags.OFN_OVERWRITEPROMPT; var pofn = &ofn; var res = dialog is OpenFileDialog ? UnmanagedMethods.GetOpenFileName(new IntPtr(pofn)) : UnmanagedMethods.GetSaveFileName(new IntPtr(pofn)); if (!res) return null; if (dialog?.Filters.Count > 0) userSelectedExt = dialog.Filters[ofn.nFilterIndex - 1].Extensions.FirstOrDefault(); } var cStart = 0; string dir = null; var files = new List<string>(); for (var c = 0; c < fileBuffer.Length; c++) { if (fileBuffer[c] == 0) { //Encountered double zero char if (cStart == c) break; var s = new string(fileBuffer, cStart, c - cStart); if (dir == null) dir = s; else files.Add(s); cStart = c + 1; } } if (files.Count == 0) { if (dialog is SaveFileDialog) { if (string.IsNullOrWhiteSpace(Path.GetExtension(dir)) && !string.IsNullOrWhiteSpace(userSelectedExt) && !userSelectedExt.Contains("*")) dir = Path.ChangeExtension(dir, userSelectedExt); } return new[] {dir}; } return files.Select(f => Path.Combine(dir, f)).ToArray(); }); }
public IEnumerable<string> GetAttributeValue(string data, string template, string attributeName) { template = ClearContent(template); var templateParts = template.ToLower().Split('*'); var content = new StringBuilder(data.ToLower()); ClearContent(content); template = ClearContent(template); int startPos = content.Contains(templateParts[0]); if (startPos == -1) yield return string.Empty; int endPos = content.Contains(templateParts[1], startPos + templateParts[0].Length - 1); if (startPos != -1 && endPos != -1) { content.Remove(0, startPos); startPos = content.Contains(templateParts[0]); endPos = content.Contains(templateParts[1], startPos + templateParts[0].Length - 1); if (startPos != -1 && endPos != -1) { content.Remove(endPos + templateParts[1].Length, content.Length - (endPos + templateParts[1].Length)); } } while (startPos != -1 && endPos != -1) { startPos = content.Contains(attributeName, startPos); if (startPos == -1) yield return string.Empty;//return result; endPos = content.Contains(">", startPos); if (endPos == -1) yield return string.Empty; //return result; char[] destination = new char[endPos - (startPos + attributeName.Length)]; content.CopyTo(startPos + attributeName.Length, destination, 0, endPos - (startPos + attributeName.Length)); int breakPos = -1; for (int i = 0; i < destination.Length; i++) if (destination[i] == ' ') { breakPos = i; break; } if (breakPos > -1) { Array.Resize<char>(ref destination, breakPos); } string link = new string(destination); //if (!link.StartsWith("host")) // link = host + '/' + link; //link = link.Replace("/./", "/"); //result.Add(link); startPos = content.Contains(attributeName, endPos); endPos = content.Contains(">", startPos + attributeName.Length - 1); yield return RemoveTags(link); } yield return string.Empty;//return result; }
/// <summary> /// Creates the index for the bz2 file on a separate thread. /// </summary> internal void DecodeAsync() { bool failed = false; startTime = DateTime.Now; try { InitializeAction(); // Locate the bzip2 blocks in the file Counter.Start("LocateBlock"); LocateBlocks(); Counter.Stop("LocateBlock"); // Two times more than the first block but not less than 100 bytes long bufSize = ((ends[0] - beginnings[0]) / 8) * 2 + 100; // Buffers for the current and next block blockBuf = new byte[bufSize]; charBuf = new char[bufSize]; // Whether there was a Wiki topic carryover from current block to the next one char[] charCarryOver = new char[0]; // The length of the currently loaded data long loadedLength = 0; StringBuilder sb = new StringBuilder(); // Starting indexing startTime = DateTime.Now; elapsed = new TimeSpan(0); ReportProgress(0, DecodingProgress.State.Running, Properties.Resources.ProgressIndexing); for (long i = 0; i < totalBlocks && !abortDecoding; i++) { ReportProgress((int)((double)(i * 100) / (double)totalBlocks), DecodingProgress.State.Running, String.Empty); #region Load-Decode-HandleDecodedData Counter.Start("LoadBlock"); loadedLength = LoadBlock(beginnings[i], ends[i], ref blockBuf); if (charBuf.Length < blockBuf.Length) { charBuf = new char[blockBuf.Length]; } int bytesUsed = 0; int charsUsed = 0; bool completed = false; // Convert the text to UTF8 utf8.Convert(blockBuf, 0, (int)loadedLength, charBuf, 0, charBuf.Length, i == totalBlocks - 1, out bytesUsed, out charsUsed, out completed); if (!completed) { throw new Exception(Properties.Resources.UTFDecoderError); } // Construct a current string sb.Length = 0; if (charCarryOver.Length > 0) { sb.Append(charCarryOver); } sb.Append(charBuf, 0, charsUsed); int carryOverLength = charCarryOver.Length; Counter.Stop("LoadBlock"); int charsMatched = HandleDecodedData(sb.ToString(), beginnings[i], ends[i], carryOverLength, i == totalBlocks - 1); // There's a Wiki topic carryover, let's store the characters which need to be carried over if (charsMatched > 0) { charCarryOver = new char[charsMatched]; sb.CopyTo(charsUsed + carryOverLength - charsMatched, charCarryOver, 0, charsMatched); } else { charCarryOver = new char[0]; } // this is not exact place to handle, but least side effect for measurement and mostly correct. if (EnableAutoLogging) { AutoLogging(); } #endregion } // Wait till all the threads finish WaitTillFinish(); PostAction(); Split(); } /* catch (Exception ex) { ReportProgress(0, DecodingProgress.State.Failure, ex.ToString()); failed = true; } * */ finally { } // Try to release some memory FinalizeAction(failed); ReportProgress(0, DecodingProgress.State.Finished, String.Empty); }
/* ** Name: save_text ** ** Description: ** Copies text from a string buffer into the SQL text character array. ** Array is expanded if necessary. String buffer is emptied. ** ** Input: ** buff String buffer. ** ** Output: ** None. ** ** Returns: ** void ** ** History: ** 20-Aug-01 (gordy) ** Created. */ private void save_text( StringBuilder buff ) { /* ** Expand text array if needed. */ if ( buff.Length > text.Length ) text = new char[ buff.Length ]; txt_len = buff.Length; // buff.getChars( 0, txt_len, text, 0 ); buff.CopyTo(0, text, 0, txt_len); buff.Length = 0; return; }
private static DateTime DeserializeDate (ref StringBuilder input) { var inChars = new char[11]; input.CopyTo (0, inChars, 0, inChars.Length); DateTime result; if (!DateTime.TryParseExact (new string (inChars), "MM:dd:yyyy;", CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) throw new SerializationException (); input.Remove (0, inChars.Length); return result; }
private int GetInputBuffer(StringBuilder content, bool isUnc, out char[] buffer) { int length = content.Length; length += isUnc ? PathInternal.UncExtendedPrefixToInsert.Length : PathInternal.ExtendedPathPrefix.Length; buffer = new char[length]; if (isUnc) { PathInternal.UncExtendedPathPrefix.CopyTo(0, buffer, 0, PathInternal.UncExtendedPathPrefix.Length); int prefixDifference = PathInternal.UncExtendedPathPrefix.Length - PathInternal.UncPathPrefix.Length; content.CopyTo(prefixDifference, buffer, PathInternal.ExtendedPathPrefix.Length, content.Length - prefixDifference); return prefixDifference; } else { int prefixSize = PathInternal.ExtendedPathPrefix.Length; PathInternal.ExtendedPathPrefix.CopyTo(0, buffer, 0, prefixSize); content.CopyTo(0, buffer, prefixSize, content.Length); return prefixSize; } }
void WriteStringBuilder(StringBuilder sb) { if (m_tmpWrite.Length < sb.Length) { Array.Resize(ref m_tmpWrite, Math.Max(m_tmpWrite.Length * 2, sb.Length)); } sb.CopyTo(0, m_tmpWrite, 0, sb.Length); m_streamWriter.Write(m_tmpWrite, 0, sb.Length); }
public void Write(StringBuilder sb, int index, int count, TextTokenKind tokenKind) { WriteIndent(); if (count == 1) writer.Write(sb[index]); else { int left = count; while (left > 0) { int len = Math.Min(outputBuffer.Length, left); sb.CopyTo(index, outputBuffer, 0, len); writer.Write(outputBuffer, 0, len); left -= len; } } column += count; }
public void Problem13() { var input = @" 37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676 89261670696623633820136378418383684178734361726757 28112879812849979408065481931592621691275889832738 44274228917432520321923589422876796487670272189318 47451445736001306439091167216856844588711603153276 70386486105843025439939619828917593665686757934951 62176457141856560629502157223196586755079324193331 64906352462741904929101432445813822663347944758178 92575867718337217661963751590579239728245598838407 58203565325359399008402633568948830189458628227828 80181199384826282014278194139940567587151170094390 35398664372827112653829987240784473053190104293586 86515506006295864861532075273371959191420517255829 71693888707715466499115593487603532921714970056938 54370070576826684624621495650076471787294438377604 53282654108756828443191190634694037855217779295145 36123272525000296071075082563815656710885258350721 45876576172410976447339110607218265236877223636045 17423706905851860660448207621209813287860733969412 81142660418086830619328460811191061556940512689692 51934325451728388641918047049293215058642563049483 62467221648435076201727918039944693004732956340691 15732444386908125794514089057706229429197107928209 55037687525678773091862540744969844508330393682126 18336384825330154686196124348767681297534375946515 80386287592878490201521685554828717201219257766954 78182833757993103614740356856449095527097864797581 16726320100436897842553539920931837441497806860984 48403098129077791799088218795327364475675590848030 87086987551392711854517078544161852424320693150332 59959406895756536782107074926966537676326235447210 69793950679652694742597709739166693763042633987085 41052684708299085211399427365734116182760315001271 65378607361501080857009149939512557028198746004375 35829035317434717326932123578154982629742552737307 94953759765105305946966067683156574377167401875275 88902802571733229619176668713819931811048770190271 25267680276078003013678680992525463401061632866526 36270218540497705585629946580636237993140746255962 24074486908231174977792365466257246923322810917141 91430288197103288597806669760892938638285025333403 34413065578016127815921815005561868836468420090470 23053081172816430487623791969842487255036638784583 11487696932154902810424020138335124462181441773470 63783299490636259666498587618221225225512486764533 67720186971698544312419572409913959008952310058822 95548255300263520781532296796249481641953868218774 76085327132285723110424803456124867697064507995236 37774242535411291684276865538926205024910326572967 23701913275725675285653248258265463092207058596522 29798860272258331913126375147341994889534765745501 18495701454879288984856827726077713721403798879715 38298203783031473527721580348144513491373226651381 34829543829199918180278916522431027392251122869539 40957953066405232632538044100059654939159879593635 29746152185502371307642255121183693803580388584903 41698116222072977186158236678424689157993532961922 62467957194401269043877107275048102390895523597457 23189706772547915061505504953922979530901129967519 86188088225875314529584099251203829009407770775672 11306739708304724483816533873502340845647058077308 82959174767140363198008187129011875491310547126581 97623331044818386269515456334926366572897563400500 42846280183517070527831839425882145521227251250327 55121603546981200581762165212827652751691296897789 32238195734329339946437501907836945765883352399886 75506164965184775180738168837861091527357929701337 62177842752192623401942399639168044983993173312731 32924185707147349566916674687634660915035914677504 99518671430235219628894890102423325116913619626622 73267460800591547471830798392868535206946944540724 76841822524674417161514036427982273348055556214818 97142617910342598647204516893989422179826088076852 87783646182799346313767754307809363333018982642090 10848802521674670883215120185883543223812876952786 71329612474782464538636993009049310363619763878039 62184073572399794223406235393808339651327408011116 66627891981488087797941876876144230030984490851411 60661826293682836764744779239180335110989069790714 85786944089552990653640447425576083659976645795096 66024396409905389607120198219976047599490197230297 64913982680032973156037120041377903785566085089252 16730939319872750275468906903707539413042652315011 94809377245048795150954100921645863754710598436791 78639167021187492431995700641917969777599028300699 15368713711936614952811305876380278410754449733078 40789923115535562561142322423255033685442488917353 44889911501440648020369068063960672322193204149535 41503128880339536053299340368006977710650566631954 81234880673210146739058568557934581403627822703280 82616570773948327592232845941706525094512325230608 22918802058777319719839450180888072429661980811197 77158542502016545090413245809786882778948721859617 72107838435069186155435662884062257473692284509516 20849603980134001723930671666823555245252804609722 53503534226472524250874054075591789781264330331690 "; var lines = input.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); var inputGrid = new List<IEnumerable<int>>(); foreach (var line in lines) { inputGrid.Add( (from c in line select int.Parse(c.ToString())).ToList() ); } Assert.IsTrue(inputGrid.Count == 100, "Wrong Input"); var carry = 0; //inputGrid = new List<IEnumerable<int>>(); //inputGrid.Add(new int[] { 9, 9, 9, 9 }); //inputGrid.Add(new int[] { 1, 1, 1, 1 }); //inputGrid.Add(new int[] { 2, 2, 2, 2 }); // add by 2 rows at a time // using Zip var lastRow = inputGrid[0] as IEnumerable<int>; inputGrid.RemoveAt(0); while (inputGrid.Count() > 0) { // zip is combining two sequence into one using predicate var reverseLastRow = lastRow.Reverse<int>().ToArray(); var reverseCurrentRow = inputGrid[0].ToList(); if (inputGrid[0].Count() < reverseLastRow.Count()) { reverseCurrentRow.Insert(0, 0); } reverseCurrentRow.Reverse(); var resultOfTwoRows = reverseLastRow.Zip(reverseCurrentRow, (last, current) => { // adder var sum = last + current + carry; var digit = sum % 10; if (sum >= 10) { carry = 1; } else { carry = 0; } return digit; }).ToArray(); if (carry == 0) { var added = resultOfTwoRows.Reverse<int>().ToArray(); lastRow = added; } else { var added = (new int[] { carry }).Concat(resultOfTwoRows.Reverse<int>()).ToArray(); lastRow = added; } inputGrid.RemoveAt(0); } StringBuilder sb = new StringBuilder(); if (carry != 0) { sb.Append(carry); } foreach (var item in lastRow) { sb.Append(item); } char[] result = new char[10]; sb.CopyTo(0, result, 0, Math.Min(10, sb.Length)); var final = string.Join("", result); Assert.IsTrue(final == "5537376230", "Wrong Answer"); /* you cannot add like this? maybe carrying does not defined for large numbers Func<int, IEnumerable<int>> allNumberOfColumn = (c) => { return from r in 0.To( inputGrid.Count - 1 ) select inputGrid[r][c]; }; Func<int> getCarry = () => { return carry; }; Func<int,int> setCarry = (v) => { carry = v; return carry; }; var resultForColumns = from c in 49.To(0) // start from back let sum = allNumberOfColumn(c).Sum() let sumWithCarry = sum + getCarry() let digit = sumWithCarry % 10 // we need only last digit, the rest is carry let toCarry = setCarry(sumWithCarry - digit) select new { ColumnDigit = digit, Actual = sum, CarryAfter = toCarry, SumWithCarry = sumWithCarry, Numbers = allNumberOfColumn(c).ToArray() }; // answer for the column var columns = resultForColumns.ToList(); Assert.IsTrue(columns[0].Actual == 422, "Wrong number since first column"); Assert.IsTrue(columns[0].CarryAfter == 420, "Wrong carry since first column"); Assert.IsTrue(columns[0].ColumnDigit == 2, "Wrong result since first column"); columns.Reverse(); StringBuilder sb = new StringBuilder(); sb.Append(columns[0].CarryAfter); foreach (var item in columns) { sb.Append(item.ColumnDigit); } char[] result = new char[10]; sb.CopyTo(0, result, 0, 10); var final = string.Join("", result); * */ }
public void Read() { lock (m_lockObject) { lock (m_fileLock) { Monitor.PulseAll(m_fileLock); } Comment comment = null; StreamReader input = null; try { if (File.Exists(FILE_NAME)) { input = new StreamReader(FILE_NAME); EndOfStreamException.Reader reader = new EndOfStreamException.Reader(input); while (true) { char value = reader.ReadWithoutWhitespace(); StringBuilder buffer; if (value == '\n' || value == ';') { if (comment == null) { comment = new Comment(); } if (value == '\n') { comment.AddBytes(NEW_LINE); } else { buffer = new StringBuilder(30); for (; value != '\n'; value = reader.Read()) { buffer.Append(value); } buffer.Append('\n'); char[] data = new char[buffer.Length]; buffer.CopyTo(0, data, 0, buffer.Length); comment.AddBytes(data); } } else if (value == '[') { while (reader.Read() != ']') { } while (reader.Read() != '\n') { } } else { buffer = new StringBuilder(30); for (; value != '='; value = reader.ReadWithoutWhitespace()) { buffer.Append(value); } string name = buffer.ToString(); buffer = new StringBuilder(30); bool shouldBreak = false; value = reader.ReadWithoutWhitespace(); if (value == '"') { for (value = reader.Read(); value != '"'; value = reader.Read()) { buffer.Append(value); } while (reader.Read() != '\n') { } } else { try { for (; value != '\n'; value = reader.ReadWithoutWhitespace()) { buffer.Append(value); } } catch (EndOfStreamException) { shouldBreak = true; } } string result = buffer.ToString(); m_keys.Add(name); m_values.Add(name, result); NetworkTable.GetTable(TABLE_NAME).PutString(name, result); if (comment != null) { if (m_comments == null) { m_comments = new Dictionary<string, Comment>(); } m_comments.Add(name, comment); comment = null; } if (shouldBreak) { break; } } } } } catch (IOException ex) { Console.WriteLine(ex); } catch (EndOfStreamException) { Console.WriteLine("Done Reading"); } if (input != null) { try { input.Close(); } catch(IOException) { } } if (comment != null) { m_endComment = comment; } } NetworkTable.GetTable(TABLE_NAME).PutBoolean(SAVE_FIELD, false); NetworkTable.GetTable(TABLE_NAME).AddTableListener(this);//Figure this out }
private void LoadPasswordValue(StringBuilder password) { var pwd = new char[password.Length]; var securePassword = new SecureString(); try { password.CopyTo(0, pwd, 0, pwd.Length); foreach (var c in pwd) { securePassword.AppendChar(c); } securePassword.MakeReadOnly(); Password = securePassword.Copy(); } finally { // discard the char array Array.Clear(pwd, 0, pwd.Length); } }
private char[] layout(int form) { char[] cmant; int i=0; int ix=0; StringBuilder sb=null; int euse=0; int sig=0; char csign=(char)0; char[] rec=null; int needsign; int mag; int len=0; cmant=new char[mant.Length]; // copy sbyte[] to a char[] for(ix=mant.Length,i=0;ix>0;ix--,i++){ cmant[i]=(char)(mant[i]+((int)('0'))); } if (form!=MathContext.PLAIN) {/* exponential notation needed */ sb=new StringBuilder(cmant.Length+15); // -x.xxxE+999999999 if (ind==isneg) sb.Append('-'); euse=(exp+cmant.Length)-1; // exponent to use /* setup sig=significant digits and copy to result */ if (form==MathContext.SCIENTIFIC) { // [default] sb.Append(cmant[0]); // significant character if (cmant.Length>1) // have decimal part sb.Append('.').Append(cmant,1,cmant.Length-1); } else {do{ sig=euse%3; // common if (sig<0) sig=3+sig; // negative exponent euse=euse-sig; sig++; if (sig>=cmant.Length) { // zero padding may be needed sb.Append(cmant,0,cmant.Length); for(ix=sig-cmant.Length;ix>0;ix--){ sb.Append('0'); } } else { // decimal point needed sb.Append(cmant,0,sig).Append('.').Append(cmant,sig,cmant.Length-sig); } }while(false);}/*engineering*/ if (euse!=0) { if (euse<0) { csign='-'; euse=(int)-euse; } else csign='+'; sb.Append('E').Append(csign).Append(euse); } rec=new char[sb.Length]; sb.CopyTo(0, rec, 0, sb.Length); return rec; } /* Here for non-exponential (plain) notation */ if (exp==0) {/* easy */ if (ind>=0) return cmant; // non-negative integer rec=new char[cmant.Length+1]; rec[0]='-'; System.Array.Copy(cmant,0,rec,1,cmant.Length); return rec; } /* Need a '.' and/or some zeros */ needsign=(int)((ind==isneg)?1:0); // space for sign? 0 or 1 /* MAG is the position of the point in the mantissa (index of the character it follows) */ mag=exp+cmant.Length; if (mag<1) {/* 0.00xxxx form */ len=(needsign+2)-exp; // needsign+2+(-mag)+cmant.Length rec=new char[len]; if (needsign!=0) rec[0]='-'; rec[needsign]='0'; rec[needsign+1]='.'; for(ix=(int)-mag,i=needsign+2;ix>0;ix--,i++){ // maybe none rec[i]='0'; } System.Array.Copy(cmant,0,rec,(needsign+2)-mag,cmant.Length); return rec; } if (mag>cmant.Length) {/* xxxx0000 form */ len=needsign+mag+2; rec=new char[len]; if (needsign!=0) rec[0]='-'; rec[needsign+mag] = '.'; rec[needsign+mag+1] = '0'; System.Array.Copy(cmant,0,rec,needsign,cmant.Length); for(ix=mag-cmant.Length,i=needsign+cmant.Length;ix>0;ix--,i++){ // never 0 rec[i]='0'; } return rec; } /* decimal point is in the middle of the mantissa */ len=(needsign+1)+cmant.Length; rec=new char[len]; if (needsign!=0) rec[0]='-'; System.Array.Copy(cmant,0,rec,needsign,mag); rec[needsign+mag]='.'; System.Array.Copy(cmant,mag,rec,(needsign+mag)+1,cmant.Length-mag); return rec; }
private bool CheckForEndOfData(StringBuilder sb) { if (sb.Length < 5) return false; char[] compare = new char[5]; sb.CopyTo(sb.Length - 5, compare, 0, 5); return (endMarker as IStructuralEquatable).Equals(compare, EqualityComparer<char>.Default); }
public static void CopyTo_Invalid() { var builder = new StringBuilder("Hello"); Assert.Throws<ArgumentNullException>("destination", () => builder.CopyTo(0, null, 0, 0)); // Destination is null Assert.Throws<ArgumentOutOfRangeException>("sourceIndex", () => builder.CopyTo(-1, new char[10], 0, 0)); // Source index < 0 Assert.Throws<ArgumentOutOfRangeException>("sourceIndex", () => builder.CopyTo(6, new char[10], 0, 0)); // Source index > builder.Length Assert.Throws<ArgumentOutOfRangeException>("destinationIndex", () => builder.CopyTo(0, new char[10], -1, 0)); // Destination index < 0 Assert.Throws<ArgumentOutOfRangeException>("count", () => builder.CopyTo(0, new char[10], 0, -1)); // Count < 0 Assert.Throws<ArgumentException>(null, () => builder.CopyTo(5, new char[10], 0, 1)); // Source index + count > builder.Length Assert.Throws<ArgumentException>(null, () => builder.CopyTo(4, new char[10], 0, 2)); // Source index + count > builder.Length Assert.Throws<ArgumentException>(null, () => builder.CopyTo(0, new char[10], 10, 1)); // Destination index + count > destinationArray.Length Assert.Throws<ArgumentException>(null, () => builder.CopyTo(0, new char[10], 9, 2)); // Destination index + count > destinationArray.Length }
public string GetSingleContent(string data, string template) { var templateParts = template.ToLower().Split('*'); if (templateParts != null && templateParts.Length == 2) { templateParts[0] = ClearContent(templateParts[0]); templateParts[1] = ClearContent(templateParts[1]); } var content = new StringBuilder(data.ToLower()); ClearContent(content); int startPos = content.Contains(templateParts[0]); if (startPos == -1) return string.Empty; int endPos = content.Contains(templateParts[1], startPos + templateParts[0].Length ); if (startPos != -1 && endPos != -1) { char[] destination = new char[endPos - startPos + templateParts[0].Length]; content.CopyTo(startPos + templateParts[0].Length, destination, 0, endPos - (startPos + templateParts[0].Length)); string result = new string(destination); content = null; return result;//RemoveTags(result).Trim(); } content = null; return string.Empty;//return result; }
public static String GetCanonicalPath(String path) { String currentDirectory = Directory.GetCurrentDirectory(); StringBuilder path_ = new StringBuilder(); if ((path[0] == '/' || path[0] == '\\') && (path[1] == '/' || path[1] == '\\')) { path_.Append(path); } else if ((path[0] == '/' || path[0] == '\\')) { path_.Append(currentDirectory.Substring(0, 2)).Append(path); } else if ((path[0] >= 'a' && path[0] <= 'z' || path[0] >= 'A' && path[0] <= 'Z') && path[1] == ':') { path_.Append(path); } else { path_.Append(currentDirectory).Append('\\').Append(path); } char[] buf = new char[path_.Length + 3]; path_.CopyTo(0, buf, 0, path_.Length); int cursor = 0; int parentIdx = 0; for (int i = 0; i < buf.Length - 3; ) { if (buf[i] == '/') buf[i] = '\\'; if ((i + 2) < buf.Length && buf[i] == '\\' && buf[i + 1] == '.' && (buf[i + 2] == '\\' || buf[i + 2] == '/')) { i = i + 2; } else if ((i + 3) < buf.Length && buf[i] == '\\' && buf[i + 1] == '.' && buf[i + 2] == '.' && (buf[i + 3] == '\\' || buf[i + 3] == '/')) { cursor = parentIdx; i += 4; } else if (buf[i] == '\\') { buf[cursor++] = buf[i++]; parentIdx = cursor; } else { buf[cursor++] = buf[i++]; } } if (buf[cursor - 1] == '\\') return new String(buf, 0, cursor - 1); else return new String(buf, 0, cursor); }
/// <summary> /// Creates the index for the bz2 file on a separate thread. /// </summary> private void CreateIndexAsync() { bool failed = false; try { // Close any searchers if (searcher != null) { searcher.Close(); searcher = null; } indexExists = false; // Create the index writer indexer = new IndexWriter(indexPath, textAnalyzer, true); memoryIndexer = new IndexWriter(new RAMDirectory(), textAnalyzer, true); memoryIndexer.SetMaxBufferedDocs(1000); memoryIndexer.SetMergeFactor(100); indexer.SetMaxBufferedDocs(1000); indexer.SetMergeFactor(100); // Locate the bzip2 blocks in the file LocateBlocks(); // Two times more than the first block but not less than 100 bytes long bufSize = ((ends[0] - beginnings[0]) / 8) * 2 + 100; // Buffers for the current and next block blockBuf = new byte[bufSize]; charBuf = new char[bufSize]; // Whether there was a Wiki topic carryover from current block to the next one char[] charCarryOver = new char[0]; // The length of the currently loaded data long loadedLength = 0; StringBuilder sb = new StringBuilder(); // Starting indexing ReportProgress(0, IndexingProgress.State.Running, "Indexing"); for (long i = 0; i < totalBlocks && !abortIndexing; i++) { ReportProgress((int)((double)(i * 100) / (double)totalBlocks), IndexingProgress.State.Running, String.Empty); #region Indexing logic loadedLength = LoadBlock(beginnings[i], ends[i], ref blockBuf); if (charBuf.Length < blockBuf.Length) { charBuf = new char[blockBuf.Length]; } int bytesUsed = 0; int charsUsed = 0; bool completed = false; // Convert the text to UTF8 utf8.Convert(blockBuf, 0, (int)loadedLength, charBuf, 0, charBuf.Length, i == totalBlocks - 1, out bytesUsed, out charsUsed, out completed); if (!completed) { throw new Exception("UTF8 decoder could not complete the conversion"); } // Construct a current string sb.Length = 0; if (charCarryOver.Length > 0) { sb.Append(charCarryOver); } sb.Append(charBuf, 0, charsUsed); int carryOverLength = charCarryOver.Length; int charsMatched = IndexString(sb.ToString(), beginnings[i], ends[i], carryOverLength, i == totalBlocks - 1); // There's a Wiki topic carryover, let's store the characters which need to be carried over if (charsMatched > 0) { charCarryOver = new char[charsMatched]; sb.CopyTo(charsUsed + carryOverLength - charsMatched, charCarryOver, 0, charsMatched); } else { charCarryOver = new char[0]; } #endregion } // Wait till all the threads finish while (activeThreads != 0) { ReportProgress(0, IndexingProgress.State.Running, "Waiting for tokenizer threads to finish"); Thread.Sleep(TimeSpan.FromSeconds(5)); } ReportProgress(0, IndexingProgress.State.Running, "Flushing documents to disk"); Lucene.Net.Store.Directory dir = memoryIndexer.GetDirectory(); memoryIndexer.Close(); indexer.AddIndexes(new Lucene.Net.Store.Directory[] { dir }); memoryIndexer = null; ReportProgress(0, IndexingProgress.State.Running, "Optimizing index"); indexer.Optimize(); indexExists = true; } catch (Exception ex) { ReportProgress(0, IndexingProgress.State.Failure, ex.ToString()); failed = true; } // Try to release some memory if (indexer != null) { indexer.Close(); indexer = null; } if (failed || abortIndexing) { Directory.Delete(indexPath, true); indexExists = false; } else { if (indexExists) { searcher = new IndexSearcher(indexPath); } } ReportProgress(0, IndexingProgress.State.Finished, String.Empty); }
private static DateTime DeserializeTime (ref StringBuilder input) { if (input [8] == ';') { // Without milliseconds var inChars = new char[9]; input.CopyTo (0, inChars, 0, inChars.Length); DateTime result; if (!DateTime.TryParseExact (new string (inChars), "HH:mm:ss;", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out result)) throw new SerializationException (); input.Remove (0, inChars.Length); return result; } else if (input [12] == ';') { // With milliseconds char[] inChars = new char[13]; input.CopyTo (0, inChars, 0, inChars.Length); var inString = new string (inChars); DateTime result; if (!DateTime.TryParseExact (inString, "HH:mm:ss.fff;", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out result)) throw new SerializationException (); input.Remove (0, inChars.Length); return result; } throw new SerializationException (); }
protected static char[] CopyFromStringBuiler(StringBuilder stBuilder, int start, int len) { char[] copyBuff = new char[len]; stBuilder.CopyTo(start, copyBuff, 0, len); return copyBuff; }
/// <summary> /// retrieves the first value of the comma separated list, and removes the value from the list. /// This version of GetNextCSV is quite optimized, but less flexible than the other version. /// only supports single character separators, and works only with the specified separator /// </summary> /// <param name="list">the comma separated list that will get the first value removed</param> /// <param name="separator">the delimiter/separator of the list</param> /// <param name="ARemoveLeadingAndTrailingSpaces">if this is true, leading and trailing spaces will be discarded (useful for file imports)</param> /// <returns>the first value of the list</returns> public static string GetNextCSV(ref StringBuilder list, char separator, Boolean ARemoveLeadingAndTrailingSpaces = false) { if (list.Length == 0) { return ""; } int position = 0; bool escape = false; bool isFinalisedQuotedText = false; StringBuilder value = new StringBuilder(); if (list[0] != separator) { while (position < list.Length) { if (escape) { escape = false; } else { if (list[position] == '\\') { escape = true; position++; } } if ((list[position] == ' ') && (separator != ' ') && (value.Length == 0) && ARemoveLeadingAndTrailingSpaces) { // leading spaces are ignored position++; } else if (list[position] == '"') { // TODO: no substring??? try { char[] quotedstring = new char[FindMatchingQuote(list, position) - position]; list.CopyTo(position + 1, quotedstring, 0, quotedstring.Length); if (value.Length == 0) { value.Append(quotedstring); } else { value.Append("\"").Append(quotedstring).Append("\""); } position += quotedstring.Length + 2; } catch (IndexOutOfRangeException) { // Problem with matching quotes... if (value.Length == 0) { value.Append(CSV_STRING_FORMAT_ERROR); } else { value.Append("\"").Append(CSV_STRING_FORMAT_ERROR).Append("\""); } position = list.Length; } // If we are not to add trailing spaces we set isFinalisedQuotedText = true if (ARemoveLeadingAndTrailingSpaces) { isFinalisedQuotedText = true; } } else { if (!isFinalisedQuotedText) { // Do not append anything (eg trailing spaces) to already finalised quoted text value.Append(list[position]); } position++; } if (!escape && (position < list.Length) && (list[position] == separator)) { // found the next separator break; } } } value.Replace("\"\"", "\""); if (position == list.Length) { list.Remove(0, list.Length); } else { list.Remove(0, position + 1); // there still was a separator, so if the list is now empty, we need to provide an empty value if (list.Length == 0) { list.Append("\"\""); } } if (isFinalisedQuotedText || !ARemoveLeadingAndTrailingSpaces) { return value.ToString(); } else { return value.ToString().TrimEnd(new char[] { ' ' }); } }
/// <summary> /// 从StringBuilder中复制出char[] /// </summary> /// <param name="buff"></param> /// <returns></returns> static char[] ToChars(StringBuilder buff) { char[] chs = new char[buff.Length]; buff.CopyTo(0, chs, 0, chs.Length); return chs; }