Ejemplo n.º 1
0
    // A2: reverse the whole string, detect each word and reverse the word
    // Pitfall: need extra work to remove continuous space
    public String reverseWords(String input)
    {
        if (input==null || input.length() == 0) return input;
        StringBuilder a = new StringBuilder(input);

        int start = -1;
        int end = -1;

        reverse(a, 0, a.length()-1);

        for (int i=0; i<=a.length(); i++)
        {
            if (i == a.length() || a.charAt(i) == ' ')
            {
                if (start < end) reverse(a, start+1, end);
                start = i;
            }
            else
            {
                end = i;
            }
        }

        return a.toString();
    }
 /**
  * Returns the message string of the DuplicateFormatFlagsException.
  *
  * @return the message string of the DuplicateFormatFlagsException.
  */
 public override String getMessage()
 {
     StringBuilder buffer = new StringBuilder();
     buffer.append("Flags of the DuplicateFormatFlagsException is'");
     buffer.append(flags);
     buffer.append("'");
     return buffer.toString();
 }
Ejemplo n.º 3
0
 public static string GetFailQueries(string[] exceptionQueries, bool verbose)
 {
     StringBuilder failQueries = new StringBuilder();
     for (int i = 0; i < exceptionQueries.Length; i++)
     {
         new ExceptionQueryTst(exceptionQueries[i], verbose).DoTest(failQueries);
     }
     return failQueries.toString();
 }
 private KeyValuePair<List<List<string>>, string> generateFileInput(int count, string fieldDelimiter, bool hasWeights, bool hasPayloads)
 {
     List<List<string>> entries = new List<List<string>>();
     StringBuilder sb = new StringBuilder();
     bool hasPayload = hasPayloads;
     for (int i = 0; i < count; i++)
     {
         if (hasPayloads)
         {
             hasPayload = (i == 0) ? true : Random().nextBoolean();
         }
         KeyValuePair<List<string>, string> entrySet = GenerateFileEntry(fieldDelimiter, (!hasPayloads && hasWeights) ? Random().nextBoolean() : hasWeights, hasPayload);
         entries.Add(entrySet.Key);
         sb.append(entrySet.Value);
     }
     return new KeyValuePair<List<List<string>>, string>(entries, sb.toString());
 }
 public static String toASCIILowerCase(String s)
 {
     int len = s.length();
     StringBuilder buffer = new StringBuilder(len);
     for (int i = 0; i < len; i++)
     {
         char c = s.charAt(i);
         if ('A' <= c && c <= 'Z')
         {
             buffer.append((char)(c + ('a' - 'A')));
         }
         else
         {
             buffer.append(c);
         }
     }
     return buffer.toString();
 }
Ejemplo n.º 6
0
            public override object Format(Passage[] passages, string content)
            {
                // Copied from DefaultPassageFormatter, but
                // tweaked to include the matched term:
                StringBuilder sb  = new StringBuilder();
                int           pos = 0;

                foreach (Passage passage in passages)
                {
                    // don't add ellipsis if its the first one, or if its connected.
                    if (passage.StartOffset > pos && pos > 0)
                    {
                        sb.append("... ");
                    }
                    pos = passage.StartOffset;
                    for (int i = 0; i < passage.NumMatches; i++)
                    {
                        int start = passage.matchStarts[i];
                        int end   = passage.matchEnds[i];
                        // its possible to have overlapping terms
                        if (start > pos)
                        {
                            sb.Append(content, pos, start - pos);
                        }
                        if (end > pos)
                        {
                            sb.Append("<b>");
                            int startPos = Math.Max(pos, start);
                            sb.Append(content, startPos, end - startPos);
                            sb.Append('(');
                            sb.Append(passage.MatchTerms[i].Utf8ToString());
                            sb.Append(')');
                            sb.Append("</b>");
                            pos = end;
                        }
                    }
                    // its possible a "term" from the analyzer could span a sentence boundary.
                    sb.Append(content, pos, Math.Max(pos, passage.EndOffset) - pos);
                    pos = passage.EndOffset;
                }
                return(sb.toString());
            }
Ejemplo n.º 7
0
        protected internal virtual String convertPattern(String template, String fromChars, String toChars,
                                                         bool check)
        {
            if (!check && fromChars.equals(toChars))
            {
                return(template);
            }
            bool          quote  = false;
            StringBuilder output = new StringBuilder();
            int           length = template.length();

            for (int i = 0; i < length; i++)
            {
                int  index;
                char next = template.charAt(i);
                if (next == '\'')
                {
                    quote = !quote;
                }
                if (!quote && (index = fromChars.indexOf(next)) != -1)
                {
                    output.append(toChars.charAt(index));
                }
                else if (check &&
                         !quote &&
                         ((next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z')))
                {
                    // text.05=Invalid pattern char {0} in {1}
                    throw new java.lang.IllegalArgumentException("Invalid pattern char " + next + " in " + template); //$NON-NLS-1$
                }
                else
                {
                    output.append(next);
                }
            }
            if (quote)
            {
                // text.04=Unterminated quote
                throw new java.lang.IllegalArgumentException("Unterminated quote"); //$NON-NLS-1$
            }
            return(output.toString());
        }
Ejemplo n.º 8
0
        public bool alert(Host host, BackgroundException failure, StringBuilder log)
        {
            _notification.alert(host, failure, log);
            bool r = false;

            _controller.Invoke(delegate
            {
                String provider = host.getProtocol().getProvider();
                string footer   = String.Format("{0}/{1}", PreferencesFactory.get().getProperty("website.help"),
                                                provider);
                string title    = LocaleFactory.localizedString("Error");
                string message  = failure.getMessage() ?? LocaleFactory.localizedString("Unknown");
                string detail   = failure.getDetail() ?? LocaleFactory.localizedString("Unknown");
                string expanded = log.length() > 0 ? log.toString() : null;
                string commandButtons;
                if (_diagnostics.determine(failure) == FailureDiagnostics.Type.network)
                {
                    commandButtons = String.Format("{0}|{1}", LocaleFactory.localizedString("Try Again", "Alert"),
                                                   LocaleFactory.localizedString("Network Diagnostics", "Alert"));
                }
                else
                {
                    commandButtons = String.Format("{0}", LocaleFactory.localizedString("Try Again", "Alert"));
                }
                _controller.WarningBox(title, message, detail, expanded, commandButtons, true, footer,
                                       delegate(int option, bool @checked)
                {
                    switch (option)
                    {
                    case 0:
                        r = true;
                        break;

                    case 1:
                        ReachabilityFactory.get().diagnose(host);
                        r = false;
                        break;
                    }
                });
            }, true);
            return(r);
        }
            private static void testRanges(){
                //testing ranges 
                string[] letters = { "A", "B", "C", "D" ,"E" , "F", "G", "H", "I", "J", "K", "L", "M" ,"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; 
                //first range a to Z 
                range range1 = 0..;
                //next range is from D to Z
                range range2 = 3..;
                //3rd range B to Y 
                range range3 = 1..^1; 
                //4th range A to X      
                range range4 = 0..^2;

                StringBuilder builder = new StringBuilder();
                range range5 = 1..4;
                foreach(var letter in letters[range5])
                {
                    builder.append($"{letter}"");
                }
                    Console.Writeline(builder.toString());
                }
 protected void HandleSqlLogRegistry()
 {
     if (DBFluteConfig.GetInstance().IsUseSqlLogRegistry)
     {
         StringBuilder sb = new StringBuilder();
         InternalSqlLogRegistryLocator.Instance = new InternalSqlLogRegistry();
         sb.append("{SqlLog Information}").append(GetLineSeparator());
         sb.append("  [SqlLogRegistry]").append(GetLineSeparator());
         sb.append("    ...Setting up SqlLogRegistry").append(GetLineSeparator());
         sb.append("    because the property 'IsUseSqlLogRegistry' of the config of DBFlute is true");
         _log.Info(sb.toString());
     }
     else
     {
         if (InternalSqlLogRegistryLocator.Instance != null)
         {
             InternalSqlLogRegistryLocator.Instance = null;
         }
     }
 }
Ejemplo n.º 11
0
        public override string toString()
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.append(new StringBuilder().append("Fst(start=").append(this.start).append(", isyms=").append(Arrays.toString(this.isyms)).append(", osyms=").append(Arrays.toString(this.osyms)).append(", semiring=").append(this.semiring).append(")\n").toString());
            int num = this.states.size();

            for (int i = 0; i < num; i++)
            {
                State state = (State)this.states.get(i);
                stringBuilder.append(new StringBuilder().append("  ").append(state).append("\n").toString());
                int numArcs = state.getNumArcs();
                for (int j = 0; j < numArcs; j++)
                {
                    Arc arc = state.getArc(j);
                    stringBuilder.append(new StringBuilder().append("    ").append(arc).append("\n").toString());
                }
            }
            return(stringBuilder.toString());
        }
Ejemplo n.º 12
0
        private string join(Iterable <String> items, int limit)
        {
            StringBuilder sb    = new StringBuilder();
            int           count = 0;

            foreach (string item in items)
            {
                if (count > 0)
                {
                    sb.append(", ");
                }
                sb.append(item);
                if (limit > 0 && count == limit)
                {
                    break;
                }
                count++;
            }
            return(sb.toString());
        }
Ejemplo n.º 13
0
    public string method()
    {
        var sb    = new StringBuilder();
        var it    = power(2, 8).iterator();
        var first = true;

        while (it.hasNext())
        {
            if (first)
            {
                first = false;
            }
            else
            {
                sb.append(", ");
            }
            sb.append("" + it.nextInt());
        }
        return(sb.toString());
    }
Ejemplo n.º 14
0
        public static string doubleToScientificString(double number, int fractionDigits)
        {
            DecimalFormat decimalFormat = new DecimalFormat();
            StringBuilder stringBuilder = new StringBuilder(5 + fractionDigits).append("0.");

            for (int i = 0; i < fractionDigits; i++)
            {
                stringBuilder.append('0');
            }
            stringBuilder.append("E00");
            decimalFormat.applyPattern(stringBuilder.toString());
            string text = decimalFormat.format(number);
            int    num  = String.instancehelper_indexOf(text, 69);

            if (String.instancehelper_charAt(text, num + 1) != '-')
            {
                return(new StringBuilder().append(String.instancehelper_substring(text, 0, num + 1)).append('+').append(String.instancehelper_substring(text, num + 1)).toString());
            }
            return(text);
        }
Ejemplo n.º 15
0
        /// <param name="data">The AnswerDataObject to be serialized
        /// </param>
        /// <returns> A string containing the xforms compliant format
        /// for a <select> tag, a string containing a list of answers
        /// separated by space characters.
        /// </returns>
        public virtual System.Object serializeAnswerData(SelectMultiData data)
        {
            System.Collections.ArrayList   selections = (System.Collections.ArrayList)data.Value;
            System.Collections.IEnumerator en         = selections.GetEnumerator();
            StringBuilder selectString = new StringBuilder();

            //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
            while (en.MoveNext())
            {
                //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
                Selection selection = (Selection)en.Current;
                if (selectString.length() > 0)
                {
                    selectString.append(DELIMITER);
                }
                selectString.append(selection.Value);
            }
            //As Crazy, and stupid, as it sounds, this is the XForms specification
            //for storing multiple selections.
            return(selectString.toString());
        }
        /**
         * Implement a toString() method suitable for debugging.
         *
         * @return a debugging toString
         */
        public override String ToString()
        {
            StringBuilder buf = new StringBuilder();

            buf.append("[");
            java.util.Iterator <Object> i = uniqueSet().iterator();
            while (i.hasNext())
            {
                Object current = i.next();
                int    count   = getCount(current);
                buf.append(count);
                buf.append(":");
                buf.append(current);
                if (i.hasNext())
                {
                    buf.append(",");
                }
            }
            buf.append("]");
            return(buf.toString());
        }
Ejemplo n.º 17
0
        public static String text2LengthAndHex(String text)
        {
            byte[]        bytes = text.getBytes(StandardCharsets.UTF_8);
            StringBuilder sb    = new StringBuilder();

            sb.append(String.Format("{0:X2} {1:X2} {2:X2} {3:X2}", bytes.Length >> 24, bytes.Length >> 16, bytes.Length >> 8, 0xFF & bytes.Length));
            if (bytes.Length > 0)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    sb.append(String.Format(" {0:X2}", 0xFF & bytes[i]));
                }
                int idx = bytes.Length;
                while ((idx & 3) != 0)
                {
                    idx++;
                    sb.append(" 00");
                }
            }
            return(sb.toString());
        }
        /**
         * returns a new random sentence, up to maxSentenceLength "words" in length.
         * each word is a single character (a-z). The first one is capitalized.
         */
        private String newSentence(Random r, int maxSentenceLength)
        {
            StringBuilder sb          = new StringBuilder();
            int           numElements = TestUtil.NextInt32(r, 1, maxSentenceLength);

            for (int i = 0; i < numElements; i++)
            {
                if (sb.Length > 0)
                {
                    sb.append(' ');
                    sb.append((char)TestUtil.NextInt32(r, 'a', 'z'));
                }
                else
                {
                    // capitalize the first word to help breakiterator
                    sb.append((char)TestUtil.NextInt32(r, 'A', 'Z'));
                }
            }
            sb.append(". "); // finalize sentence
            return(sb.toString());
        }
Ejemplo n.º 19
0
        public override System.String ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.append("{filt-expr:");
            //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
            sb.append(x.ToString());
            sb.append(",{");
            for (int i = 0; i < predicates.Length; i++)
            {
                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                sb.append(predicates[i].ToString());
                if (i < predicates.Length - 1)
                {
                    sb.append(",");
                }
            }
            sb.append("}}");

            return(sb.toString());
        }
Ejemplo n.º 20
0
        public static string getContextName(Unit[] context)
        {
            if (context == null)
            {
                return("*");
            }
            if (context.Length == 0)
            {
                return("(empty)");
            }
            StringBuilder stringBuilder = new StringBuilder();
            int           num           = context.Length;

            for (int i = 0; i < num; i++)
            {
                Unit unit = context[i];
                stringBuilder.append((unit != null) ? unit.getName() : null).append('.');
            }
            stringBuilder.setLength(stringBuilder.length() - 1);
            return(stringBuilder.toString());
        }
Ejemplo n.º 21
0
 private void collect(Node x, StringBuilder prefix, String pattern, Queue<String> results) {
     if (x == null) return;
     int d = prefix.length();
     if (d == pattern.length() && x.val != null)
         results.enqueue(prefix.toString());
     if (d == pattern.length())
         return;
     char c = pattern.charAt(d);
     if (c == '.') {
         for (char ch = 0; ch < R; ch++) {
             prefix.append(ch);
             collect(x.next[ch], prefix, pattern, results);
             prefix.deleteCharAt(prefix.length() - 1);
         }
     }
     else {
         prefix.append(c);
         collect(x.next[c], prefix, pattern, results);
         prefix.deleteCharAt(prefix.length() - 1);
     }
 }
Ejemplo n.º 22
0
        public virtual string getWordUnitPath()
        {
            StringBuilder stringBuilder = new StringBuilder();

            for (Token token = this; token != null; token = token.getPredecessor())
            {
                SearchState searchState = token.getSearchState();
                if (searchState is WordSearchState)
                {
                    WordSearchState wordSearchState = (WordSearchState)searchState;
                    Word            word            = wordSearchState.getPronunciation().getWord();
                    stringBuilder.insert(0, new StringBuilder().append(' ').append(word.getSpelling()).toString());
                }
                else if (searchState is UnitSearchState)
                {
                    UnitSearchState unitSearchState = (UnitSearchState)searchState;
                    Unit            unit            = unitSearchState.getUnit();
                    stringBuilder.insert(0, new StringBuilder().append(' ').append(unit.getName()).toString());
                }
            }
            return(String.instancehelper_trim(stringBuilder.toString()));
        }
Ejemplo n.º 23
0
        private static void WriteAndReadAString()
        {
            // Write out a string whose UTF-8 encoding is quite possibly
            // longer than 65535 bytes
            int           length     = Random().nextInt(A_NUMBER_NEAR_65535) + 1;
            MemoryStream  baos       = new MemoryStream();
            StringBuilder testBuffer = new StringBuilder();

            for (int i = 0; i < length; i++)
            {
                testBuffer.append((char)Random().Next());
            }
            string           testString = testBuffer.toString();
            DataOutputStream dos        = new DataOutputStream(baos);

            dos.WriteUTF(testString);

            // Corrupt the data to produce malformed characters
            byte[] testBytes   = baos.ToArray();
            int    dataLength  = testBytes.Length;
            int    corruptions = Random().nextInt(MAX_CORRUPTIONS_PER_CYCLE);

            for (int i = 0; i < corruptions; i++)
            {
                int index = Random().nextInt(dataLength);
                testBytes[index] = (byte)Random().Next();
            }

            // Pay special attention to mangling the end to produce
            // partial characters at end
            testBytes[dataLength - 1] = (byte)Random().Next();
            testBytes[dataLength - 2] = (byte)Random().Next();

            // Attempt to decode the bytes back into a String
            MemoryStream    bais = new MemoryStream(testBytes);
            DataInputStream dis  = new DataInputStream(bais);

            dis.ReadUTF();
        }
        private static String getParameters(MethodInfo method)
        {
            var sb = new StringBuilder();

            sb.append('(');
            var first = true;

            foreach (var p in method.Parameters)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    sb.append(", ");
                }
                sb.append(getName(p.Type));
            }
            sb.append(')');
            return(sb.toString());
        }
Ejemplo n.º 25
0
        // ===============================================================================
        //                                                                  Basic Override
        //                                                                  ==============
        public override String ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.append("{").append(this.CurrentPageNumber).append("/").append(this.AllPageCount);
            sb.append(" of ").append(this.AllRecordCount);
            sb.append(" ").append(IsExistPrePage() ? "true" : "false").append("/").append(IsExistNextPage() ? "true" : "false");
            if (_pageGroupOption != null)
            {
                sb.append(" group:{").append(_pageGroupOption.PageGroupSize).append(",").append(ToStringUtil.ToString(PageGroup().CreatePageNumberList())).append("}");
            }
            if (_pageRangeOption != null)
            {
                sb.append(" range:{").append(_pageRangeOption.PageRangeSize).append(",").append(_pageRangeOption.IsFillLimit);
                sb.append(",").append(ToStringUtil.ToString(PageRange().CreatePageNumberList())).append("}");
            }
            sb.append(" list=").append((this.SelectedList != null ? "" + this.SelectedList.Count : null));
            sb.append(" page=").append(this.PageSize);
            sb.append("}");
            sb.append(":selectedList=").append(this.SelectedList != null ? ToStringUtil.ToString(this.SelectedList) : null);
            return(sb.toString());
        }
Ejemplo n.º 26
0
 public override string toString()
 {
     if (this.cachedName == null)
     {
         StringBuilder stringBuilder = new StringBuilder();
         if (this.isEmitting())
         {
             stringBuilder.append('*');
         }
         stringBuilder.append(this.getName());
         if (this.parent != null)
         {
             stringBuilder.append('_');
             stringBuilder.append(this.parent);
         }
         if (this.isFinal())
         {
             stringBuilder.append('!');
         }
         this.cachedName = stringBuilder.toString();
     }
     return(this.cachedName);
 }
Ejemplo n.º 27
0
        /**
         * 前缀查询,通过字符数组来表示字符串可以优化运行速度
         *
         * @param chars 字符串的字符数组
         * @param begin 开始的下标
         * @return
         */
        public LinkedList <Map.Entry <String, V> > commonPrefixSearchWithValue(char[] chars, int begin)
        {
            LinkedList <Map.Entry <String, V> > result = new LinkedList <Map.Entry <String, V> >();
            StringBuilder sb     = new StringBuilder();
            BaseNode      branch = this;

            for (int i = begin; i < chars.length; ++i)
            {
                char aChar = chars[i];
                branch = branch.getChild(aChar);
                if (branch == null || branch.status == Status.UNDEFINED_0)
                {
                    return(result);
                }
                sb.append(aChar);
                if (branch.status == Status.WORD_MIDDLE_2 || branch.status == Status.WORD_END_3)
                {
                    result.add(new AbstractMap.SimpleEntry <String, V>(sb.toString(), (V)branch.value));
                }
            }

            return(result);
        }
Ejemplo n.º 28
0
        private static URL grammarNameToURL(URL url, string text)
        {
            text = String.instancehelper_replace(text, '.', '/');
            StringBuilder stringBuilder = new StringBuilder();

            if (url != null)
            {
                stringBuilder.append(url);
                if (stringBuilder.charAt(stringBuilder.length() - 1) != '/')
                {
                    stringBuilder.append('/');
                }
            }
            stringBuilder.append(text).append(".gram");
            string text2 = stringBuilder.toString();
            URL    url2;

            try
            {
                url2 = new URL(text2);
            }
            catch (MalformedURLException)
            {
                goto IL_62;
            }
            return(url2);

IL_62:
            url2 = ClassLoader.getSystemResource(text2);
            if (url2 == null)
            {
                string text3 = text2;

                throw new MalformedURLException(text3);
            }
            return(url2);
        }
Ejemplo n.º 29
0
        public String Stem(String input)
        {
            StringBuilder sb = new StringBuilder();

            if (input == null)
            {
                return(null);
            }

            if (string.IsNullOrWhiteSpace(input))
            {
                return(string.Empty);
            }

            //
            input = input.ToLower();
            //reset string buffer
            sb.delete(0, sb.length());
            sb.insert(0, input);
            // stemming...
            //removes case endings from nouns and adjectives
            removeCase(sb);
            //removes possesive endings from names -ov- and -in-
            removePossessives(sb);
            //removes comparative endings
            removeComparative(sb);
            //removes diminutive endings
            removeDiminutive(sb);
            //removes augmentatives endings
            removeAugmentative(sb);
            //removes derivational sufixes from nouns
            removeDerivational(sb);

            var result = sb.toString();

            return(result);
        }
Ejemplo n.º 30
0
        internal const String encoding = "utf-8"; //$NON-NLS-1$

        #endregion Fields

        #region Methods

        /**
         * All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
         * and legal characters are converted into their hexidecimal value prepended
         * by '%'.
         * <p>
         * For example: '#' -> %23
         * Other characters, which are unicode chars that are not US-ASCII, and are
         * not ISO Control or are not ISO Space chars, are preserved.
         * <p>
         * Called from {@code URI.quoteComponent()} (for multiple argument
         * constructors)
         *
         * @param s
         *            java.lang.String the string to be converted
         * @param legal
         *            java.lang.String the characters allowed to be preserved in the
         *            string s
         * @return java.lang.String the converted string
         */
        internal static String quoteIllegal(String s, String legal)
        {
            //throws UnsupportedEncodingException {
            StringBuilder buf = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                if ((ch >= 'a' && ch <= 'z')
                        || (ch >= 'A' && ch <= 'Z')
                        || (ch >= '0' && ch <= '9')
                        || legal.indexOf(ch) > -1
                        || (ch > 127 && !java.lang.Character.isSpaceChar(ch) && !java.lang.Character
                                .isISOControl(ch))) {
                    buf.append(ch);
                } else {
                    byte[] bytes = new String(new char[] { ch }).getBytes(encoding);
                    for (int j = 0; j < bytes.Length; j++) {
                        buf.append('%');
                        buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
                        buf.append(digits.charAt(bytes[j] & 0xf));
                    }
                }
            }
            return buf.toString();
        }
Ejemplo n.º 31
0
        public void TestHugeTerm2()
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < 40960; i++)
            {
                sb.append('a');
            }
            string       input     = sb.toString();
            ICUTokenizer tokenizer = new ICUTokenizer(new StringReader(input), new DefaultICUTokenizerConfig(false, true));

            char[] token = new char[4096];
            Arrays.Fill(token, 'a');
            string expectedToken = new string(token);

            string[] expected =
            {
                expectedToken, expectedToken, expectedToken,
                expectedToken, expectedToken, expectedToken,
                expectedToken, expectedToken, expectedToken,
                expectedToken
            };
            AssertTokenStreamContents(tokenizer, expected);
        }
Ejemplo n.º 32
0
 internal bool GetNextSnippet()
 {
     startTerm   = 0;
     startOffset = nextStartOffset;
     snippetBuffer.Remove(0, snippetBuffer.Length);
     while (true)
     {
         if (ch != -1)
         {
             ch = ReadCharFromBuffer();
         }
         if (ch == -1)
         {
             break;
         }
         else if (!IsDelimiter(ch))
         {
             snippetBuffer.append((char)ch);
         }
         else if (snippetBuffer.Length > 0)
         {
             break;
         }
         else
         {
             startOffset++;
         }
     }
     if (snippetBuffer.Length == 0)
     {
         return(false);
     }
     snippet = snippetBuffer.toString();
     lenTerm = snippet.Length >= n ? n : snippet.Length;
     return(true);
 }
Ejemplo n.º 33
0
 private KeyValuePair<List<string>, string> GenerateFileEntry(string fieldDelimiter, bool hasWeight, bool hasPayload)
 {
     List<string> entryValues = new List<string>();
     StringBuilder sb = new StringBuilder();
     string term = TestUtil.RandomSimpleString(Random(), 1, 300);
     sb.append(term);
     entryValues.Add(term);
     if (hasWeight)
     {
         sb.append(fieldDelimiter);
         long weight = TestUtil.NextLong(Random(), long.MinValue, long.MaxValue);
         sb.append(weight);
         entryValues.Add(weight.ToString());
     }
     if (hasPayload)
     {
         sb.append(fieldDelimiter);
         string payload = TestUtil.RandomSimpleString(Random(), 1, 300);
         sb.append(payload);
         entryValues.Add(payload);
     }
     sb.append("\n");
     return new KeyValuePair<List<string>, string>(entryValues, sb.toString());
 }
Ejemplo n.º 34
0
        public static System.String printBytes(sbyte[] data)
        {
            StringBuilder sb = new StringBuilder();

            sb.append("[");
            for (int i = 0; i < data.Length; i++)
            {
                System.String hex = System.Convert.ToString(data[i], 16);
                if (hex.Length == 1)
                {
                    hex = "0" + hex;
                }
                else
                {
                    hex = hex.Substring(hex.Length - 2);
                }
                sb.append(hex);
                if (i < data.Length - 1)
                {
                    if ((i + 1) % 30 == 0)
                    {
                        sb.append("\n ");
                    }
                    else if ((i + 1) % 10 == 0)
                    {
                        sb.append("  ");
                    }
                    else
                    {
                        sb.append(" ");
                    }
                }
            }
            sb.append("]");
            return(sb.toString());
        }
Ejemplo n.º 35
0
        private void writeDocsToFile(TextWriter writer, bool addHeader, IDictionary <string, string> otherFields)
        {
            if (addHeader)
            {
                writer.Write(WriteLineDocTask.FIELDS_HEADER_INDICATOR);
                writer.Write(WriteLineDocTask.SEP);
                writer.Write(DocMaker.TITLE_FIELD);
                writer.Write(WriteLineDocTask.SEP);
                writer.Write(DocMaker.DATE_FIELD);
                writer.Write(WriteLineDocTask.SEP);
                writer.Write(DocMaker.BODY_FIELD);
                if (otherFields != null)
                {
                    // additional field names in the header
                    foreach (Object fn in otherFields.Keys)
                    {
                        writer.Write(WriteLineDocTask.SEP);
                        writer.Write(fn.toString());
                    }
                }
                writer.WriteLine();
            }
            StringBuilder doc = new StringBuilder();

            doc.append("title").append(WriteLineDocTask.SEP).append("date").append(WriteLineDocTask.SEP).append(DocMaker.BODY_FIELD);
            if (otherFields != null)
            {
                // additional field values in the doc line
                foreach (Object fv in otherFields.Values)
                {
                    doc.append(WriteLineDocTask.SEP).append(fv.toString());
                }
            }
            writer.Write(doc.toString());
            writer.WriteLine();
        }
Ejemplo n.º 36
0
        public void testPrintCertificateInfo()
        {
            String expectedCertificateInfo = "Certificate name:\n"
                                             + "  /ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B\n"
                                             + "Validity:\n"
                                             + "  NotBefore: 20150814T223739\n"
                                             + "  NotAfter: 20150818T223738\n"
                                             + "Public key bits:\n"
                                             + "MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQCeBj5HhbI0N6qFR6wDJIO1nKgF\n"
                                             + "OiQe64kBu+mbssMirGjj8GwCzmimxNCnBpCcqhsIHYtDmjNnRG0hoxuImpdeWcQV\n"
                                             + "C9ksvVEHYYKtwbjXv5vPfSTCY/OXF+v+YiW6W02Kwnq9Q4qPuPLxxWow01CMyJrf\n"
                                             + "7+0153pi6nZ8uwgmxwIBEQ==\n" + "Signature Information:\n"
                                             + "  Signature Type: SignatureSha256WithRsa\n"
                                             + "  Key Locator: Name=/ndn/site1/KEY/ksk-2516425377094\n";

            CertificateV2 certificate = new CertificateV2();

            certificate.wireDecode(new Blob(CERT, false));

            StringBuilder actual = new StringBuilder();

            certificate.printCertificate(actual);
            Assert.AssertEquals(expectedCertificateInfo, actual.toString());
        }
Ejemplo n.º 37
0
        public void TestLargeSentence()
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < 5000; i++)
            {
                sb.append("我购买了道具和服装");
            }
            Analyzer    analyzer = new SmartChineseAnalyzer(TEST_VERSION_CURRENT);
            TokenStream stream   = analyzer.GetTokenStream("", sb.toString());

            try
            {
                stream.Reset();
                while (stream.IncrementToken())
                {
                }
                stream.End();
            }
            finally
            {
                IOUtils.DisposeWhileHandlingException(stream);
            }
        }
Ejemplo n.º 38
0
 /// <summary>
 /// Convert this component value by escaping characters according to the
 /// NDN URI Scheme. This also adds "..." to a value with zero or more ".".
 /// This adds a type code prefix as needed, such as "sha256digest=".
 /// </summary>
 ///
 /// <returns>The escaped string.</returns>
 public String toEscapedString()
 {
     StringBuilder result = new StringBuilder(value_.buf().remaining());
     toEscapedString(result);
     return result.toString();
 }
Ejemplo n.º 39
0
        /// <summary>
        /// Encode the name according to the "NDN URI Scheme".  If there are interest
        /// selectors, append "?" and added the selectors as a query string.  For
        /// example "/test/name?ndn.ChildSelector=1".
        /// </summary>
        ///
        /// <returns>The URI string.</returns>
        /// @note This is an experimental feature.  See the API docs for more detail at
        /// http://named-data.net/doc/ndn-ccl-api/interest.html#interest-touri-method .
        public String toUri()
        {
            StringBuilder selectors = new StringBuilder();

            if (minSuffixComponents_ >= 0)
                selectors.append("&ndn.MinSuffixComponents=").append(
                        minSuffixComponents_);
            if (maxSuffixComponents_ >= 0)
                selectors.append("&ndn.MaxSuffixComponents=").append(
                        maxSuffixComponents_);
            if (childSelector_ >= 0)
                selectors.append("&ndn.ChildSelector=").append(childSelector_);
            selectors.append("&ndn.MustBeFresh=").append((mustBeFresh_) ? 1 : 0);
            if (interestLifetimeMilliseconds_ >= 0)
                selectors.append("&ndn.InterestLifetime=").append(
                        (long) Math.Round(interestLifetimeMilliseconds_,MidpointRounding.AwayFromZero));
            if (nonce_.size() > 0) {
                selectors.append("&ndn.Nonce=");
                net.named_data.jndn.Name.toEscapedString(nonce_.buf(), selectors);
            }
            if (getExclude().size() > 0)
                selectors.append("&ndn.Exclude=").append(getExclude().toUri());

            StringBuilder result = new StringBuilder();

            result.append(getName().toUri());
            String selectorsString = selectors.toString();
            if (selectorsString.Length > 0)
                // Replace the first & with ?.
                result.append("?").append(selectorsString.Substring(1));

            return result.toString();
        }
Ejemplo n.º 40
0
 protected internal virtual String convertPattern(String template, String fromChars, String toChars,
         bool check)
 {
     if (!check && fromChars.equals(toChars)) {
         return template;
     }
     bool quote = false;
     StringBuilder output = new StringBuilder();
     int length = template.length();
     for (int i = 0; i < length; i++) {
         int index;
         char next = template.charAt(i);
         if (next == '\'') {
             quote = !quote;
         }
         if (!quote && (index = fromChars.indexOf(next)) != -1) {
             output.append(toChars.charAt(index));
         } else if (check
                 && !quote
                 && ((next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z'))) {
             // text.05=Invalid pattern char {0} in {1}
             throw new java.lang.IllegalArgumentException("Invalid pattern char "+next+" in "+ template); //$NON-NLS-1$
         } else {
             output.append(next);
         }
     }
     if (quote) {
         // text.04=Unterminated quote
         throw new java.lang.IllegalArgumentException("Unterminated quote"); //$NON-NLS-1$
     }
     return output.toString();
 }
Ejemplo n.º 41
0
        //throws IOException
        /**
         * Returns the next line of text available from this reader. A line is
         * represented by zero or more characters followed by {@code '\n'},
         * {@code '\r'}, {@code "\r\n"} or the end of the reader. The string does
         * not include the newline sequence.
         *
         * @return the contents of the line or {@code null} if no characters were
         *         read before the end of the reader has been reached.
         * @throws IOException
         *             if this reader is closed or some other I/O error occurs.
         */
        public virtual String readLine()
        {
            lock (lockJ) {
                if (isClosed()) {
                    throw new IOException(MESSAGE_READER_IS_CLOSED); //$NON-NLS-1$
                }
                /* has the underlying stream been exhausted? */
                if (pos == end && fillBuf() == -1) {
                    return null;
                }
                for (int charPos = pos; charPos < end; charPos++) {
                    char ch = buf[charPos];
                    if (ch > '\r') {
                        continue;
                    }
                    if (ch == '\n') {
                        String res = new String(buf, pos, charPos - pos);
                        pos = charPos + 1;
                        return res;
                    } else if (ch == '\r') {
                        String res = new String(buf, pos, charPos - pos);
                        pos = charPos + 1;
                        if (((pos < end) || (fillBuf() != -1))
                                && (buf[pos] == '\n')) {
                            pos++;
                        }
                        return res;
                    }
                }

                char eol = '\0';
                StringBuilder result = new StringBuilder(80);
                /* Typical Line Length */

                result.Append(buf, pos, end - pos);
                while (true) {
                    pos = end;

                    /* Are there buffered characters available? */
                    if (eol == '\n') {
                        return result.toString();
                    }
                    // attempt to fill buffer
                    if (fillBuf() == -1) {
                        // characters or null.
                        return result.Length > 0 || eol != '\0'
                                ? result.toString()
                                : null;
                    }
                    for (int charPos = pos; charPos < end; charPos++) {
                        char c = buf[charPos];
                        if (eol == '\0') {
                            if ((c == '\n' || c == '\r')) {
                                eol = c;
                            }
                        } else if (eol == '\r' && c == '\n') {
                            if (charPos > pos) {
                                result.Append(buf, pos, charPos - pos - 1);
                            }
                            pos = charPos + 1;
                            return result.toString();
                        } else {
                            if (charPos > pos) {
                                result.Append(buf, pos, charPos - pos - 1);
                            }
                            pos = charPos;
                            return result.toString();
                        }
                    }
                    if (eol == '\0') {
                        result.Append(buf, pos, end - pos);
                    } else {
                        result.Append(buf, pos, end - pos - 1);
                    }
                }
            }
        }
Ejemplo n.º 42
0
 /**
  * Used to convert raw characters to their escaped version
  * when these raw version cannot be used as part of an ASCII
  * string literal.
  */
 static string add_escapes(String str)
 {
     StringBuilder retval = new StringBuilder();
     char ch;
     for (int i = 0; i < str.Length(); i++)
     {
         switch (str[i])
         {
             case '\0':
                 continue;
             case '\b':
                 retval.Append("\\b");
                 continue;
             case '\t':
                 retval.Append("\\t");
                 continue;
             case '\n':
                 retval.Append("\\n");
                 continue;
             case '\f':
                 retval.Append("\\f");
                 continue;
             case '\r':
                 retval.Append("\\r");
                 continue;
             case '\"':
                 retval.Append("\\\"");
                 continue;
             case '\'':
                 retval.Append("\\\'");
                 continue;
             case '\\':
                 retval.Append("\\\\");
                 continue;
             default:
                 if ((ch = str[i]) < 0x20 || ch > 0x7e)
                 {
                     String s = "0000" + Integer.toString(ch, 16);
                     retval.Append("\\u" + s.Substring(s.Length() - 4, s.Length()));
                 }
                 else
                 {
                     retval.Append(ch);
                 }
                 continue;
         }
     }
     return retval.toString();
 }
Ejemplo n.º 43
0
        /* can process only 32-bit numbers */
        internal static String toDecimalScaledString(long value, int scale)
        {
            int resLengthInChars;
            int currentChar;
            char [] result;
            bool negNumber = value < 0;
            if(negNumber) {
                value = -value;
            }
            if (value == 0) {
                switch (scale) {
                    case 0: return "0"; //$NON-NLS-1$
                    case 1: return "0.0"; //$NON-NLS-1$
                    case 2: return "0.00"; //$NON-NLS-1$
                    case 3: return "0.000"; //$NON-NLS-1$
                    case 4: return "0.0000"; //$NON-NLS-1$
                    case 5: return "0.00000"; //$NON-NLS-1$
                    case 6: return "0.000000"; //$NON-NLS-1$
                    default:
                        StringBuilder result0 = new StringBuilder();
                        if (scale  < 0) {
                            result0.Append("0E+"); //$NON-NLS-1$
                        } else {
                            result0.Append("0E"); //$NON-NLS-1$
                        }
                        result0.Append( (scale == java.lang.Integer.MIN_VALUE) ? "2147483648" : java.lang.Integer.toString(-scale)); //$NON-NLS-1$
                        return result0.toString();
                }
            }
            // one 32-bit unsigned value may contains 10 decimal digits
            resLengthInChars = 18;
            // Explanation why +1+7:
            // +1 - one char for sign if needed.
            // +7 - For "special case 2" (see below) we have 7 free chars for
            //  inserting necessary scaled digits.
            result = new char[resLengthInChars+1];
            //  Allocated [resLengthInChars+1] characters.
            // a free latest character may be used for "special case 1" (see below)
            currentChar = resLengthInChars;
            long v = value;
            do {
                long prev = v;
                v /= 10;
                result[--currentChar] = (char) (0x0030 + (prev - v * 10));
            } while (v != 0);

            long exponent = (long)resLengthInChars - (long)currentChar - scale - 1L;
            if (scale == 0) {
                if (negNumber) {
                    result[--currentChar] = '-';
                }
                return new String(result, currentChar, resLengthInChars - currentChar);
            }
            if (scale > 0 && exponent >= -6) {
                if (exponent >= 0) {
                    // special case 1
                    int insertPoint = currentChar + (int) exponent ;
                    for(int j=resLengthInChars-1; j>=insertPoint; j--) {
                        result[j+1] = result[j];
                    }
                    result[++insertPoint]='.';
                    if (negNumber) {
                        result[--currentChar] = '-';
                    }
                    return new String(result, currentChar, resLengthInChars - currentChar + 1);
                }
                // special case 2
                for (int j = 2; j < -exponent + 1; j++) {
                    result[--currentChar] = '0';
                }
                result[--currentChar] = '.';
                result[--currentChar] = '0';
                if (negNumber) {
                    result[--currentChar] = '-';
                }
                return new String(result, currentChar, resLengthInChars - currentChar);
            }
            int startPoint = currentChar + 1;
            int endPoint = resLengthInChars;
            StringBuilder result1 = new StringBuilder(16+endPoint-startPoint);
            if (negNumber) {
                result1.Append('-');
            }
            if (endPoint - startPoint >= 1) {
                result1.Append(result[currentChar]);
                result1.Append('.');
                result1.Append(result,currentChar+1,resLengthInChars - currentChar-1);
            } else {
                result1.Append(result,currentChar,resLengthInChars - currentChar);
            }
            result1.Append('E');
            if (exponent > 0) {
                result1.Append('+');
            }
            result1.Append(java.lang.Long.toString(exponent));
            return result1.toString();
        }
Ejemplo n.º 44
0
        /**
         * Builds the correspondent {@code String} representation of {@code val}
         * being scaled by {@code scale}.
         *
         * @see BigInteger#toString()
         * @see BigDecimal#toString()
         */
        internal static String toDecimalScaledString(BigInteger val, int scale)
        {
            int sign = val.sign;
            int numberLength = val.numberLength;
            int []digits = val.digits;
            int resLengthInChars;
            int currentChar;
            char []result;

            if (sign == 0) {
                switch (scale) {
                    case 0:
                        return "0"; //$NON-NLS-1$
                    case 1:
                        return "0.0"; //$NON-NLS-1$
                    case 2:
                        return "0.00"; //$NON-NLS-1$
                    case 3:
                        return "0.000"; //$NON-NLS-1$
                    case 4:
                        return "0.0000"; //$NON-NLS-1$
                    case 5:
                        return "0.00000"; //$NON-NLS-1$
                    case 6:
                        return "0.000000"; //$NON-NLS-1$
                    default:
                        StringBuilder result0 = new StringBuilder();
                        if (scale < 0) {
                            result0.Append("0E+"); //$NON-NLS-1$
                        } else {
                            result0.Append("0E"); //$NON-NLS-1$
                        }
                        result0.Append(-scale);
                        return result0.toString();
                }
            }
            // one 32-bit unsigned value may contains 10 decimal digits
            resLengthInChars = numberLength * 10 + 1 + 7;
            // Explanation why +1+7:
            // +1 - one char for sign if needed.
            // +7 - For "special case 2" (see below) we have 7 free chars for
            // inserting necessary scaled digits.
            result = new char[resLengthInChars + 1];
            // allocated [resLengthInChars+1] characters.
            // a free latest character may be used for "special case 1" (see
            // below)
            currentChar = resLengthInChars;
            if (numberLength == 1) {
                int highDigit = digits[0];
                if (highDigit < 0) {
                    long v = highDigit & 0xFFFFFFFFL;
                    do {
                        long prev = v;
                        v /= 10;
                        result[--currentChar] = (char) (0x0030 + ((int) (prev - v * 10)));
                    } while (v != 0);
                } else {
                    int v = highDigit;
                    do {
                        int prev = v;
                        v /= 10;
                        result[--currentChar] = (char) (0x0030 + (prev - v * 10));
                    } while (v != 0);
                }
            } else {
                int []temp = new int[numberLength];
                int tempLen = numberLength;
                java.lang.SystemJ.arraycopy(digits, 0, temp, 0, tempLen);
                /*BIG_LOOP: */while (true) {
                    // divide the array of digits by bigRadix and convert
                    // remainders
                    // to characters collecting them in the char array
                    long result11 = 0;
                    for (int i1 = tempLen - 1; i1 >= 0; i1--) {
                        long temp1 = (result11 << 32)
                                + (temp[i1] & 0xFFFFFFFFL);
                        long res = divideLongByBillion(temp1);
                        temp[i1] = (int) res;
                        result11 = (int) (res >> 32);
                    }
                    int resDigit = (int) result11;
                    int previous = currentChar;
                    do {
                        result[--currentChar] = (char) (0x0030 + (resDigit % 10));
                    } while (((resDigit /= 10) != 0) && (currentChar != 0));
                    int delta = 9 - previous + currentChar;
                    for (int i = 0; (i < delta) && (currentChar > 0); i++) {
                        result[--currentChar] = '0';
                    }
                    int j = tempLen - 1;
                    for (; temp[j] == 0; j--) {
                        if (j == 0) { // means temp[0] == 0
                            goto AFTER_LOOP; //break BIG_LOOP;
                        }
                    }
                    tempLen = j + 1;
                }
            AFTER_LOOP:
                while (result[currentChar] == '0') {
                    currentChar++;
                }
            }
            bool negNumber = (sign < 0);
            int exponent = resLengthInChars - currentChar - scale - 1;
            if (scale == 0) {
                if (negNumber) {
                    result[--currentChar] = '-';
                }
                return new String(result, currentChar, resLengthInChars
                        - currentChar);
            }
            if ((scale > 0) && (exponent >= -6)) {
                if (exponent >= 0) {
                    // special case 1
                    int insertPoint = currentChar + exponent;
                    for (int j = resLengthInChars - 1; j >= insertPoint; j--) {
                        result[j + 1] = result[j];
                    }
                    result[++insertPoint] = '.';
                    if (negNumber) {
                        result[--currentChar] = '-';
                    }
                    return new String(result, currentChar, resLengthInChars
                            - currentChar + 1);
                }
                // special case 2
                for (int j = 2; j < -exponent + 1; j++) {
                    result[--currentChar] = '0';
                }
                result[--currentChar] = '.';
                result[--currentChar] = '0';
                if (negNumber) {
                    result[--currentChar] = '-';
                }
                return new String(result, currentChar, resLengthInChars
                        - currentChar);
            }
            int startPoint = currentChar + 1;
            int endPoint = resLengthInChars;
            StringBuilder result1 = new StringBuilder();//16 + endPoint - startPoint);
            if (negNumber) {
                result1.Append('-');
            }
            if (endPoint - startPoint >= 1) {
                result1.Append(result[currentChar]);
                result1.Append('.');
                result1.Append(result, currentChar + 1, resLengthInChars
                        - currentChar - 1);
            } else {
                result1.Append(result, currentChar, resLengthInChars
                        - currentChar);
            }
            result1.Append('E');
            if (exponent > 0) {
                result1.Append('+');
            }
            result1.Append(java.lang.Integer.toString(exponent));
            return result1.toString();
        }
Ejemplo n.º 45
0
 /**
  * Other characters, which are Unicode chars that are not US-ASCII, and are
  * not ISO Control or are not ISO Space chars are not preserved. They are
  * converted into their hexidecimal value prepended by '%'.
  * <p>
  * For example: Euro currency symbol -> "%E2%82%AC".
  * <p>
  * Called from URI.toASCIIString()
  *
  * @param s
  *            java.lang.String the string to be converted
  * @return java.lang.String the converted string
  */
 static String encodeOthers(String s)
 {
     //throws UnsupportedEncodingException {
     StringBuilder buf = new StringBuilder();
     for (int i = 0; i < s.length(); i++) {
         char ch = s.charAt(i);
         if (ch <= 127) {
             buf.append(ch);
         } else {
             byte[] bytes = new String(new char[] { ch }).getBytes(encoding);
             for (int j = 0; j < bytes.Length; j++) {
                 buf.append('%');
                 buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
                 buf.append(digits.charAt(bytes[j] & 0xf));
             }
         }
     }
     return buf.toString();
 }
Ejemplo n.º 46
0
        /**
         * Parses the next token from this tokenizer's source stream or reader. The
         * type of the token is stored in the {@code ttype} field, additional
         * information may be stored in the {@code nval} or {@code sval} fields.
         *
         * @return the value of {@code ttype}.
         * @throws IOException
         *             if an I/O error occurs while parsing the next token.
         */
        public virtual int nextToken()
        {
            // throws IOException {
            if (pushBackToken) {
                pushBackToken = false;
                if (ttype != TT_UNKNOWN) {
                    return ttype;
                }
            }
            sval = null; // Always reset sval to null
            int currentChar = peekChar == -2 ? read() : peekChar;

            if (lastCr && currentChar == '\n') {
                lastCr = false;
                currentChar = read();
            }
            if (currentChar == -1) {
                return (ttype = TT_EOF);
            }

            byte currentType = currentChar > 255 ? TOKEN_WORD
                    : tokenTypes[currentChar];
            while ((currentType & TOKEN_WHITE) != 0) {
                /**
                 * Skip over white space until we hit a new line or a real token
                 */
                if (currentChar == '\r') {
                    lineNumber++;
                    if (isEOLSignificant) {
                        lastCr = true;
                        peekChar = -2;
                        return (ttype = TT_EOL);
                    }
                    if ((currentChar = read()) == '\n') {
                        currentChar = read();
                    }
                } else if (currentChar == '\n') {
                    lineNumber++;
                    if (isEOLSignificant) {
                        peekChar = -2;
                        return (ttype = TT_EOL);
                    }
                    currentChar = read();
                } else {
                    // Advance over this white space character and try again.
                    currentChar = read();
                }
                if (currentChar == -1) {
                    return (ttype = TT_EOF);
                }
                currentType = currentChar > 255 ? TOKEN_WORD
                        : tokenTypes[currentChar];
            }

            /**
             * Check for digits before checking for words since digits can be
             * contained within words.
             */
            if ((currentType & TOKEN_DIGIT) != 0) {
                StringBuilder digits = new StringBuilder(20);
                bool haveDecimal = false, checkJustNegative = currentChar == '-';
                while (true) {
                    if (currentChar == '.') {
                        haveDecimal = true;
                    }
                    digits.append((char) currentChar);
                    currentChar = read();
                    if ((currentChar < '0' || currentChar > '9')
                            && (haveDecimal || currentChar != '.')) {
                        break;
                    }
                }
                peekChar = currentChar;
                if (checkJustNegative && digits.Length == 1) {
                    // Didn't get any other digits other than '-'
                    return (ttype = '-');
                }
                try {
                    nval = java.lang.Double.valueOf(digits.toString()).doubleValue();
                } catch (java.lang.NumberFormatException e) {
                    // Unsure what to do, will write test.
                    nval = 0;
                }
                return (ttype = TT_NUMBER);
            }
            // Check for words
            if ((currentType & TOKEN_WORD) != 0) {
                StringBuilder word = new StringBuilder(20);
                while (true) {
                    word.append((char) currentChar);
                    currentChar = read();
                    if (currentChar == -1
                            || (currentChar < 256 && (tokenTypes[currentChar] & (TOKEN_WORD | TOKEN_DIGIT)) == 0)) {
                        break;
                    }
                }
                peekChar = currentChar;
                sval = forceLowercase ? word.toString().ToLower() : word
                        .toString();
                return (ttype = TT_WORD);
            }
            // Check for quoted character
            if (currentType == TOKEN_QUOTE) {
                int matchQuote = currentChar;
                StringBuilder quoteString = new StringBuilder();
                int peekOne = read();
                while (peekOne >= 0 && peekOne != matchQuote && peekOne != '\r'
                        && peekOne != '\n') {
                    bool readPeek = true;
                    if (peekOne == '\\') {
                        int c1 = read();
                        // Check for quoted octal IE: \377
                        if (c1 <= '7' && c1 >= '0') {
                            int digitValue = c1 - '0';
                            c1 = read();
                            if (c1 > '7' || c1 < '0') {
                                readPeek = false;
                            } else {
                                digitValue = digitValue * 8 + (c1 - '0');
                                c1 = read();
                                // limit the digit value to a byte
                                if (digitValue > 037 || c1 > '7' || c1 < '0') {
                                    readPeek = false;
                                } else {
                                    digitValue = digitValue * 8 + (c1 - '0');
                                }
                            }
                            if (!readPeek) {
                                // We've consumed one to many
                                quoteString.append((char) digitValue);
                                peekOne = c1;
                            } else {
                                peekOne = digitValue;
                            }
                        } else {
                            switch (c1) {
                                case 'a':
                                    peekOne = 0x7;
                                    break;
                                case 'b':
                                    peekOne = 0x8;
                                    break;
                                case 'f':
                                    peekOne = 0xc;
                                    break;
                                case 'n':
                                    peekOne = 0xA;
                                    break;
                                case 'r':
                                    peekOne = 0xD;
                                    break;
                                case 't':
                                    peekOne = 0x9;
                                    break;
                                case 'v':
                                    peekOne = 0xB;
                                    break;
                                default:
                                    peekOne = c1;
                                    break;
                            }
                        }
                    }
                    if (readPeek) {
                        quoteString.append((char) peekOne);
                        peekOne = read();
                    }
                }
                if (peekOne == matchQuote) {
                    peekOne = read();
                }
                peekChar = peekOne;
                ttype = matchQuote;
                sval = quoteString.toString();
                return ttype;
            }
            // Do comments, both "//" and "/*stuff*/"
            if (currentChar == '/' && (slashSlashCommentsJ || slashStarCommentsJ)) {
                if ((currentChar = read()) == '*' && slashStarCommentsJ) {
                    int peekOne = read();
                    while (true) {
                        currentChar = peekOne;
                        peekOne = read();
                        if (currentChar == -1) {
                            peekChar = -1;
                            return (ttype = TT_EOF);
                        }
                        if (currentChar == '\r') {
                            if (peekOne == '\n') {
                                peekOne = read();
                            }
                            lineNumber++;
                        } else if (currentChar == '\n') {
                            lineNumber++;
                        } else if (currentChar == '*' && peekOne == '/') {
                            peekChar = read();
                            return nextToken();
                        }
                    }
                } else if (currentChar == '/' && slashSlashCommentsJ) {
                    // Skip to EOF or new line then return the next token
                    while ((currentChar = read()) >= 0 && currentChar != '\r'
                            && currentChar != '\n') {
                        // Intentionally empty
                    }
                    peekChar = currentChar;
                    return nextToken();
                } else if (currentType != TOKEN_COMMENT) {
                    // Was just a slash by itself
                    peekChar = currentChar;
                    return (ttype = '/');
                }
            }
            // Check for comment character
            if (currentType == TOKEN_COMMENT) {
                // Skip to EOF or new line then return the next token
                while ((currentChar = read()) >= 0 && currentChar != '\r'
                        && currentChar != '\n') {
                    // Intentionally empty
                }
                peekChar = currentChar;
                return nextToken();
            }

            peekChar = read();
            return (ttype = currentChar);
        }
Ejemplo n.º 47
0
 /// <summary>
 /// Convert the value by escaping characters according to the NDN URI Scheme.
 /// This also adds "..." to a value with zero or more ".".
 /// This does not add a type code prefix such as "sha256digest=".
 /// </summary>
 ///
 /// <param name="value"></param>
 /// <returns>The escaped string.</returns>
 public static String toEscapedString(ByteBuffer value_ren)
 {
     StringBuilder result = new StringBuilder(value_ren.remaining());
     toEscapedString(value_ren, result);
     return result.toString();
 }
Ejemplo n.º 48
0
        /// <summary>
        /// Encode this Exclude with elements separated by "," and Exclude.Type.ANY
        /// shown as "///".
        /// </summary>
        ///
        /// <returns>the URI string</returns>
        public String toUri()
        {
            if ((entries_.Count==0))
                return "";

            StringBuilder result = new StringBuilder();
            for (int i = 0; i < entries_.Count; ++i) {
                if (i > 0)
                    result.append(",");

                if (get(i).getType() == net.named_data.jndn.Exclude.Type.ANY)
                    result.append("*");
                else
                    get(i).getComponent().toEscapedString(result);
            }

            return result.toString();
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Encode this name as a URI according to the NDN URI Scheme.
        /// </summary>
        ///
        /// <param name="includeScheme">which is normally the case where toUri() is used for display.</param>
        /// <returns>The URI string.</returns>
        public String toUri(bool includeScheme)
        {
            if ((components_.Count==0))
                return (includeScheme) ? "ndn:/" : "/";

            StringBuilder result = new StringBuilder();
            if (includeScheme)
                result.append("ndn:");
            for (int i = 0; i < components_.Count; ++i) {
                result.append("/");
                get(i).toEscapedString(result);
            }

            return result.toString();
        }
Ejemplo n.º 50
0
 /// <summary>
 /// This method is used to convert the provided value into an XML
 /// usable format. This is used in the serialization process when
 /// there is a need to convert a field value in to a string so
 /// that that value can be written as a valid XML entity.
 /// </summary>
 /// <param name="value">
 /// this is the value to be converted to a string
 /// </param>
 /// <returns>
 /// this is the string representation of the given value
 /// </returns>
 public String Write(Object value, int length) {
    StringBuilder text = new StringBuilder(length);
    for(int i = 0; i < length; i++) {
       Object entry = Array.get(value, i);
       if(entry != null) {
          text.append(entry);
       }
    }
    return text.toString();
 }
Ejemplo n.º 51
0
	    /**
	     * Parses <code>source</code> for special double values.  These values
	     * include Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY.
	     *
	     * @param source the string to parse
	     * @param value the special value to parse.
	     * @param pos input/ouput parsing parameter.
	     * @return the special number.
	     */
	    private static Number parseNumber(String source, double value,
	                                      ParsePosition pos) {
	        Number ret = null;
	
	        StringBuilder sb = new StringBuilder();
	        sb.append('(');
	        sb.append(value);
	        sb.append(')');
	
	        int n = sb.length();
	        int startIndex = pos.getIndex();
	        int endIndex = startIndex + n;
	        if (endIndex < source.length()) {
	            if (source.substring(startIndex, endIndex).compareTo(sb.toString()) == 0) {
	                ret = Double.valueOf(value);
	                pos.setIndex(endIndex);
	            }
	        }
	
	        return ret;
	    }
Ejemplo n.º 52
0
 /**
  * Returns the state of this tokenizer in a readable format.
  *
  * @return the current state of this tokenizer.
  */
 public override String ToString()
 {
     // Values determined through experimentation
     StringBuilder result = new StringBuilder();
     result.append("Token["); //$NON-NLS-1$
     switch (ttype) {
         case TT_EOF:
             result.append("EOF"); //$NON-NLS-1$
             break;
         case TT_EOL:
             result.append("EOL"); //$NON-NLS-1$
             break;
         case TT_NUMBER:
             result.append("n="); //$NON-NLS-1$
             result.append(nval);
             break;
         case TT_WORD:
             result.append(sval);
             break;
         default:
             if (ttype == TT_UNKNOWN || tokenTypes[ttype] == TOKEN_QUOTE) {
                 result.append(sval);
             } else {
                 result.append('\'');
                 result.append((char) ttype);
                 result.append('\'');
             }
             break;
     }
     result.append("], line "); //$NON-NLS-1$
     result.append(lineNumber);
     return result.toString();
 }
 /**
  * Makes a bunch of single-char tokens (the max # unique terms will at most be 26).
  * puts the # unique terms into expected, to be checked against the norm.
  */
 private string AddValue()
 {
     StringBuilder sb = new StringBuilder();
     HashSet<string> terms = new HashSet<string>();
     int num = TestUtil.NextInt(Random(), 0, 255);
     for (int i = 0; i < num; i++)
     {
         sb.append(' ');
         char term = (char)TestUtil.NextInt(Random(), 'a', 'z');
         sb.append(term);
         terms.add("" + term);
     }
     expected.Add(terms.size());
     return sb.toString();
 }
Ejemplo n.º 54
0
        /**
         * Decodes the string argument which is assumed to be encoded in the {@code
         * x-www-form-urlencoded} MIME content type using the UTF-8 encoding scheme.
         * <p>
         *'%' and two following hex digit characters are converted to the
         * equivalent byte value. All other characters are passed through
         * unmodified.
         * <p>
         * e.g. "A%20B%20C %24%25" -> "A B C $%"
         * <p>
         * Called from URI.getXYZ() methods
         *
         * @param s
         *            java.lang.String The encoded string.
         * @return java.lang.String The decoded version.
         */
        static String decode(String s)
        {
            //throws UnsupportedEncodingException {

            StringBuilder result = new StringBuilder();
            java.io.ByteArrayOutputStream outJ = new java.io.ByteArrayOutputStream();
            for (int i = 0; i < s.length();) {
                char c = s.charAt(i);
                if (c == '%') {
                    outJ.reset();
                    do {
                        if (i + 2 >= s.length()) {
                            throw new java.lang.IllegalArgumentException("Incomplete % sequence at: "+ i); //$NON-NLS-1$
                        }
                        int d1 = java.lang.Character.digit(s.charAt(i + 1), 16);
                        int d2 = java.lang.Character.digit(s.charAt(i + 2), 16);
                        if (d1 == -1 || d2 == -1) {
                            throw new java.lang.IllegalArgumentException("Invalid % sequence ("+s.substring(i, i + 3)+") at: "+java.lang.StringJ.valueOf(i));
                        }
                        outJ.write((byte) ((d1 << 4) + d2));
                        i += 3;
                    } while (i < s.length() && s.charAt(i) == '%');
                    result.append(outJ.toString(encoding));
                    continue;
                }
                result.append(c);
                i++;
            }
            return result.toString();
        }
Ejemplo n.º 55
0
 /**
  * Returns a string containing a concise, human-readable description of the
  * receiver.
  *
  * @return a comma delimited list of the indices of all bits that are set.
  */
 public override String ToString()
 {
     StringBuilder sb = new StringBuilder(bits.Length / 2);
     int bitCount = 0;
     sb.append('{');
     bool comma = false;
     for (int i = 0; i < bits.Length; i++) {
         if (bits[i] == 0) {
             bitCount += ELM_SIZE;
             continue;
         }
         for (int j = 0; j < ELM_SIZE; j++) {
             if (((bits[i] & (TWO_N_ARRAY[j])) != 0)) {
                 if (comma) {
                     sb.append(", "); //$NON-NLS-1$
                 }
                 sb.append(bitCount);
                 comma = true;
             }
             bitCount++;
         }
     }
     sb.append('}');
     return sb.toString();
 }
Ejemplo n.º 56
0
        /// <summary>
        /// 获取分页数据
        /// </summary>
        public string getListData(TDemoModel searchModel = null)
        {
            StringBuilder sb = new StringBuilder();
            string searchText = "";
            //检索
            StringBuilder searchScript = new StringBuilder();
            searchScript.AppendLine(" WHERE ");
            searchScript.AppendLine(" 1 = 1 ");
            if (!String.IsNullOrEmpty(searchModel.fullTextSearch))
            {
                searchScript.AppendLine(" AND ( ");
                searchScript.AppendLine("     [Column1] LIKE N'%" + searchModel.fullTextSearch.quote() + "%'");
                searchScript.AppendLine("     OR [Column2] = '" + searchModel.fullTextSearch.quote() + "'");
                searchScript.AppendLine("     OR [Column3] = '" + searchModel.fullTextSearch.quote() + "'");
                searchScript.AppendLine("     OR [Column4] = '" + searchModel.fullTextSearch.quote() + "'");
                searchScript.AppendLine(" ) ");
            }
            searchText = searchScript.toString();

            //获取总数据量
            sb.AppendLine(" DECLARE @dataCount int ");
            sb.AppendLine("  ");
            sb.AppendLine(" SELECT ");
            sb.AppendLine(" @dataCount = COUNT(1) ");
            sb.AppendLine(" FROM [dbo].[TDemo]");
            sb.AppendLine(searchText);
            sb.Append(" ; ");

            //数据分页
            sb.AppendLine(" WITH TMP AS ( ");
            sb.AppendLine(" SELECT ");
            sb.AppendLine(" [ID] ");
            sb.AppendLine(" ,[Column1] ");
            sb.AppendLine(" ,[Column2] ");
            sb.AppendLine(" ,[Column3] ");
            sb.AppendLine(" ,[Column4] ");
            sb.AppendLine(" ,ROW_NUMBER() OVER(" + string.Format("ORDER BY {0} {1}",
                                                    searchModel.sortColumn,
                                                    searchModel.sortDirection == System.ComponentModel.ListSortDirection.Ascending ? "ASC" : "DESC")
                                                + ") AS [RowNumber] ");
            sb.AppendLine(" FROM [dbo].[TDemo]");
            sb.AppendLine(searchText);
            sb.AppendLine(" ) ");

            //获取分页数据
            sb.AppendLine(" SELECT ");
            sb.AppendLine(" A.[ID] ");
            sb.AppendLine(" ,A.[Column1] ");
            sb.AppendLine(" ,A.[Column2] ");
            sb.AppendLine(" ,A.[Column3] ");
            sb.AppendLine(" ,A.[Column4] ");
            sb.AppendLine(" ,@dataCount AS [DataCount] ");
            sb.AppendLine(" FROM TMP AS A ");
            if (searchModel != null)
            {
                sb.AppendLine(" WHERE ");
                sb.AppendLine(" 1 = 1 ");
                sb.AppendLine(string.Format(" AND A.[RowNumber] BETWEEN {0} AND {1} ", searchModel.startRowNumber, searchModel.endRowNumber));
            }

            if (searchModel != null && !Check.getIns().isEmpty(searchModel.sortColumn))
            {
                sb.AppendLine(string.Format("ORDER BY A.{0} {1}",
                    searchModel.sortColumn,
                    searchModel.sortDirection == System.ComponentModel.ListSortDirection.Ascending ? "ASC" : "DESC"));
            }
            return sb.ToString();
        }
Ejemplo n.º 57
0
	private void mHereDocContents()
	{
		EnterRule_HereDocContents();
		EnterRule("HereDocContents", 121);
		TraceIn("HereDocContents", 121);
		try
		{
			// C:\\Users\\exKAZUu\\Projects\\Code2Xml\\Code2Xml.Core\\Generators\\ANTLRv3\\Php\\Php.g:736:2: ()
			DebugEnterAlt(1);
			// C:\\Users\\exKAZUu\\Projects\\Code2Xml\\Code2Xml.Core\\Generators\\ANTLRv3\\Php\\Php.g:736:4: 
			{
			DebugLocation(736, 4);
			if (state.backtracking == 0)
			{

						// Please see also Code2Xml.Languages.ANTLRv3.Core.ExtensionForParser
						var sb = new StringBuilder();
						while (input.LA(1) != '\n') {
							sb.append((char)input.LA(1));
							input.consume();
						}
						input.consume();
						var hereDocName = sb.toString().TrimEnd();
						var hdnl = hereDocName.length();
						while (true) {
							var matchEnd = true;
							for (int i = 0; i < hdnl; i++) {
								if (input.LA(1) != hereDocName.charAt(i)) {
									matchEnd = false;
									break;
								}
								input.consume();
							}
							if (matchEnd == false) {
								while (input.LA(1) != '\n') {
									input.consume();
								}
								input.consume();
							} else {
								break;
							}
						}
					
			}

			}

		}
		finally
		{
			TraceOut("HereDocContents", 121);
			LeaveRule("HereDocContents", 121);
			LeaveRule_HereDocContents();
		}
	}
Ejemplo n.º 58
0
 public String readLine()
 {
     //throws IOException {
     StringBuilder line = new StringBuilder(80); // Typical line length
     bool foundTerminator = false;
     while (true) {
         int nextByte = inJ.read();
         switch (nextByte) {
             case -1:
                 if (line.Length == 0 && !foundTerminator) {
                     return null;
                 }
                 return line.toString();
             case (byte) '\r':
                 if (foundTerminator) {
                     ((PushbackInputStream) inJ).unread(nextByte);
                     return line.toString();
                 }
                 foundTerminator = true;
                 /* Have to be able to peek ahead one byte */
                 if (!(inJ is PushbackInputStream)) { //think Bug in Harmony, not test on class but on type required
                     inJ = new PushbackInputStream(inJ);
                 }
                 break;
             case (byte) '\n':
                 return line.toString();
             default:
                 if (foundTerminator) {
                     ((PushbackInputStream) inJ).unread(nextByte);
                     return line.toString();
                 }
                 line.append((char) nextByte);
                 break;
         }
     }
 }
    public String reverseWords(String s)
    {
        if (s == null)
        {
            return s;
        }

        int begin = 0;
        int end = 0;
        while (begin < s.length() && s.charAt(begin) == ' ')
        {
            begin++;
        }
        if (begin == s.length())
        {
            return "";
        }

        if (s.length() <= 1)
        {
            return s;
        }
        StringBuilder result = new StringBuilder("");
        while (begin < s.length() && end < s.length())
        {
            while (begin < s.length() && s.charAt(begin) == ' ')
            {
                begin++;
            }
            if (begin == s.length())
            {
                break;
            }
            end = begin + 1;
            while (end < s.length() && s.charAt(end) != ' ')
            {
                end++;
            }
            if (result.length() != 0)
            {
                result.insert(0, " ");
            }
            if (end < s.length())
            {
                result.insert(0, s.substring(begin, end));
            }
            else
            {
                result.insert(0, s.substring(begin, s.length()));
                break;
            }
            begin = end + 1;
        }
        return result.toString();
    }
Ejemplo n.º 60
-5
    // A1: going in reverse order, detect each word to append to the new string
    public String reverseWords(String a)
    {
        if (a == null || a.length() == 0) return a;

        StringBuilder b = new StringBuilder();

        int end = -1;
        int start = -1;
        int i = a.length()-1;

        while (i >= 0)
        {
            while (i >= 0 && a.charAt(i) == ' ') i--;
            end = i;

            while (i >= 0 && a.charAt(i) != ' ') i--;
            start = i;

            if (start < end) {
                if (b.length() > 0) b.append(' ');
                b.append(a.substring(start+1, end+1));
            }
        }

        return b.toString();
    }