public void StringBuilderIndexOf() { // name of the song that I was listening when I create the function :) var sb = new StringBuilder("Blue Pilots Project - Million Clouds"); Assert.AreEqual(5, sb.IndexOf("Pilots")); Assert.AreEqual(20, sb.IndexOf('-')); Assert.AreEqual(22, sb.IndexOf("m", 0, true)); }
private static int GetStartIndex(StringBuilder value) { int startIndex = value.IndexOf("\r\n\"", false); if (startIndex >= 0) { startIndex += 3; } else { startIndex = value.IndexOf("\n\"", false); if (startIndex >= 0) { startIndex += 2; } else { startIndex = 0; } } return startIndex; }
static void Main(string[] args) { // расширение для StringBuilder (public, static not implement, first argument is this) string str = "hello World for test!"; StringBuilder sb = new StringBuilder(str); Int32 index = sb.IndexOf('W'); Console.WriteLine("sb.IndexOf('W') = "+ index); // расширение для IEnumerable (public, static not implement, first argument is this) List<string> list = new List<string>() { "1", "2", "3", "4", "5" }; list.ShowItems(); "hello my little pony".ShowItems(); //list.Count(); Console.ReadLine(); }
public LetNode(Token<TokenType> t) { //Note:Syntax: let <var> = <expr> StringBuilder statement = new StringBuilder(t.TokenValue); statement.RemoveSpaceAtBegin(); statement.RemoveKeywordAtBegin(TemplateKeywords.Let); statement.RemoveSpaceAtBegin(); //this._varName = statement.ExtractFirstToken(); int idx = statement.IndexOf('='); if (idx < 0) ExceptionHelper.ThrowKeywordExpected("="); this._varName = statement.ToString().Substring(0, idx).Trim(); statement.RemoveBegin(_varName); if (!_varName.IsValidVariableName()) ExceptionHelper.ThrowInvalidVarName(_varName); statement.RemoveSpaceAtBegin(); statement.RemoveKeywordAtBegin("="); this._expression = statement.ToString().Trim(); if (_expression.Length == 0) ExceptionHelper.ThrowSyntaxError(t.TokenValue); }
public string Generate(string csharpCode, bool formatOutput = false, params QuineParam[] extraParams) { bool newlineEscaping = csharpCode.Contains(Newline); bool backslashEscaping = newlineEscaping || csharpCode.Contains('\\'); bool minified = Minified; string printMethod = PrintMethod; if (csharpCode.Contains("using System;")) printMethod = printMethod.Replace("System.", ""); int number = 0; string strNumberString = "{" + number++ + "}"; string quotes1NumberString = "{" + number++ + "}"; string backslashNumberString = backslashEscaping ? "{" + number++ + "}" : ""; string newlineNumberString = (!minified || newlineEscaping) ? "{" + number++ + "}" : ""; string space = minified ? "" : " "; string indent = ""; if (!minified) { int ind = csharpCode.IndexOf(KernelPattern); int newlineInd = csharpCode.LastIndexOf(Newline, ind); indent = csharpCode.Substring(newlineInd + Newline.Length, ind - newlineInd - Newline.Length); } var existedExtraParams = extraParams.Where(p => csharpCode.IndexOf(p.KeyBegin) != -1); var kernel = new StringBuilder(); kernel.AppendFormat("var {0}{5}={5}{4}{3}{4};{6}{1}({0},{5}{0},{5}{2}{4}{2}", StrName, printMethod, Quotes2, strNumberString, quotes1NumberString, space, minified ? "" : newlineNumberString + indent); if (backslashEscaping) kernel.AppendFormat(",{2}{0}{1}{1}{0}", Quotes2, backslashNumberString, space); if (newlineEscaping) kernel.AppendFormat(",{2}{0}{1}r{1}n{0}", quotes1NumberString, backslashNumberString, space); foreach (var p in existedExtraParams) { string value = p.Value.Replace("{", "{{").Replace("}", "}}").Replace(Quotes1, quotes1NumberString); if (backslashEscaping) value = value.Replace(Backslash, backslashNumberString); if (newlineEscaping) value = value.Replace(Newline, newlineNumberString); kernel.AppendFormat(",{1}{0}", value, space); } kernel.Append(");"); var str = new StringBuilder(csharpCode); str = str.Replace("{", "{{").Replace("}", "}}").Replace(Quotes1, quotes1NumberString); if (backslashEscaping) str = str.Replace(Backslash, backslashNumberString); if (newlineEscaping) str = str.Replace(Newline, newlineNumberString); str = str.Replace(KernelPattern, kernel.ToString()); foreach (var p in existedExtraParams) { int beginInd = str.IndexOf(p.KeyBegin); if (beginInd != -1) { int endInd = str.IndexOf(p.KeyEnd, beginInd); if (endInd != -1) { if (beginInd == endInd) str = str.Replace(p.KeyBegin, "{" + number++ + "}"); else { str = str.Remove(beginInd, endInd + p.KeyEnd.Length - beginInd); str = str.Insert(beginInd, "{" + number++ + "}"); } } } } var insertToResult = new StringBuilder(); insertToResult.AppendFormat("var {0}{5}={5}{1}{2}{1};{6}{3}({0},{5}{0},{5}{4}{1}{4}", StrName, Quotes1, str, printMethod, Quotes2, space, minified ? "" : Newline + indent); if (backslashEscaping) insertToResult.AppendFormat(",{2}{0}{1}{1}{0}", Quotes2, Backslash, space); if (!minified || newlineEscaping) insertToResult.AppendFormat(",{2}{0}{1}r{1}n{0}", Quotes1, Backslash, space); foreach (var p in existedExtraParams) insertToResult.AppendFormat(",{1}{0}", p.Value, space); insertToResult.Append(");"); var result = new StringBuilder(csharpCode); result = result.Replace(KernelPattern, insertToResult.ToString()); foreach (var p in existedExtraParams) { int beginInd = result.IndexOf(p.KeyBegin); if (beginInd != -1) { int endInd = result.IndexOf(p.KeyEnd, beginInd); if (endInd != -1) { if (beginInd == endInd) result = result.Replace(p.KeyBegin, p.KeySubstitute == "$key$" ? "" : p.KeySubstitute); else { if (p.KeySubstitute == "$key$") result = result.Replace(p.KeyBegin, "").Replace(p.KeyEnd, ""); else { result = result.Remove(beginInd, endInd + p.KeyEnd.Length - beginInd); result = result.Insert(beginInd, p.KeySubstitute); } } } } } if (formatOutput) return new CSharpParser().Parse(result.ToString()).ToString(); else return result.ToString(); }
private static int FindStartIndex(StringBuilder buffer, int messageIndex) { int index = buffer.IndexOf(CarriageReturnLineFeed, messageIndex, false); return index >= 0 ? index : buffer.IndexOf(LineFeed, messageIndex, false); }
private static int FindEndIndex(StringBuilder buffer, int startIndex) { int index = buffer.IndexOf(String.Concat(CarriageReturnLineFeed, PyonFooter, CarriageReturnLineFeed), startIndex, false); if (index >= 0) { return index; } index = buffer.IndexOf(String.Concat(LineFeed, PyonFooter, LineFeed), startIndex, false); if (index >= 0) { return index; } //index = buffer.IndexOf(PyonFooter, startIndex, StringComparison.Ordinal); //if (index >= 0) //{ // return index; //} return -1; }
/// <summary> /// Parse first message from the data buffer and remove it from the buffer value. The remaining buffer value is returned to the caller. /// </summary> /// <param name="buffer">Data buffer value.</param> /// <returns>JsonMessage or null if no message is available in the buffer.</returns> internal static JsonMessage GetNextJsonMessage(StringBuilder buffer) { if (buffer == null) return null; // find the header int messageIndex = buffer.IndexOf(PyonHeader, false); if (messageIndex < 0) { return null; } // set starting message index messageIndex += PyonHeader.Length; // find the first CrLf or Lf character after the header int startIndex = FindStartIndex(buffer, messageIndex); if (startIndex < 0) return null; // find the footer int endIndex = FindEndIndex(buffer, startIndex); if (endIndex < 0) { return null; } // create the message and set received time stamp var message = new JsonMessage { Received = DateTime.UtcNow }; // get the message name message.Key = buffer.Substring(messageIndex, startIndex - messageIndex); // get the PyON message buffer.SubstringBuilder(startIndex, message.Value, endIndex - startIndex); // replace PyON values with JSON values message.Value.Replace(": None", ": null"); // set the index so we know where to trim the string (end plus footer length) int nextStartIndex = endIndex + PyonFooter.Length; // if more buffer is available set it and return, otherwise set the buffer empty if (nextStartIndex < buffer.Length) { buffer.Remove(0, nextStartIndex); } else { buffer.Clear(); } return message; }
public void ClearContent(StringBuilder content) { content.Replace('\r', ' '); content.Replace('\n', ' '); content.Replace('\0', ' '); content.Replace('\t', ' '); while (content.IndexOf(" ") >= 0) content.Replace(" ", " "); while (content.IndexOf("href =") >= 0) content.Replace("href =", "href="); while (content.IndexOf("\"") >= 0) content.Replace("\"", ""); while (content.IndexOf("'") >= 0) content.Replace("'", ""); while (content.IndexOf("&") >= 0) content.Replace("&", "&"); }
bool IsWorkflow(StringBuilder serviceData) { var startIdx = serviceData.IndexOf("<XamlDefinition>", 0, false); if(startIdx >= 0) { var endIdx = serviceData.IndexOf("</XamlDefinition>", startIdx, false); var dif = endIdx - startIdx; // we know a blank wf is larger then our max string size ;) return startIdx > 0 && dif > (GlobalConstants.MAX_SIZE_FOR_STRING - 1024); } return false; }
/// ------------------------------------------------------------------------- /// <summary> /// Common code that is called from the Control tests to verify the properties associated with a control /// </summary> /// ------------------------------------------------------------------------- internal void TS_TestControlProperties() { string[] frameworks = new string[] { m_le.Current.FrameworkId, DEFAULT_FRAMEWORK }; ControlType ctType = m_le.Current.ControlType; XmlNode node; // Things such as GetBoundingRect, GetClickablePoint return diffent values if they are on or off the viewable portion, // so bail out with an invalid configuration if (m_le.Current.IsOffscreen == true) { // If we can scroll into view, try it if ((bool)m_le.GetCurrentPropertyValue(AutomationElement.IsScrollItemPatternAvailableProperty)) { ScrollItemPattern sip = m_le.GetCurrentPattern(ScrollItemPattern.Pattern) as ScrollItemPattern; try { Comment("Scrolling element({0}) into view", Library.GetUISpyLook(m_le)); sip.ScrollIntoView(); } catch (InvalidOperationException) { ThrowMe(CheckType.IncorrectElementConfiguration, "Cannot test properties for elements that are not visible"); } } if (m_le.Current.IsOffscreen == true) ThrowMe(CheckType.IncorrectElementConfiguration, "Cannot test properties for elements that are not visible"); Comment("Element(" + Library.GetUISpyLook(m_le) + ") is now visible for testing"); } // There is a better way of doing this, by quering the XML for specifics, but need to get this written ArrayList seenProps = new ArrayList(); foreach (string frameWorkId in frameworks) { foreach (XmlNode n in GetNodes(XMLPROPERTIES, ctType, frameWorkId)) { node = n; node = node.NextSibling; if (node == null) return; // Go through all the XML nodes for the properties that this control supports. // This will only test the properties that it finds in the XML. while (node != null) { string property = new StringBuilder(node.Name).Replace("_", ".").ToString(); AutomationProperty ap = Helpers.GetPropertyByName(property); if (seenProps.IndexOf(ap.ProgrammaticName) == -1) { seenProps.Add(ap.ProgrammaticName); string patternName = property.Substring(0, property.IndexOf(".")); if ((patternName == "AutomationElement") || (PatternSupported(patternName))) { object currentValue = m_le.GetCurrentPropertyValue(ap); Comment("Validating {0}.GetCurrentPropertyValue({1})={2}", ctType.ProgrammaticName, property, currentValue); Comment("Node validation is {0}", node.InnerText.ToUpper(CultureInfo.CurrentCulture)); switch (node.InnerText.ToUpper(CultureInfo.CurrentCulture)) { case XML_NON_EMPTY_STRING: { if (currentValue is string) { string obj = (string)currentValue; if (String.IsNullOrEmpty(obj)) { ThrowMe(CheckType.Verification, "{0} : IsNullOrEmpty() returned true but should have been a valid string", property); } } else { ThrowMe(CheckType.Verification, "{0} : did not return correct data type, but returned {1}", property, currentValue.GetType().ToString()); } break; } case XML_FALSE: { if (currentValue is bool) { bool obj = (bool)currentValue; if (obj != false) { ThrowMe(CheckType.Verification, "{0} : did not return a false, but returned {1}", property, obj); } } else { ThrowMe(CheckType.Verification, "{0} : did not return correct data type, but returned {1}", property, currentValue.GetType().ToString()); } break; } case XML_TRUE: { if (currentValue is bool) { bool obj = (bool)currentValue; if (obj != true) { ThrowMe(CheckType.Verification, "{0} : did not return a true, but returned {1}", property, obj); } } else { ThrowMe(CheckType.Verification, "{0} : did not return correct data type, but returned {1}", property, currentValue.GetType().ToString()); } break; } case XML_REQUIRED: { if (currentValue == null || currentValue == AutomationElement.NotSupported) { ThrowMe(CheckType.Verification, "{0} : did not return a valid value, but returned {1}", property,currentValue == null ? "<null>" : currentValue); } break; } case XML_NEVER: { if (currentValue != null || currentValue != AutomationElement.NotSupported) { ThrowMe(CheckType.Verification, "{0} : did not return AutomationElement.NotSupported but returned {1}", property, currentValue ); } break; } case XML_NULL: { if (currentValue != null) { ThrowMe(CheckType.Verification, "{0} : was expected to return null but returned ({1})", property, currentValue ); } break; } case XML_WARN_IF_NOT_NULL: { if (currentValue != null) { ThrowMe(CheckType.Verification, "{0} : was expected to return null but did not", property); } break; } case XML_NOTNULL: { if (currentValue == null) { ThrowMe(CheckType.Verification, "{0} : returned null and was expected to have a valid value", property); } break; } case XML_WARN_IF_NULL: { if (currentValue == null) { ThrowMe(CheckType.Verification, "{0} : returned null and was expected to have a valid value", property); } break; } case XML_NaN: { if (currentValue == null) { ThrowMe(CheckType.Verification, "{0} : returned 'null' and should have returned double.NaN", property); } else if (currentValue is Point) { Point obj = (Point)currentValue; if (!IsNaN(obj.X)) { ThrowMe(CheckType.Verification, "{0} : Point.X returned '{1}' and should have returned double.NaN", property, obj.X); } if (!IsNaN(obj.Y)) { ThrowMe(CheckType.Verification, "{0} : Point.Y returned '{1}' and should have returned double.NaN", property, obj.Y); } } else if (currentValue is Rect) { Rect obj = (Rect)currentValue; if (!IsNaN(obj.Bottom)) { ThrowMe(CheckType.Verification, "{0} : Point.Bottom returned '{1}' and should have returned double.NaN", property, obj.Bottom); } if (!IsNaN(obj.Top)) { ThrowMe(CheckType.Verification, "{0} : Point.Top returned '{1}' and should have returned double.NaN", property, obj.Top); } if (!IsNaN(obj.Left)) { ThrowMe(CheckType.Verification, "{0} : Point.Left returned '{1}' and should have returned double.NaN", property, obj.Left); } if (!IsNaN(obj.Right)) { ThrowMe(CheckType.Verification, "{0} : Point.Right returned '{1}' and should have returned double.NaN", property, obj.Right); } } else if (!IsNaN(currentValue)) { ThrowMe(CheckType.Verification, "{0} : should have returned NaN", property); } break; } case XML_NOT_NaN: { if (currentValue == null) { ThrowMe(CheckType.Verification, "{0} : returned 'null' and should not have returned double.NaN", property); } else if (currentValue is Point) { Point obj = (Point)currentValue; if (IsNaN(obj.X)) { ThrowMe(CheckType.Verification, "{0} : Point.X should not have returned double.NaN", property); } if (IsNaN(obj.Y)) { ThrowMe(CheckType.Verification, "{0} : Point.Y should not have returned double.NaN", property); } } else if (currentValue is Rect) { Rect obj = (Rect)currentValue; if (IsNaN(obj.Bottom)) { ThrowMe(CheckType.Verification, "{0} : Rect.Bottom should not have returned double.NaN", property); } if (IsNaN(obj.Top)) { ThrowMe(CheckType.Verification, "{0} : Rect.Top should not have returned double.NaN", property); } if (IsNaN(obj.Left)) { ThrowMe(CheckType.Verification, "{0} : Rect.Left should not have returned double.NaN", property); } if (IsNaN(obj.Right)) { ThrowMe(CheckType.Verification, "{0} : Rect.Right should not have returned double.NaN", property); } } else if (IsNaN(currentValue)) { ThrowMe(CheckType.Verification, "{0} : returned NaN and should not have", property); } break; } default: throw new Exception(property + ": Bad fomatted XML, need to handle " + node.InnerText + " for " + property); } } } node = node.NextSibling; } } } m_TestStep++; }
/// <summary> /// Splits the given string on every instance of a separator character, as long as the separator is not quoted. Each split /// piece is then unquoted if requested. /// </summary> /// <remarks> /// 1) Unless requested to keep empty splits, a block of contiguous (unquoted) separators is treated as one separator. /// 2) If no separators are given, the string is split on whitespace. /// </remarks> /// <param name="input"></param> /// <param name="maxSplits"></param> /// <param name="keepEmptySplits"></param> /// <param name="unquote"></param> /// <param name="emptySplits">[out] a count of all pieces that were empty, and thus discarded, per remark (1) above</param> /// <param name="separator"></param> /// <returns>ArrayList of all the pieces the string was split into.</returns> internal static ArrayList SplitUnquoted ( string input, int maxSplits, bool keepEmptySplits, bool unquote, out int emptySplits, params char[] separator ) { ErrorUtilities.VerifyThrow(maxSplits >= 2, "There is no point calling this method for less than two splits."); string separators = new StringBuilder().Append(separator).ToString(); ErrorUtilities.VerifyThrow(separators.IndexOf('"') == -1, "The double-quote character is not supported as a separator."); StringBuilder splitString = new StringBuilder(); splitString.EnsureCapacity(input.Length); bool isQuoted = false; int precedingBackslashes = 0; int splits = 1; for (int i = 0; (i < input.Length) && (splits < maxSplits); i++) { switch (input[i]) { case '\0': // Pretend null characters just aren't there. Ignore them. Debug.Assert(false, "Null character in parameter"); break; case '\\': splitString.Append('\\'); precedingBackslashes++; break; case '"': splitString.Append('"'); if ((precedingBackslashes % 2) == 0) { if (isQuoted && (i < (input.Length - 1)) && (input[i + 1] == '"')) { splitString.Append('"'); i++; } isQuoted = !isQuoted; } precedingBackslashes = 0; break; default: if (!isQuoted && (((separators.Length == 0) && char.IsWhiteSpace(input[i])) || (separators.IndexOf(input[i]) != -1))) { splitString.Append('\0'); if (++splits == maxSplits) { splitString.Append(input, i + 1, input.Length - (i + 1)); } } else { splitString.Append(input[i]); } precedingBackslashes = 0; break; } } ArrayList pieces = new ArrayList(); emptySplits = 0; foreach (string splitPiece in splitString.ToString().Split(s_splitMarker, maxSplits)) { string piece = (unquote ? Unquote(splitPiece) : splitPiece); if ((piece.Length > 0) || keepEmptySplits) { pieces.Add(piece); } else { emptySplits++; } } return pieces; }
private static string ParseStringValue(string property, IConfiguration config, ISet<string> visitedPlaceHolders, ILogger logger = null) { if (string.IsNullOrEmpty(property)) return property; StringBuilder result = new StringBuilder(property); int startIndex = property.IndexOf(PREFIX); while (startIndex != -1) { int endIndex = FindEndIndex(result, startIndex); if (endIndex != -1) { string placeholder = result.Substring(startIndex + PREFIX.Length, endIndex); string originalPlaceholder = placeholder; if (!visitedPlaceHolders.Add(originalPlaceholder)) { throw new ArgumentException(String.Format("Circular placeholder reference '{0}' in property definitions", originalPlaceholder)); } // Recursive invocation, parsing placeholders contained in the placeholder key. placeholder = ParseStringValue(placeholder, config, visitedPlaceHolders); // Handle array references foo:bar[1]:baz format -> foo:bar:1:baz string lookup = placeholder.Replace('[', ':').Replace("]", ""); // Now obtain the value for the fully resolved key... string propVal = config[lookup]; if (propVal == null) { int separatorIndex = placeholder.IndexOf(SEPARATOR); if (separatorIndex != -1) { string actualPlaceholder = placeholder.Substring(0, separatorIndex); string defaultValue = placeholder.Substring(separatorIndex + SEPARATOR.Length); propVal = config[actualPlaceholder]; if (propVal == null) { propVal = defaultValue; } } } if (propVal != null) { // Recursive invocation, parsing placeholders contained in these // previously resolved placeholder value. propVal = ParseStringValue(propVal, config, visitedPlaceHolders); result.Replace(startIndex, endIndex + SUFFIX.Length, propVal); logger?.LogVerbose("Resolved placeholder '{0}'" + placeholder); startIndex = result.IndexOf(PREFIX, startIndex + propVal.Length); } else { // Proceed with unprocessed value. startIndex = result.IndexOf(PREFIX, endIndex + PREFIX.Length); } visitedPlaceHolders.Remove(originalPlaceholder); } else { startIndex = -1; } } return result.ToString(); }
/// <summary> /// Reads vectos from file. /// File format like in LIbSVM /// label index:value index2:value ..... /// -1 4:0.5 10:0.9 .... /// </summary> /// <param name="fileName">Data set file name</param> /// <returns></returns> //public static Problem<Vector> ReadVectorsFromFile(string fileName) //{ // List<float> labels = new List<float>(); // List<Vector> vectors = new List<Vector>(); // using (FileStream fileStream = File.OpenRead(fileName)) // { // using (StreamReader input = new StreamReader(fileStream)) // { // int max_index = 0; // while (input.Peek() > -1) // { // string[] parts = input.ReadLine().Trim().Split(); // //label // labels.Add(float.Parse(parts[0])); // //other parts with index and value // int m = parts.Length - 1; // List<Vector.Node> nodes = new List<Vector.Node>(); // int index = 0; // float value; // for (int j = 0; j < m; j++) // { // string[] nodeParts = parts[j + 1].Split(':'); // index = int.Parse(nodeParts[0]); // value = float.Parse(nodeParts[1], System.Globalization.CultureInfo.InvariantCulture); // nodes.Add(new Vector.Node(index, (float)value)); // // v[index] = value; // } // if (m > 0) // { // max_index = Math.Max(max_index, index); // } // vectors.Add(new Vector(nodes)); // } // //assing max index as vector Dimension, // //not always true for different data sets // for (int i = 0; i < vectors.Count; i++) // { // vectors[i].Dimension = max_index; // } // } // } // //Problem<Vector> vectorProblem = new Problem<Vector>(vectors.ToArray(),labels.ToArray()); // //vectorProblem.Elements = vectors.ToArray(); // //vectorProblem.ElementsCount = vectors.Count; // //vectorProblem.Labels = labels.ToArray(); // //return vectorProblem; // return new Problem<Vector>(vectors.ToArray(), labels.ToArray()); //} /// <summary> /// Reads vectos from file. /// File format like in LIbSVM /// label index:value index2:value ..... /// -1 4:0.5 10:0.9 .... /// </summary> /// <param name="fileName">Data set file name</param> /// <returns></returns> public static Problem<SparseVec> ReadVectorsFromFile(string fileName, int numberOfFeatures) { //initial list capacity 8KB, its only heuristic int listCapacity = 1 << 13; //if maxIndex is grether than numberOfFeatures int indexAboveFeature = 0; //list of labels List<float> labels = new List<float>(listCapacity); //counts how many labels we have Dictionary<float, int> coutLabels = new Dictionary<float, int>(10); //list of array, each array symbolize vector // List<KeyValuePair<int, float>[]> vectors = new List<KeyValuePair<int, float>[]>(listCapacity); //new List<List<KeyValuePair<int, double>>>(); //vector parts (index and value) separator char[] vecPartsSeparator = new char[] { ' ' }; //separator between index and value in one part char[] idxValSeparator = new char[] { ':' }; int max_index = numberOfFeatures; List<KeyValuePair<int, float>> vec = new List<KeyValuePair<int, float>>(32); //list of Vectors, currently use SparseVector implementation from dnAnalitycs List<SparseVec> dnaVectors = new List<SparseVec>(listCapacity); using (FileStream fileStream = File.OpenRead(fileName)) { using (StreamReader input = new StreamReader(fileStream)) { //todo: string split function to many memory allocation, http://msdn.microsoft.com/en-us/library/b873y76a.aspx while (input.Peek() > -1) { int indexSeparatorPosition = -1; string inputLine = input.ReadLine().Trim(); int index = 0; float value = 0; #region old code /* string[] parts =inputLine.Split(vecPartsSeparator,StringSplitOptions.RemoveEmptyEntries); //label labels.Add(float.Parse(parts[0],CultureInfo.InvariantCulture)); //other parts with index and value int m = parts.Length - 1; //list of index and value for one vector List<KeyValuePair<int, double>> vec = new List<KeyValuePair<int, double>>(m); //extract index and value for (int j = 0; j < m; j++) { //string[] nodeParts = parts[j + 1].Split(idxValSeparator); //index = int.Parse(nodeParts[0]); //value = float.Parse(nodeParts[1], System.Globalization.CultureInfo.InvariantCulture); //it is more memory eficcient than above version with split indexSeparatorPosition = parts[j + 1].IndexOf(idxValSeparator[0]); index = int.Parse(parts[j+1].Substring(0,indexSeparatorPosition) ); value = float.Parse(parts[j+1].Substring(indexSeparatorPosition+1)); vec.Add(new KeyValuePair<int, double>(index, value)); // v[index] = value; } */ #endregion //add one space to the end of line, needed for parsing string oneLine = new StringBuilder(inputLine).Append(" ").ToString(); int partBegin = -1, partEnd = -1; partBegin = oneLine.IndexOf(vecPartsSeparator[0]); //from begining to first space is label float dataLabel = float.Parse(oneLine.Substring(0, partBegin), CultureInfo.InvariantCulture); labels.Add(dataLabel); if (coutLabels.ContainsKey(dataLabel)) coutLabels[dataLabel]++; else coutLabels[dataLabel] = 1; index = -1; value = -1; partEnd = oneLine.IndexOf(vecPartsSeparator[0], partBegin + 1); while (partEnd > 0) { indexSeparatorPosition = oneLine.IndexOf(idxValSeparator[0], partBegin); index = int.Parse(oneLine.Substring(partBegin + 1, indexSeparatorPosition - (partBegin + 1))); if (index < 1) { throw new ArgumentOutOfRangeException("indexes should start from 1 not from 0"); } value = float.Parse(oneLine.Substring(indexSeparatorPosition + 1, partEnd - (indexSeparatorPosition + 1)), CultureInfo.InvariantCulture); vec.Add(new KeyValuePair<int, float>(index, value)); partBegin = partEnd; partEnd = oneLine.IndexOf(vecPartsSeparator[0], partBegin + 1); } if (vec.Count > 0) { max_index = Math.Max(max_index, index); } //we implictie set numberOfFeatures if max_index is less then numberOfFeatures if (max_index <= numberOfFeatures) max_index = numberOfFeatures; else { //how many previosus vectors has wrong (less) dim size indexAboveFeature = dnaVectors.Count; } // vectors.Add(vec.ToArray()); dnaVectors.Add(new SparseVec(max_index, vec)); //clear vector parts vec.Clear(); }//end while } } for (int i = 0; i < indexAboveFeature; i++) { dnaVectors[i].Dim = max_index; } int numberOfClasses = coutLabels.Count; var elementClasses = coutLabels.Keys.ToArray(); // Array.Sort(elementClasses); return new Problem<SparseVec>(dnaVectors.ToArray(), labels.ToArray(), max_index,numberOfClasses,elementClasses); }
private void SubstituteParam(StringBuilder source, CodeDataGeneratorParam p) { if (p.Value != null) { int beginInd = source.IndexOf(p.KeyBegin); if (beginInd != -1) { int endInd = source.IndexOf(p.KeyEnd, beginInd); int ind, length; if (!p.SaveKey) { ind = beginInd; length = endInd + p.KeyEnd.Length - ind; } else { ind = beginInd + p.KeyBegin.Length; length = endInd - ind; } source = source.Remove(ind, length); if (!IgnoreIndents) source = InsertWithIndents(source, ind, p.Value); else source = source.Insert(ind, p.Value); } } }
public void IndexTest() { StringBuilder str = new StringBuilder("Hello"); Assert.AreEqual(1, str.IndexOf("el")); Assert.AreEqual(3, str.LastIndexOf("l")); }
public static string ClearComments(this string html) { html = html.CleanHeader(); var starts = new List<int>(); for (var i = 0; i < html.Length; i++) { if (i >= html.Length - 4) { break; } i = html.IndexOf(@"<!--", i, StringComparison.Ordinal); if (i == -1) { break; } starts.Add(i); } var ends = starts.Select(start => html.IndexOf(@"-->", start, StringComparison.Ordinal) + 3).ToList(); var content = new StringBuilder(html).ToString(); //Enable cleaning mso styling content = starts.Select((t, i) => html.Substring(t, ends[i] - t)).Aggregate(content, (current, comment) => current.Replace(comment, "")); content = content.Replace(@"<![if !vml]>", ""); content = content.Replace(@"<![endif]>", ""); content = content.Substring(content.IndexOf("<body")); content = content.Substring(content.IndexOf(">") + 1); content = content.Remove(content.LastIndexOf("</body>"), content.Length - content.LastIndexOf("</body>")); //deleting index from description if (content.Contains("<div style='mso-element:comment-list'>")) { content = content.Remove(content.IndexOf("<div style='mso-element:comment-list'>")); } for (int i = 0; ; i++) { if (!content.Contains(">[")) { break; } //content = content.Remove(content.IndexOf(">[")+1, 5); content = content.Remove(content.IndexOf(">[") + 1, (content.IndexOf("]</a>")+1) - (content.IndexOf(">[") + 1)); } return content.Trim(); }
public string RemoveTags(string content) { var templateParts = new string[] { "<", ">" }; int startPos = content.IndexOf(templateParts[0]); if (startPos == -1) return content.Replace('\0', ' ').Trim(); ; int endPos = content.IndexOf(templateParts[1], startPos + templateParts[0].Length); while (startPos != -1 && endPos != -1) { content = content.Remove(startPos, endPos + 1 - startPos); startPos = content.IndexOf(templateParts[0]); if (startPos == -1) return content.Replace('\0', ' ').Trim(); endPos = content.IndexOf(templateParts[1], startPos + templateParts[0].Length); } return content.Replace('\0', ' ').Trim();//TrimEnd('\0'); }
bool IsSource(StringBuilder serviceData) { return serviceData.IndexOf("<Source ", 0, false) == 0; }
public static string GetWordAfter(string stringToStartAfter, StringBuilder entireString, int indexToStartAt, StringComparison comparison) { int indexOf = entireString.IndexOf(stringToStartAfter, indexToStartAt, true); if (indexOf != -1) { int startOfWord = indexOf + stringToStartAfter.Length; // Let's not count the start of the word if it's a newline while (entireString[startOfWord] == WhitespaceChars[0] || entireString[startOfWord] == WhitespaceChars[1] || entireString[startOfWord] == WhitespaceChars[2] || entireString[startOfWord] == WhitespaceChars[3]) { startOfWord++; } int endOfWord = entireString.IndexOfAny(WhitespaceChars, startOfWord); if (endOfWord == -1) { endOfWord = entireString.Length; } return entireString.Substring(startOfWord, endOfWord - startOfWord); } else { return null; } }
// TODO: cjr: would be best to have this non default to false, so that will be the next step once it all works public StringBuilder ToServiceDefinition(bool prepairForDeployment = false) { //TODO this method replicates functionality that is available in the server. There is a serious need to create a common library for resource contracts and resource serialization. StringBuilder result = new StringBuilder(); if(ResourceType == ResourceType.WorkflowService) { var msg = Environment.ResourceRepository.FetchResourceDefinition(Environment, GlobalConstants.ServerWorkspaceID, ID, false); StringBuilder xaml = WorkflowXaml; if ((xaml==null || xaml.Length==0) && msg != null && msg.Message != null) { xaml = msg.Message; } if (xaml != null && xaml.Length != 0) { var service = CreateWorkflowXElement(xaml); // save to the string builder ;) XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true }; using (XmlWriter xwriter = XmlWriter.Create(result, xws)) { service.Save(xwriter); } } } else if(ResourceType == ResourceType.Source || ResourceType == ResourceType.Service) { var msg = Environment.ResourceRepository.FetchResourceDefinition(Environment, GlobalConstants.ServerWorkspaceID, ID, prepairForDeployment); result = msg.Message; if(result == null || result.Length == 0) { result = WorkflowXaml; } if(ResourceType == ResourceType.Service) { var completeDefintion = CreateServiceXElement(result); result = completeDefintion.ToStringBuilder(); } //2013.07.05: Ashley Lewis for bug 9487 - category may have changed! var startNode = result.IndexOf("<Category>", 0, true) + "<Category>".Length; var endNode = result.IndexOf("</Category>", 0, true); if(endNode > startNode) { var len = (endNode - startNode); var oldCategory = result.Substring(startNode, len); if(oldCategory != Category) { result = result.Replace(oldCategory, Category); } } } else { throw new Exception("ToServiceDefinition doesn't support resources of type source. Sources are meant to be managed through the Web API."); } return result; }
public void TestEx() { StringBuilder sb = new System.Text.StringBuilder(); sb.IndexOf('c'); }
/// <summary> /// constructor, open template from file /// </summary> /// <param name="AFullPath"></param> public ProcessTemplate(string AFullPath = null) { if ((AFullPath == null) || (AFullPath.Length == 0)) { return; } if (!File.Exists(AFullPath)) { throw new Exception("Cannot find template file " + AFullPath + "; please adjust the TemplateDir parameter"); } StreamReader r; r = File.OpenText(AFullPath); FTemplateCode = new StringBuilder(); while (!r.EndOfStream) { string line = r.ReadLine().TrimEnd(new char[] { '\r', '\t', ' ', '\n' }).Replace("\t", " "); FTemplateCode.Append(line).Append(Environment.NewLine); } r.Close(); // add other files, {#INCLUDE <filename>} while (FTemplateCode.Contains("{#INCLUDE ")) { Int32 pos = FTemplateCode.IndexOf("{#INCLUDE "); Int32 newLinePos = FTemplateCode.IndexOf(Environment.NewLine, pos); string line = FTemplateCode.Substring(pos, newLinePos - pos); Int32 bracketClosePos = FTemplateCode.IndexOf("}", pos); string filename = FTemplateCode.Substring(pos + "{#INCLUDE ".Length, bracketClosePos - pos - "{#INCLUDE ".Length).Trim(); // do this recursively, to get snippets and code in the right place, even from the include files ProcessTemplate includedTemplate = new ProcessTemplate(Path.GetDirectoryName(AFullPath) + Path.DirectorySeparatorChar + filename); FTemplateCode = FTemplateCode.Replace(line, includedTemplate.FTemplateCode.ToString()); foreach (string key in includedTemplate.FSnippets.Keys) { FSnippets.Add(key, includedTemplate.FSnippets[key]); } } // split off snippets (identified by "{##") if (FTemplateCode.Contains("{##")) { StringCollection snippets = StringHelper.StrSplit(FTemplateCode.ToString(), "{##"); // first part is the actual template code FTemplateCode = new StringBuilder(snippets[0]); for (int counter = 1; counter < snippets.Count; counter++) { string snippetName = snippets[counter].Substring(0, snippets[counter].IndexOf("}")); // exclude first newline string snippetText = snippets[counter].Substring(snippets[counter].IndexOf(Environment.NewLine) + Environment.NewLine.Length); // remove all whitespaces from the end, but keep one line ending for ENDIF etc snippetText = snippetText.TrimEnd(new char[] { '\n', '\r', ' ', '\t' }) + Environment.NewLine; FSnippets.Add(snippetName, snippetText); } } // just make sure that there is a newline at the end, for ENDIF etc FTemplateCode.Append(Environment.NewLine); }
/// <summary> /// clean up the code, remove spaces, too many empty lines /// </summary> /// <param name="s"></param> /// <returns></returns> public void BeautifyCode(ref StringBuilder s) { // remove spaces at end of line while (s.IndexOf(" " + Environment.NewLine) != -1) { s.Replace(" " + Environment.NewLine, Environment.NewLine); } // remove 2 or more empty lines and replace with just one while (s.IndexOf(Environment.NewLine + Environment.NewLine + Environment.NewLine) != -1) { s.Replace(Environment.NewLine + Environment.NewLine + Environment.NewLine, Environment.NewLine + Environment.NewLine); } }
public void ExtensionMethods_IndexOf_WhenStringBuilderDoesContainValueAndIndexIsAfter_ExpectNegativeIndex() { //------------Setup for test-------------------------- StringBuilder value = new StringBuilder("a b c"); //------------Execute Test--------------------------- var result = value.IndexOf("a", 1, false); //------------Assert Results------------------------- Assert.AreEqual(-1, result); }
/// check if all placeholders have been replaced in the template; ignore IFDEF public Boolean CheckTemplateCompletion(StringBuilder s) { int posPlaceholder = s.IndexOf("{#"); string remainingTemplatePlaceholders = ""; while (posPlaceholder > -1) { string latestPlaceholder = s.Substring(posPlaceholder + 2, s.IndexOf("}", posPlaceholder) - posPlaceholder - 2); remainingTemplatePlaceholders += latestPlaceholder + Environment.NewLine; posPlaceholder = s.IndexOf("{#", posPlaceholder + 2); } if (remainingTemplatePlaceholders.Length > 0) { if (FDestinationFile.Length > 0) { StreamWriter FWriter; FWriter = File.CreateText(FDestinationFile + ".error"); FWriter.Write(s.ToString()); FWriter.Close(); throw new Exception("The template has not completely been filled in. " + Environment.NewLine + "You are missing: " + Environment.NewLine + remainingTemplatePlaceholders + Environment.NewLine + "Check file " + FDestinationFile + ".error"); } else { TLogging.Log("Failure in this code: "); TLogging.Log(s.ToString()); throw new Exception("The template has not completely been filled in. " + Environment.NewLine + "You are missing: " + Environment.NewLine + remainingTemplatePlaceholders); } } return true; }
public void ExtensionMethods_IndexOf_WhenStringBuilderContainsValue_ExpectValidIndex() { //------------Setup for test-------------------------- StringBuilder value = new StringBuilder("a b c"); //------------Execute Test--------------------------- var result = value.IndexOf("b", 0, true); //------------Assert Results------------------------- Assert.AreEqual(2, result); }
StringBuilder RemoveSignature(StringBuilder sb) { const string SignatureStart = "<Signature xmlns"; const string SignatureEnd = "</Signature>"; var startIdx = sb.IndexOf(SignatureStart, 0,false); if (startIdx >= 0) { var endIdx = sb.IndexOf(SignatureEnd, startIdx,false); if (endIdx >= 0) { var len = endIdx - startIdx + SignatureEnd.Length; return sb.Remove(startIdx, len); } } return sb; }
internal static int GetIndexAfter(string stringToSearchFor, StringBuilder entireStringToSearchIn) { int indexOfString = entireStringToSearchIn.IndexOf(stringToSearchFor); if (indexOfString == -1) { return -1; } else { int returnValue = indexOfString + stringToSearchFor.Length + 1; if (entireStringToSearchIn[returnValue] == '\n') { returnValue++; } return returnValue; } }
public static void SetClassNameAndNamespace(string classNamespace, string elementName, StringBuilder templateCode, bool useGlobalContent, string replacementContentManagerName, string inheritance) { string namespaceToReplace = StringFunctions.GetWordAfter("namespace ", templateCode); bool isScreen = namespaceToReplace.Contains("Screen"); string classNameToReplace = StringFunctions.GetWordAfter("public partial class ", templateCode); if (isScreen) { templateCode.Replace("namespace " + namespaceToReplace, "namespace " + classNamespace); if (useGlobalContent) { // replace the content mangaer name with the global content manager templateCode.Replace("\"" + classNameToReplace + "\"", replacementContentManagerName); } } else { string whatToReplaceWith = ""; //if (projectNamespace.Contains(".Entities.")) // Not sure why we require the period at the end of Entities if(classNamespace.Contains(".Entities") && classNamespace.IndexOf('.') == classNamespace.IndexOf(".Entities")) { // This is a full namespace. Okay, let's just use that whatToReplaceWith = "namespace " + classNamespace; } else { // We gotta put Entities at the end ourselves whatToReplaceWith = "namespace " + classNamespace + ".Entities"; } templateCode.Replace("namespace " + namespaceToReplace, whatToReplaceWith); } if (!string.IsNullOrEmpty(inheritance)) { templateCode.Replace(classNameToReplace, elementName); var indexOfClass = templateCode.IndexOf("class " + elementName); if (indexOfClass != -1) { int length = ("class " + elementName).Length; templateCode.Insert(indexOfClass + length, " : " + inheritance); } } else { templateCode.Replace(classNameToReplace, elementName); } }
static void Main(string[] args) { StringBuilder str = new StringBuilder(); str.Append("Hello_World !!!"); Console.WriteLine("Index is at: " + str.IndexOf("World", 1)); Console.WriteLine("Index is at: " + str.IndexOf("H")); Console.WriteLine("Index is at: " + str.IndexOf("e")); Console.WriteLine("Index is at: " + str.IndexOf("l")); Console.WriteLine("Index is at: " + str.IndexOf("l", 3)); Console.WriteLine("Index is at: " + str.IndexOf("o")); Console.WriteLine("Index is at: " + str.IndexOf("W")); Console.WriteLine("Index is at: " + str.IndexOf("o")); Console.WriteLine("Index is at: " + str.IndexOf("r")); Console.WriteLine("Index is at: " + str.IndexOf("l")); Console.WriteLine("Index is at: " + str.IndexOf("d")); Console.WriteLine("Substring 5 to end: " + str.Substring(5)); Console.WriteLine("Substring 1, length 1: " + str.Substring(1, 1)); StringBuilder[] strs = str.Split(new String[] { " ", "_" }); Console.WriteLine("Does string contain Hello? " + str.Contains("Hello")); Console.WriteLine("Does string end with !!!? " + str.EndsWith("!!!")); Console.WriteLine("Last index of !: " + str.LastIndexOf("!")); Console.WriteLine("Press any key to continue..."); Console.ReadLine(); }