Exemplo n.º 1
0
        public virtual void load()
        {
            KaldiTextParser parser          = new KaldiTextParser(this.location);
            TransitionModel transitionModel = new TransitionModel(parser);

            this.senonePool = new KaldiGmmPool(parser);
            File              file              = new File(this.location, "phones.txt");
            InputStream       inputStream       = new URL(file.getPath()).openStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader    bufferedReader    = new BufferedReader(inputStreamReader);
            HashMap           hashMap           = new HashMap();
            string            text;

            while (null != (text = bufferedReader.readLine()))
            {
                string[] array = String.instancehelper_split(text, " ");
                if (Character.isLetter(String.instancehelper_charAt(array[0], 0)))
                {
                    hashMap.put(array[0], Integer.valueOf(Integer.parseInt(array[1])));
                }
            }
            this.contextIndependentUnits = new HashMap();
            this.hmmManager = new LazyHmmManager(parser, transitionModel, this.senonePool, hashMap);
            Iterator iterator = hashMap.keySet().iterator();

            while (iterator.hasNext())
            {
                string text2 = (string)iterator.next();
                Unit   unit  = this.unitManager.getUnit(text2, String.instancehelper_equals("SIL", text2));
                this.contextIndependentUnits.put(unit.getName(), unit);
                this.hmmManager.get(HMMPosition.__UNDEFINED, unit);
            }
            this.loadTransform();
            this.loadProperties();
        }
Exemplo n.º 2
0
 /// <exception cref="System.IO.IOException"/>
 public virtual string NextLog()
 {
     if (currentLogData != null && currentLogLength > 0)
     {
         do
         {
             // seek to the end of the current log, relying on BoundedInputStream
             // to prevent seeking past the end of the current log
             if (currentLogData.Skip(currentLogLength) < 0)
             {
                 break;
             }
         }while (currentLogData.Read() != -1);
     }
     currentLogType   = null;
     currentLogLength = 0;
     currentLogData   = null;
     currentLogISR    = null;
     try
     {
         string logType      = valueStream.ReadUTF();
         string logLengthStr = valueStream.ReadUTF();
         currentLogLength = long.Parse(logLengthStr);
         currentLogData   = new BoundedInputStream(valueStream, currentLogLength);
         currentLogData.SetPropagateClose(false);
         currentLogISR = new InputStreamReader(currentLogData, Sharpen.Extensions.GetEncoding
                                                   ("UTF-8"));
         currentLogType = logType;
     }
     catch (EOFException)
     {
     }
     return(currentLogType);
 }
Exemplo n.º 3
0
 private char[] getText(IFile file)
 {
     char[] text;
     if (parameters.AllFiles.getProjectRelativeName(file).equals(parameters.EditedFileName))
     {
         text = parameters.EditedFileText;
     }
     else
     {
         using (var reader = new InputStreamReader(file.getContents(), file.getCharset())) {
             var sb = new StringBuilder();
             int read;
             while ((read = reader.read(buffer)) != -1)
             {
                 sb.append(buffer, 0, read);
             }
             text = new char[sb.length()];
             sb.getChars(0, sizeof(text), text, 0);
         }
     }
     if (sizeof(text) > 0)
     {
         if (text[sizeof(text) - 1] == '\u001a')
         {
             text[sizeof(text) - 1] = ' ';
         }
     }
     return(text);
 }
Exemplo n.º 4
0
        /// <exception cref="System.IO.IOException"></exception>
        private string ReadTestPatchFile(Encoding cs)
        {
            string      patchFile = Sharpen.Extensions.GetTestName() + ".patch";
            InputStream @in       = GetType().GetResourceAsStream(patchFile);

            if (@in == null)
            {
                NUnit.Framework.Assert.Fail("No " + patchFile + " test vector");
                return(null);
            }
            // Never happens
            try
            {
                InputStreamReader r   = new InputStreamReader(@in, cs);
                char[]            tmp = new char[2048];
                StringBuilder     s   = new StringBuilder();
                int n;
                while ((n = r.Read(tmp)) > 0)
                {
                    s.Append(tmp, 0, n);
                }
                return(s.ToString());
            }
            finally
            {
                @in.Close();
            }
        }
Exemplo n.º 5
0
        private static StreamReader ToDotNetReadableStream(this InputStream stream)
        {
            MemoryStream mem    = new MemoryStream();
            StreamWriter writer = new StreamWriter(mem);

            try
            {
                InputStreamReader buffer = new InputStreamReader(stream);
                BufferedReader    reader = new BufferedReader(buffer);
                while (reader.ready())
                {
                    String line = reader.readLine();
                    if (line != null)
                    {
                        writer.WriteLine(line);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch
            {
                throw new RdfParseException("Failed to convert the Java Input Stream into a .Net Stream successfully");
            }
            finally
            {
                stream.close();
            }
            writer.Flush();
            mem.Seek(0, SeekOrigin.Begin);
            return(new StreamReader(mem));
        }
Exemplo n.º 6
0
 public override void Run()
 {
     try
     {
         InputStreamReader isr = new InputStreamReader(@is);
         BufferedReader    br  = new BufferedReader(isr);
         string            s   = null;
         //noinspection ConstantConditions
         while (s == null && shouldRun)
         {
             while ((s = br.ReadLine()) != null)
             {
                 outputFileHandle.Write(s);
                 outputFileHandle.Write("\n");
             }
             Thread.Sleep(1000);
         }
         isr.Close();
         br.Close();
         outputFileHandle.Flush();
     }
     catch (Exception ex)
     {
         System.Console.Out.WriteLine("Problem reading stream :" + @is.GetType().GetCanonicalName() + " " + ex);
         Sharpen.Runtime.PrintStackTrace(ex);
     }
 }
Exemplo n.º 7
0
        internal virtual string ExtractPassword(string pwFile)
        {
            if (pwFile.IsEmpty())
            {
                // If there is no password file defined, we'll assume that we should do
                // an anonymous bind
                return(string.Empty);
            }
            StringBuilder password = new StringBuilder();

            try
            {
                using (StreamReader reader = new InputStreamReader(new FileInputStream(pwFile), Charsets
                                                                   .Utf8))
                {
                    int c = reader.Read();
                    while (c > -1)
                    {
                        password.Append((char)c);
                        c = reader.Read();
                    }
                    return(password.ToString().Trim());
                }
            }
            catch (IOException ioe)
            {
                throw new RuntimeException("Could not read password file: " + pwFile, ioe);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Download a string from the specified URI.
        /// </summary>
        public string DownloadString(URL address)
        {
            URLConnection connection  = null;
            InputStream   inputStream = null;

            try
            {
                connection  = OpenConnection(address);
                inputStream = connection.InputStream;
                var reader  = new InputStreamReader(inputStream);
                var buffer  = new char[BUFFER_SIZE];
                var builder = new StringBuilder();
                int len;

                while ((len = reader.Read(buffer, 0, BUFFER_SIZE)) > 0)
                {
                    builder.Append(buffer, 0, len);
                }

                return(builder.ToString());
            }
            finally
            {
                if (inputStream != null)
                {
                    inputStream.Close();
                }
                var httpConnection = connection as HttpURLConnection;
                if (httpConnection != null)
                {
                    httpConnection.Disconnect();
                }
            }
        }
Exemplo n.º 9
0
        // Read predicted letter from device
        public async Task <string> ReadLetter()
        {
            try
            {
                var mReader = new InputStreamReader(cSocket.InputStream);
                var buffer  = new BufferedReader(mReader);
                if (buffer.Ready())
                {
                    char[] bcommand = new char[20];
                    await buffer.ReadAsync(bcommand);

                    string letter = new string(bcommand.Where(x => x != '\0').ToArray());
                    return(letter);
                }
                else
                {
                    return("#");
                }
            }
            catch
            {
                RunOnUiThread(() => Snackbar.Make(Window.DecorView.RootView, "Failed to get data :(", Snackbar.LengthShort).Show());
                return("");
            }
        }
Exemplo n.º 10
0
        public static string getMmsText(ContentResolver resolver, long id)
        {
            Android.Net.Uri partURI = Android.Net.Uri.Parse($"content://mms/part/{id}");
            StringBuilder   sb      = new StringBuilder(200);

            try
            {
                using (var input = resolver.OpenInputStream(partURI))
                {
                    if (input != null)
                    {
                        InputStreamReader isr    = new InputStreamReader(input, "UTF-8");
                        BufferedReader    reader = new BufferedReader(isr);
                        string            temp   = reader.ReadLine();
                        while (temp != null)
                        {
                            sb.Append(temp);
                            temp = reader.ReadLine();
                        }
                    }
                }
            }
            catch
            {
            }

            return(sb.ToString());
        }
Exemplo n.º 11
0
 /// <summary>Reads a value from the buffer that uses the Ice 2.0 encoding. This value cannot contain classes or
 /// exceptions.</summary>
 /// <typeparam name="T">The type of the value.</typeparam>
 /// <param name="buffer">The byte buffer.</param>
 /// <param name="reader">The <see cref="InputStreamReader{T}"/> that reads the value from the buffer using an
 /// <see cref="InputStream"/>.</param>
 /// <param name="communicator">The communicator (optional).</param>
 /// <param name="connection">The connection (optional).</param>
 /// <param name="proxy">The proxy (optional).</param>
 /// <returns>The value read from the buffer.</returns>
 /// <exception name="InvalidDataException">Thrown when <c>reader</c> finds invalid data or <c>reader</c> leaves
 /// unread data in the buffer.</exception>
 /// <remarks>When reading proxies, communicator, connection or proxy must be non-null.</remarks>
 public static T Read <T>(
     this ReadOnlyMemory <byte> buffer,
     InputStreamReader <T> reader,
     Communicator?communicator = null,
     Connection?connection     = null,
     IObjectPrx?proxy          = null) =>
 buffer.Read(Encoding.V20, reader, communicator, connection, proxy);
Exemplo n.º 12
0
        public static void saveWifiTxt(string src, string desc)
        {
            byte[] LINE_END = Encoding.ASCII.GetBytes("\n");
            try
            {
                InputStreamReader isr = new InputStreamReader(new System.IO.FileStream(src, System.IO.FileMode.OpenOrCreate), getCharset(src));
                BufferedReader    br  = new BufferedReader(isr);

                FileOutputStream fout = new FileOutputStream(desc, true);
                string           temp;
                while ((temp = br.ReadLine()) != null)
                {
                    byte[] bytes = Encoding.ASCII.GetBytes(temp);
                    fout.Write(bytes);
                    fout.Write(LINE_END);
                }
                br.Close();
                fout.Close();
            }
            catch (FileNotFoundException e)
            {
                e.PrintStackTrace();
            }
            catch (IOException e)
            {
                e.PrintStackTrace();
            }
        }
Exemplo n.º 13
0
        /**
         * 获取Raw下的文件内容
         *
         * @param context
         * @param resId
         * @return 文件内容
         */
        public static string getFileFromRaw(Context context, int resId)
        {
            if (context == null)
            {
                return(null);
            }

            StringBuilder s = new StringBuilder();

            try
            {
                InputStreamReader inStream = new InputStreamReader(context.Resources.OpenRawResource(resId));
                BufferedReader    br       = new BufferedReader(inStream);
                string            line;
                while ((line = br.ReadLine()) != null)
                {
                    s.Append(line);
                }
                return(s.ToString());
            }
            catch (IOException e)
            {
                e.PrintStackTrace();
                return(null);
            }
        }
Exemplo n.º 14
0
        public static string ToWebString(Uri u)
        {
            var w = new StringBuilder();

            try
            {
                var url    = new URL(u.ToString());
                var i      = new InputStreamReader(url.openStream());
                var reader = new BufferedReader(i);


                var line = reader.readLine();
                while (line != null)
                {
                    w.AppendLine(line);

                    line = reader.readLine();
                }
                reader.close();
            }
            catch
            {
                // oops
            }

            return(w.ToString());
        }
Exemplo n.º 15
0
        void StartNode()
        {
            Trace.WriteLine("Node starting ...");

            // Light client
            nodeProcess = StartProcess($"{nodeBinPath} -d {nodeBasePath} --chain={nodeChainSpecPath} --light --no-prometheus --no-telemetry");
            // Full node - Should give the possibility to run either light or full node in the UI
            //nodeProcess = StartProcess($"{nodeBinPath} -d {nodeBasePath} --chain={nodeChainSpecPath} --no-prometheus --no-telemetry");

            _ = Task.Factory.StartNew(async() =>
            {
                using var input  = new InputStreamReader(nodeProcess.ErrorStream);
                using var reader = new BufferedReader(input);

                bool ready = false;
                string line;
                while (!string.IsNullOrEmpty((line = reader.ReadLine())))
                {
                    if (!ready && line.Contains("idle", StringComparison.InvariantCultureIgnoreCase))
                    {
                        Toast.ShowShortToast("Node is ready.");
                        EventAggregator.GetEvent <NodeStatusEvent>().Publish(NodeStatus.NodeReady);
                        ready = true;
                    }
                    logs.OnNext(line);
                }
                reader.Close();
                await nodeProcess.WaitForAsync();
            }, TaskCreationOptions.LongRunning);
        }
Exemplo n.º 16
0
        private async Task <string> RunCommandAsync(string command)
        {
            try
            {
                var process = Runtime.GetRuntime().Exec(command);
                using var input  = new InputStreamReader(process.InputStream);
                using var reader = new BufferedReader(input);

                string line;
                var    output = new System.Text.StringBuilder();
                while (!string.IsNullOrEmpty(line = await reader.ReadLineAsync()))
                {
                    output.AppendLine(line);
                }
                reader.Close();
                await process.WaitForAsync();

                return(output.ToString());
            }
            catch (Java.IO.IOException e)
            {
                throw new RuntimeException(e);
            }
            catch (InterruptedException e)
            {
                throw new RuntimeException(e);
            }
        }
Exemplo n.º 17
0
        public static void Load(this Hashtable props, System.IO.Stream stream)
        {
            if (stream == null)
            {
                return;
            }
            using (var reader = new InputStreamReader((InputStream)stream, Encoding.UTF8))
            {
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if (!String.IsNullOrWhiteSpace(line) && !line.StartsWith("#"))
                    {
                        var parts = line.Split('=');
                        if (parts.Length != 2)
                        {
                            throw new InvalidOperationException("Properties must be key value pairs separated by an '='.");
                        }

                        if (!props.ContainsKey(parts[0]))
                        {
                            props.Add(parts[0], parts[1]);
                        }
                        else
                        {
                            props[parts[0]] = parts[1];
                        }
                    }
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// same as <seealso cref="#getWordSet(ResourceLoader, String, boolean)"/>,
        /// except the input is in snowball format.
        /// </summary>
        protected internal CharArraySet getSnowballWordSet(ResourceLoader loader, string wordFiles, bool ignoreCase)
        {
            assureMatchVersion();
            IList <string> files = splitFileNames(wordFiles);
            CharArraySet   words = null;

            if (files.Count > 0)
            {
                // default stopwords list has 35 or so words, but maybe don't make it that
                // big to start
                words = new CharArraySet(luceneMatchVersion, files.Count * 10, ignoreCase);
                foreach (string file in files)
                {
                    InputStream stream = null;
                    TextReader  reader = null;
                    try
                    {
                        stream = loader.openResource(file.Trim());
                        CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
                        reader = new InputStreamReader(stream, decoder);
                        WordlistLoader.getSnowballWordSet(reader, words);
                    }
                    finally
                    {
                        IOUtils.closeWhileHandlingException(reader, stream);
                    }
                }
            }
            return(words);
        }
Exemplo n.º 19
0
        public Reader reader()
        {
            InputStreamReader inputStreamReader = new InputStreamReader();

            inputStreamReader._init_(read());
            return(inputStreamReader);
        }
Exemplo n.º 20
0
        private string DoGet()
        {
            var txtUsername = FindViewById <EditText>(Resource.Id.txt_login_name);
            var username    = txtUsername.Text;
            var password    = FindViewById <EditText>(Resource.Id.txt_login_pwd).Text;

            var result  = string.Empty;
            var url     = new URL(@"http://192.168.1.115:49152");
            var urlConn = url.OpenConnection() as HttpURLConnection;

            if (urlConn == null)
            {
                return(result);
            }
            try
            {
                var inStream     = new InputStreamReader(urlConn.InputStream);
                var bufferReader = new BufferedReader(inStream);
                var readLine     = string.Empty;
                while ((readLine = bufferReader.ReadLine()) != null)
                {
                    result += readLine;
                }
                inStream.Close();
                urlConn.Disconnect();
            }
            catch (Exception ex)
            {
            }
            return(result);
        }
Exemplo n.º 21
0
        public Reader reader(Java.Lang.String encoding)
        {
            InputStreamReader inputStreamReader = new InputStreamReader();

            inputStreamReader._init_(read(), encoding);
            return(inputStreamReader);
        }
        /// <summary>
        /// Read the list of languages supported by language detection.
        /// </summary>
        /// <returns> Returns a dictionary that
        /// stores the country name and language code of the ISO 639-1.
        /// </returns>
        private Dictionary <string, string> ReadNationAndCode()
        {
            Dictionary <string, string> nationMap         = new Dictionary <string, string>();
            InputStreamReader           inputStreamReader = null;

            try
            {
                Stream inputStream = this.Assets.Open("Country_pair_new.txt");
                inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            }
            catch (Exception e)
            {
                Log.Info(TranslatorActivity.Tag, "Read Country_pair_new.txt failed.");
            }
            BufferedReader reader = new BufferedReader(inputStreamReader);
            string         line;

            try
            {
                while ((line = reader.ReadLine()) != null)
                {
                    string[] nationAndCodeList = line.Split(" ");
                    if (nationAndCodeList.Length == 2)
                    {
                        nationMap.Add(nationAndCodeList[1], nationAndCodeList[0]);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Info(TranslatorActivity.Tag, "Read Country_pair_new.txt line by line failed.");
            }
            return(nationMap);
        }
        public string ReadFromFile(string fileName)
        {
            var ret = "";

            try
            {
                var inputStream = context.OpenFileInput(fileName);

                if (inputStream != null)
                {
                    var inputStreamReader = new InputStreamReader(inputStream);
                    var bufferedReader = new BufferedReader(inputStreamReader);
                    var receiveString = "";
                    var stringBuilder = new StringBuilder();

                    while ((receiveString = bufferedReader.ReadLine()) != null)
                    {
                        stringBuilder.Append(receiveString);
                    }

                    inputStream.Close();
                    ret = stringBuilder.ToString();
                }
            }
            catch (FileNotFoundException e)
            {
                Log.Debug("Exception", "File not found: " + e.ToString());
            }
            catch (IOException e)
            {
                Log.Debug("Exception", "Can not read file: " + e.ToString());
            }

            return ret;
        }
Exemplo n.º 24
0
        /// <summary>
        /// Builds a document from the content of the web response.
        /// A warning is logged if an exception is thrown while parsing the XML content
        /// (for instance when the content is not a valid XML and can't be parsed).
        /// @throws IOException if the page could not be created
        /// @throws SAXException if the parsing fails
        /// @throws ParserConfigurationException if a DocumentBuilder cannot be created
        /// </summary>
        /// <param name="WebResponse">the response from the server</param>
        /// <returns>the parse result</returns>
        public static XmlDocument BuildDocument(WebResponse webResponse)
        {
            XmlDocument xml = new XmlDocument();

            if (webResponse == null)
            {
                return(xml);
            }

            InputStreamReader reader = new InputStreamReader(webResponse.GetContentAsStream(), Encoding.GetEncoding(webResponse.GetContentCharset()));

            // we have to do the blank input check and the parsing in one step
            TrackBlankContentReader tracker = new TrackBlankContentReader(reader);

            try
            {
                xml.Load(tracker);
                return(xml);
            }
            catch (XmlException e)
            {
                if (tracker.WasBlank)
                {
                    return(new XmlDocument());
                }
                throw e;
            }
        }
Exemplo n.º 25
0
 /// <exception cref="System.IO.FileNotFoundException"/>
 public OfflineEditsXmlLoader(OfflineEditsVisitor visitor, FilePath inputFile, OfflineEditsViewer.Flags
                              flags)
 {
     this.visitor    = visitor;
     this.fileReader = new InputStreamReader(new FileInputStream(inputFile), Charsets.
                                             Utf8);
     this.fixTxIds = flags.GetFixTxIds();
 }
Exemplo n.º 26
0
 /// <summary>Reads the arguments from a request.</summary>
 /// <paramtype name="T">The type of the arguments.</paramtype>
 /// <param name="communicator">The communicator.</param>
 /// <param name="reader">The delegate used to read the arguments.</param>
 /// <returns>The request arguments.</returns>
 public T ReadArgs <T>(Communicator communicator, InputStreamReader <T> reader)
 {
     if (HasCompressedPayload)
     {
         DecompressPayload();
     }
     return(Payload.AsReadOnlyMemory().ReadEncapsulation(Protocol.GetEncoding(), communicator, reader));
 }
Exemplo n.º 27
0
 public OutgoingRequestWithEmptyParamList(string operationName,
                                          bool idempotent,
                                          InputStreamReader <TReturnValue> reader)
     : base(reader)
 {
     _operationName = operationName;
     _idempotent    = idempotent;
 }
Exemplo n.º 28
0
            static async Task <TReturnValue> ReadReturnValueAsync(
                ValueTask <IncomingResponseFrame> task,
                Communicator communicator,
                InputStreamReader <TReturnValue> reader)
            {
                IncomingResponseFrame response = await task.ConfigureAwait(false);

                return(response.ReadReturnValue(communicator, reader));
            }
Exemplo n.º 29
0
        private void waitForKey()
        {
            this.printer.println("\n PRESS ENTER KEY TO CONTINUE...");
            InputStreamReader converter = new InputStreamReader(this.input);

            BufferedReader in = new BufferedReader(converter);
            try {
                in.readLine();
            } catch (IOException e) {
Exemplo n.º 30
0
        /// <summary>Reads the request frame parameter list.</summary>
        /// <param name="reader">An InputStreamReader delegate used to read the request frame
        /// parameters.</param>
        /// <returns>The request parameters, when the frame parameter list contains multiple parameters
        /// they must be return as a tuple.</returns>
        public T ReadParamList <T>(InputStreamReader <T> reader)
        {
            var istr = new InputStream(_communicator, Payload);

            istr.StartEncapsulation();
            T paramList = reader(istr);

            istr.EndEncapsulation();
            return(paramList);
        }
Exemplo n.º 31
0
 public void Invoke(string operation,
                    bool idempotent,
                    bool oneway,
                    IReadOnlyDictionary <string, string>?context,
                    bool synchronous,
                    InputStreamReader <T>?read = null)
 {
     Read = read;
     base.Invoke(operation, idempotent, oneway, context, synchronous);
 }
Exemplo n.º 32
0
 private void openDeviceConnection(BluetoothDevice btDevice)
 {
     try
     {
         mSocket = btDevice.CreateRfcommSocketToServiceRecord(getUUIDFromString());
         mSocket.Connect();
         mStream = mSocket.InputStream;
         mReader = new InputStreamReader(mStream);
     }
     catch (IOException e)
     {
         throw e;
     }
 }
Exemplo n.º 33
0
        /// <summary> Default constructor: sets up the Velocity
        /// Runtime, creates the visitor for traversing
        /// the node structure and then produces the
        /// visual representation by the visitation.
        /// </summary>
        public TemplateNodeView(System.String template)
        {
            try {
            RuntimeSingleton.init("velocity.properties");

            System.IO.StreamReader isr = new InputStreamReader(new System.IO.FileStream(template, System.IO.FileMode.Open, System.IO.FileAccess.Read), RuntimeSingleton.getString(RuntimeSingleton.INPUT_ENCODING))
            ;

            //UPGRADE_ISSUE: The equivalent of constructor 'java.io.BufferedReader.BufferedReader' is incompatible with the expected type in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1109"'
            System.IO.StreamReader br = new System.IO.StreamReader(isr.BaseStream);

            document = RuntimeSingleton.parse(br, template)
            ;

            visitor = new NodeViewMode();
            visitor.Context = null;
            //UPGRADE_ISSUE: The equivalent of parameter java.lang.System.out is incompatible with the expected type in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1109"'
            visitor.Writer = new System.IO.StreamWriter(System.Console.Out);
            document.jjtAccept(visitor, null);
            } catch (System.Exception e) {
            System.Console.Out.WriteLine(e);
            SupportClass.WriteStackTrace(e, Console.Error);
            }
        }
Exemplo n.º 34
0
        private static string readFile(File file, char[] buffer)
        {
            StringBuilder outFile = new StringBuilder();
            try {

            int read;
            Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8");

            do {
              read = reader.Read(buffer, 0, buffer.Length);
              if (read > 0) {
                outFile.Append(buffer, 0, read);
              }
            }
            while (read >= 0);

            reader.Close();
            }
            catch(IOException io)
            {

            }
            return outFile.ToString();
        }
Exemplo n.º 35
0
        /// <summary>
        /// Download a string from the specified URI.
        /// </summary>
        public string DownloadString(URL address)
        {
            URLConnection connection = null;
            InputStream inputStream = null;
            try
            {
                connection = OpenConnection(address);
                inputStream = connection.InputStream;
                var reader = new InputStreamReader(inputStream);
                var buffer = new char[BUFFER_SIZE];
                var builder = new StringBuilder();
                int len;                

                while ((len = reader.Read(buffer, 0, BUFFER_SIZE)) > 0)
                {
                    builder.Append(buffer, 0, len);
                }

                return builder.ToString();
            }
            finally
            {
                if (inputStream != null)
                    inputStream.Close();
                var httpConnection = connection as HttpURLConnection;
                if (httpConnection != null)
                    httpConnection.Disconnect();
            }
        }
Exemplo n.º 36
0
 /** Constructor. */
 public irParser(/* java.io.Reader */ InputStreamReader stream)
 {
     if (jj_initialized_once)
     {
         Console.Out.WriteLine("ERROR: Second call to constructor of static parser. ");
         Console.Out.WriteLine("       You must either use ReInit() or set the JavaCC option STATIC to false");
         Console.Out.WriteLine("       during parser generation.");
         throw new Error();
     }
     jj_initialized_once = true;
     jj_input_stream = new SimpleCharStream(stream, 1, 1);
     token_source = new irParserTokenManager(jj_input_stream);
     token = new IrToken();
     jj_ntk = RegExpId.UNDEFINED;
     jj_gen = 0;
     for (int i = 0; i < 9; i++) jj_la1[i] = -1;
 }
Exemplo n.º 37
0
    /**
     * @param testBuf
     * @param cs
     */
    private static bool asciiMapsToBasicLatin(byte[] testBuf, Charset cs)
    {
        CharsetDecoder dec = cs.newDecoder();
        dec.onMalformedInput(CodingErrorAction.REPORT);
        dec.onUnmappableCharacter(CodingErrorAction.REPORT);
        Reader r = new InputStreamReader(new ByteArrayInputStream(testBuf), dec);
        try {
            for (int i = 0; i < 0x7F; i++) {
                if (isAsciiSupersetnessSensitive(i)) {
                    if (r.read() != i) {
                        return false;
                    }
                } else {
                    if (r.read() != 0x20) {
                        return false;
                    }
                }
            }
        } catch (IOException e) {
            return false;
        } catch (Exception e) {
            return false;
        } catch (CoderMalfunctionError e) {
            return false;
        }

        return true;
    }
 /// <summary>
 /// same as <seealso cref="#getWordSet(ResourceLoader, String, boolean)"/>,
 /// except the input is in snowball format. 
 /// </summary>
 protected internal CharArraySet getSnowballWordSet(ResourceLoader loader, string wordFiles, bool ignoreCase)
 {
     assureMatchVersion();
     IList<string> files = splitFileNames(wordFiles);
     CharArraySet words = null;
     if (files.Count > 0)
     {
         // default stopwords list has 35 or so words, but maybe don't make it that
         // big to start
         words = new CharArraySet(luceneMatchVersion, files.Count * 10, ignoreCase);
         foreach (string file in files)
         {
             InputStream stream = null;
             TextReader reader = null;
             try
             {
                 stream = loader.openResource(file.Trim());
                 CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
                 reader = new InputStreamReader(stream, decoder);
                 WordlistLoader.getSnowballWordSet(reader, words);
             }
             finally
             {
                 IOUtils.closeWhileHandlingException(reader, stream);
             }
         }
     }
     return words;
 }