Exemplo n.º 1
0
        /// <summary>
        /// Seeks the first character of a specified line in the text stream.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="line">Line number. The current position is assumed to be line #1.</param>
        /// <returns>
        /// Returns <c>true</c> if the line is found, <b>false</b> otherwise.
        /// </returns>
        public static bool SeekLine(TextReader reader, int line)
        {
            ContractUtils.RequiresNotNull(reader, "reader");
            if (line < 1) throw new ArgumentOutOfRangeException("line");
            if (line == 1) return true;

            int current_line = 1;

            for (; ; ) {
                int c = reader.Read();

                if (c == '\r') {
                    if (reader.Peek() == '\n') {
                        reader.Read();
                    }

                    current_line++;
                    if (current_line == line) return true;

                } else if (c == '\n') {
                    current_line++;
                    if (current_line == line) return true;
                } else if (c == -1) {
                    return false;
                }
            }
        }
Exemplo n.º 2
0
 public static DataTable Parse(TextReader stream, bool headers)
 {
     DataTable table = new DataTable();
     CsvStream csv = new CsvStream(stream);
     string[] row = csv.GetNextRow();
     if (row == null)
         return null;
     if (headers)
     {
         foreach (string header in row)
         {
             if (header != null && header.Length > 0 && !table.Columns.Contains(header))
                 table.Columns.Add(header, typeof(string));
             else
                 table.Columns.Add(GetNextColumnHeader(table), typeof(string));
         }
         row = csv.GetNextRow();
     }
     while (row != null)
     {
         while (row.Length > table.Columns.Count)
             table.Columns.Add(GetNextColumnHeader(table), typeof(string));
         table.Rows.Add(row);
         row = csv.GetNextRow();
     }
     return table;
 }
Exemplo n.º 3
0
        public override object Deserialize(TextReader tr)
        {
            if (tr != null)
            {
                string value = tr.ReadToEnd();

                ICalendarObject co = SerializationContext.Peek() as ICalendarObject;
                if (co != null)
                {
                    EncodableDataType dt = new EncodableDataType();
                    dt.AssociatedObject = co;
                    value = Decode(dt, value);
                }

                value = TextUtil.Normalize(value, SerializationContext).ReadToEnd();

                try
                {
                    Uri uri = new Uri(value);
                    return uri;
                }
                catch
                {
                }
            }
            return null;
        }
Exemplo n.º 4
0
    /// <summary>Parse the input X# source code file and generate the matching target assembly
    /// language.</summary>
    /// <param name="aReader">X# source code reader.</param>
    /// <returns>The resulting target assembler content. The returned object contains
    /// a code and a data block.</returns>
    public Assembler Generate(TextReader aReader)
    {
      if (aReader == null)
      {
        throw new ArgumentNullException(nameof(aReader));
      }
      mPatterns.EmitUserComments = EmitUserComments;
      mLineNo = 0;
      var xResult = new Assembler();
      try
      {
        // Read one X# source code line at a time and process it.
        while (true)
        {
          mLineNo++;
          string xLine = aReader.ReadLine();
          if (xLine == null)
          {
            break;
          }

          ProcessLine(xLine, mLineNo);
        }
        AssertLastFunctionComplete();
        return xResult;
      }
      finally
      {
        Assembler.ClearCurrentInstance();
      }
    }
Exemplo n.º 5
0
        public BufferedCharReader(TextReader reader, int bufferSize)
        {
            Debug.Assert(reader != null);

            _reader = reader;
            _bufferSize = Math.Max(256, bufferSize);
        }
Exemplo n.º 6
0
 public static DataTable Parse(TextReader stream, bool Headers, char delimiter)
 {
     if (Headers)
         return Parse(stream, CsvHeadersAction.UseAsColumnNames, delimiter);
     else
         return Parse(stream, CsvHeadersAction.UseAsContent, delimiter);
 }
Exemplo n.º 7
0
 public static DataTable Parse(TextReader stream, CsvHeadersAction Headers, char delimiter)
 {
     DataTable table = new DataTable();
     CsvStream csv = new CsvStream(stream);
     string[] row = csv.GetNextRow(delimiter);
     if (row == null)
         return null;
     if (Headers == CsvHeadersAction.SkipHeaderLine)
     {
         row = csv.GetNextRow(delimiter);
     }
     if (Headers == CsvHeadersAction.UseAsColumnNames)
     {
         //foreach (string header in row)
         for (int i = 0;i<row.Length;i++)
         {
             if (row[i] != null && row[i].Length > 0 && !table.Columns.Contains(row[i]))
                 table.Columns.Add(row[i], typeof(string));
             else
                 table.Columns.Add(GetNextColumnHeader(table), typeof(string));
         }
         row = csv.GetNextRow(delimiter);
     }
     while (row != null)
     {
         while (row.Length > table.Columns.Count)
             table.Columns.Add(GetNextColumnHeader(table), typeof(string));
         table.Rows.Add(row);
         row = csv.GetNextRow(delimiter);
     }
     stream.Close();
     stream.Dispose();
     return table;
 }
Exemplo n.º 8
0
        public override TokenStream TokenStream(string fieldName, TextReader reader)
        {
            string str = reader.ReadToEnd();
            StringBuilder builder = new StringBuilder(str);
            builder.Replace('.', ' ');
            builder.Replace('<', ' ');
            builder.Replace('>', ' ');
            builder.Replace('[', ' ');
            builder.Replace(']', ' ');
            builder.Replace('(', ' ');
            builder.Replace(')', ' ');
            builder.Replace(',', ' ');

            builder.Replace("  ", " ");

            str = builder.ToString();
            
            for (int i = builder.Length - 1; i > 0; i--)
            {
                if (char.IsUpper(builder[i]))
                    builder.Insert(i, ' ');
            }

            builder.Append(' ').Append(str);

            return new LowerCaseFilter(new WhitespaceTokenizer(new StringReader(builder.ToString())));
        }
Exemplo n.º 9
0
        public void BasicProgram()
        {
            _codeReader = new StringReader("var a, b;\r\nfunc foo() { console.log('in foo.'); }\nif(true) foo(); for(var i = 0; i < 10; i++)\t log(i); do {/*comment*/}// more comment\n while(false); var x = true ? false : null;");

            Tokenizer tokenizer = new Tokenizer();
            tokenizer.Initialize(new SourceUnit(_languageContext, _textContentProvider, "C:\\A\\Fake\\Path.txt", SourceCodeKind.File));

            foreach (var token in new Token[] { Token.VarToken, new NameToken("a"), Token.CommaToken, new NameToken("b"), Token.SemicolonToken,
                Token.FuncToken, new NameToken("foo"), Token.LeftParenthesisToken, Token.RightParenthesisToken,
                Token.LeftBraceToken, new NameToken("console"), Token.Dot, new NameToken("log"),
                Token.LeftParenthesisToken, new ConstantValueToken("in foo."), Token.RightParenthesisToken,
                Token.SemicolonToken, Token.RightBraceToken, Token.IfToken,
                Token.LeftParenthesisToken, new ConstantValueToken(true), Token.RightParenthesisToken,
                new NameToken("foo"), Token.LeftParenthesisToken, Token.RightParenthesisToken, Token.SemicolonToken,
                Token.ForToken, Token.LeftParenthesisToken, Token.VarToken, new NameToken("i"), Token.AssignToken,
                new ConstantValueToken(0), Token.SemicolonToken, new NameToken("i"),
                Token.LessThanToken, new ConstantValueToken(10), Token.SemicolonToken, new NameToken("i"), Token.IncrementToken, Token.RightParenthesisToken,
                new NameToken("log"), Token.LeftParenthesisToken, new NameToken("i"), Token.RightParenthesisToken, Token.SemicolonToken, 
                Token.DoToken, Token.LeftBraceToken, Token.RightBraceToken, Token.WhileToken, Token.LeftParenthesisToken, new ConstantValueToken(false),
                Token.RightParenthesisToken, Token.SemicolonToken,
                Token.VarToken, new NameToken("x"), Token.AssignToken, new ConstantValueToken(true), Token.QuestionmarkToken, new ConstantValueToken(false), Token.ColonToken, new ConstantValueToken(null), Token.SemicolonToken,
                Token.EndOfFile })

                token.Should().Equal(tokenizer.GetNextToken());
        }
Exemplo n.º 10
0
		bool raise_on_number_error; // FIXME: use it

		public JavaScriptReader (TextReader reader, bool raiseOnNumberError)
		{
			if (reader == null)
				throw new ArgumentNullException ("reader");
			this.r = reader;
			raise_on_number_error = raiseOnNumberError;
		}
Exemplo n.º 11
0
 /// <summary>
 /// �ִʴ��������캯��
 /// </summary>
 /// <param name="input">�ı���ȡ��</param>
 public ThesaurusSpliter(TextReader input)
 {
     this.input = input;
     //����������.ģ�����뷨���������Ĺ���
     assoStream = new AssociateStream();
     ReadBuffer();
 }
Exemplo n.º 12
0
 public void SaveConsoleIn()
 {
     originalIn = Console.In;
     originalOut = Console.Out;
     currentOut = new StringWriter();
     Console.SetOut(currentOut);
 }
Exemplo n.º 13
0
        public WireshackReader(string file)
        {
            if (!File.Exists(file)) throw new Exception("File not found!");

            fs = new FileStream(file, FileMode.Open);
            reader = new StreamReader(fs);
        }
Exemplo n.º 14
0
        public override Sector Parse(TextReader reader)
        {
            Sector sector = new Sector();

            StringBuilder accum = new StringBuilder();
            while (true)
            {
                string line = reader.ReadLine();
                if (line == null)
                    break;
                if (Regex.IsMatch(line, @"^\s*$"))
                    continue;
                if (Regex.IsMatch(line, @"^\s*#"))
                    continue;
                if (Char.IsWhiteSpace(line[0]))
                {
                    accum.Append(" ");
                    accum.Append(Regex.Replace(line, @"^\s+", ""));
                    continue;
                }

                if (accum.Length > 0)
                    Apply(accum.ToString(), sector);

                accum.Clear();
                accum.Append(line);
            }
            if (accum.Length > 0)
            {
                Apply(accum.ToString(), sector);
            }

            return sector;
        }
Exemplo n.º 15
0
        // Main parser
        internal WsdlParser(TextReader input, String outputDir, ArrayList outCodeStreamList, String locationURL, bool bWrappedProxy, String proxyNamespace)
        {
            Util.Log("WsdlParser.WsdlParser outputDir "+outputDir+" locationURL "+locationURL+" bWrappedProxy "+bWrappedProxy+" proxyNamespace "+proxyNamespace);
            // Initialize member variables
            _XMLReader = null;
            _readerStreamsWsdl = new ReaderStream(locationURL);
            _readerStreamsWsdl.InputStream = input;
            _writerStreams = null;
            _outputDir = outputDir;
            _outCodeStreamList = outCodeStreamList;
            _bWrappedProxy = bWrappedProxy;
            if (proxyNamespace == null || proxyNamespace.Length == 0)
                _proxyNamespace = "InteropNS";
            else
                _proxyNamespace = proxyNamespace;
            if (outputDir == null)
                outputDir = ".";

            int length = outputDir.Length;
            if (length > 0)
            {
                char endChar = outputDir[length-1];
                if (endChar != '\\' && endChar != '/')
                    _outputDir = _outputDir + '\\';
            }
            //_namespaceStack = null;
            _URTNamespaces = new ArrayList();
            _blockDefault = SchemaBlockType.ALL;
            _primedNametable = CreatePrimedNametable();
            
        }
Exemplo n.º 16
0
        public void Evaluate(IDictionary<string, object> context, TextReader input, TextWriter output)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (output == null)
            {
                throw new ArgumentNullException("output");
            }

            var vctx = this.CreateVelocityContext(context);

            //执行渲染
            var successed = this.engine.Evaluate(vctx, output, "VelocityTextTemplateEngine", input);
            output.Flush();

            if (!successed)
            {
                throw new TemplateException("Failed to render template");
            }
        }
Exemplo n.º 17
0
 public XsvReader(TextReader reader, string commentString = null)
 {
     if (reader == null)
     { throw new ArgumentNullException("reader"); }
     this.BaseReader = reader;
     this.CommentString = commentString;
 }
Exemplo n.º 18
0
		public static WSABooParser CreateParser(int tabSize, string readerName, TextReader reader, Boo.Lang.Parser.ParserErrorHandler errorHandler)
		{
			var parser = new WSABooParser(CreateBooLexer(tabSize, readerName, reader));
			parser.setFilename(readerName);
			parser.Error += errorHandler;
			return parser;
		}
Exemplo n.º 19
0
        static TextWriter tw; //= new StreamReader("A-small-attempt3.in");

        #endregion Fields

        #region Methods

        static void Main(string[] args)
        {
            tr = new StreamReader("C-large-1.in");

            int n = Convert.ToInt16(tr.ReadLine());
            List<TestCase> testCases = new List<TestCase>();

            for (; i < n; i++)
            {
                TestCase t = new TestCase();
                string[] temp2 = tr.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                //string[] temp2 = temp.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                t.lowLimit = Convert.ToInt64(temp2[0]);
                t.upperLimit = Convert.ToInt64(temp2[1]);
                testCases.Add(t.processInput());

            }
            tw = new StreamWriter("output.txt");
            i = 0;
            for (; i < testCases.Count-1; i++)
            {
                tw.WriteLine("Case #{0}: {1}", (i + 1), testCases[i].output);
            }
            tw.Write("Case #{0}: {1}", (i + 1), testCases[i].output);
            tr.Close();
            tw.Close();
            //Console.ReadLine();
        }
Exemplo n.º 20
0
  public XmlConverter(TextReader rdr, XmlWriter writer, IPlatform platform)
  {
      this.rdr = rdr;
      this.writer = writer;
      this.platform = platform;
      this.parserState = new ParserState();
 }
Exemplo n.º 21
0
 /// <summary>
 /// Deserialize an IfcXml file to an iso_10303_28 object
 /// </summary>
 /// <param name="reader"></param>
 /// <exception cref="XmlException"></exception>
 /// <exception cref="InvalidOperationException"></exception>
 /// <returns></returns>
 public iso_10303 Deserialize(TextReader reader){
     if(reader == null)
         throw new ArgumentNullException("reader");
     
     iso_10303 deserializedUos;
     IfcXmlValidator validator;
     try{
         validator = new IfcXmlValidator( reader );
         
         deserializedUos = (iso_10303)serializer.Deserialize( validator.Reader );
         
     }catch(XmlException xe){
         logger.Error( String.Format(CultureInfo.InvariantCulture, "Deserialize failed: {0}", xe.Message) );
         throw;
     }catch(InvalidOperationException ioe){
         logger.Error(String.Format(CultureInfo.InvariantCulture, "Deserialize failed: {0}", ioe.Message));
         throw;
     }finally{
         reader.Close();
     }
     
     if(!validator.IsValid){
         StringBuilder warningBuilder = new StringBuilder();
         foreach(String warning in validator.Messages){
             warningBuilder.AppendLine( warning );
         }
         throw new XmlException(String.Format(CultureInfo.InvariantCulture, "Not valid IfcXml: {0}", warningBuilder.ToString()));
         
     }
     return deserializedUos;
 }
Exemplo n.º 22
0
		protected override void DoOpen (FileInfo info)
		{
			if (Extension == ".gz" || Extension == ".bz2" || Extension == ".lzma")
				GetCompressedInfoReader ();
			else
				reader = base.TextReader;
		}
Exemplo n.º 23
0
        public PuppetMasterForm()
        {
            InitializeComponent();

            //Inicializations
            puppet_master_history_TextBox.Text = "";
            dump_history_TextBox.Text = "";
            command_TextBox.Text = "";

            BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
            provider.TypeFilterLevel = TypeFilterLevel.Full;
            IDictionary props = new Hashtable();
            props["port"] = 8400;
            props["timeout"] = 200000;

            channel = new TcpChannel(props, null, provider);
            ChannelServices.RegisterChannel(channel, true);

            clients = new Dictionary<string, Tuple<string, ClientInterface>>();
            metadataServers = new Dictionary<string, Tuple<string, MetadataServerInterface>>();
            dataServers = new Dictionary<string, Tuple<string, DataServerInterface>>();

            clientStartPort = 8100;
            metadataServerStartPort = 8200;
            dataServerStartPort = 8300;

            script = null;
        }
Exemplo n.º 24
0
    void Start()
    {
        triviaFile = new FileInfo(Application.dataPath + "/trivia.txt");

        if (triviaFile != null && triviaFile.Exists) {
            reader = triviaFile.OpenText();
        } else {
            embedded = (TextAsset) Resources.Load("trivia_embedded", typeof (TextAsset));
            reader = new StringReader(embedded.text);
        }

        string lineOfText = "";
        int lineNumber = 0;

        while ( ( lineOfText = reader.ReadLine() ) != null ) {

            string question = lineOfText;
            int answerCount = Convert.ToInt32(reader.ReadLine());
            List<string> answers = new List<string>();
            for (int i = 0; i < answerCount; i++) {
                answers.Add(reader.ReadLine());
            }

            Trivia temp = new Trivia(question, answerCount, answers);

            triviaQuestions.Add(temp);
            lineNumber++;
        }

        SendMessage( "BeginGame" );
    }
Exemplo n.º 25
0
        internal OperatorScanner(TextReader reader, ErrorReporter reporter)
            : base(reader, reporter)
        {
            twoCharacterOperators = new Dictionary<char, IDictionary<char, Type>>();
            twoCharacterOperators[':'] = new Dictionary<char, Type>();
            twoCharacterOperators[':']['='] = typeof(AssignmentToken);

            twoCharacterOperators['.'] = new Dictionary<char, Type>();
            twoCharacterOperators['.']['.'] = typeof(RangeToken);

            singleCharacterOperators = new Dictionary<char, Type>();

            singleCharacterOperators.Add('+', typeof(PlusToken));
            singleCharacterOperators.Add('-', typeof(MinusToken));
            singleCharacterOperators.Add('*', typeof(MultiplyToken));
            singleCharacterOperators.Add('/', typeof(DivideToken));
            singleCharacterOperators.Add('<', typeof(LessThanToken));
            singleCharacterOperators.Add('=', typeof(ComparisonToken));
            singleCharacterOperators.Add('&', typeof(AndToken));
            singleCharacterOperators.Add('!', typeof(NotToken));
            singleCharacterOperators.Add(';', typeof(SemicolonToken));
            singleCharacterOperators.Add(':', typeof(ColonToken));
            singleCharacterOperators.Add('(', typeof(LParenToken));
            singleCharacterOperators.Add(')', typeof(RParenToken));
        }
Exemplo n.º 26
0
		public TemplateParser (string filename, TextReader input)
		{
			this.filename = filename;
			fileText = input.ReadToEnd ();
			StringReader reader = new StringReader (fileText);
			tokenizer = new TemplateTokenizer (reader);
		}
Exemplo n.º 27
0
        public int RunCommand(TextReader input, TextWriter output, string tenant, string[] args, Dictionary<string, string> switches)
        {
            try {
                tenant = tenant ?? "Default";

                var env = FindOrCreateTenant(tenant);

                var parameters = new CommandParameters {
                    Arguments = args,
                    Switches = switches,
                    Input = input,
                    Output = output
                };

                env.Resolve<ICommandManager>().Execute(parameters);

                return 0;
            }
            catch (Exception e) {
                for (int i = 0; e != null; e = e.InnerException, i++) {
                    if (i > 0) {
                        output.WriteLine("-------------------------------------------------------------------");
                    }
                    output.WriteLine("Error: {0}", e.Message);
                    output.WriteLine("{0}", e.StackTrace);
                }
                return 5;
            }
        }
Exemplo n.º 28
0
 private string AccumulatePartial(TextReader reader)
 {
     StringBuilder buffer = new StringBuilder();
     buffer.Append(">");
     do
     {
         reader.Read();
     }
     while(char.IsWhiteSpace((char)reader.Peek()));
     while(true)
     {
         var peek = (char)reader.Peek();
         if (peek == '}' || peek == '~' || char.IsWhiteSpace(peek))
         {
             break;
         }
         var node = reader.Read();
         if (node == -1)
         {
             throw new InvalidOperationException("Reached end of template before the expression was closed.");
         }
         else
         {
             buffer.Append((char)node);
         }
     }
     return buffer.ToString();
 }
Exemplo n.º 29
0
        private void Initialize(TextReader input)
        {
            rand = new Random();
            fortunes = new List<string>();

            StringBuilder sb = new StringBuilder();
            string line = input.ReadLine();
            while (line != null)
            {
                if (line == "%")
                {
                    if (sb.Length > 0)
                    {
                        fortunes.Add(sb.ToString());
                        sb.Clear();
                    }
                }
                else
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(' ');
                    }
                    sb.Append(line);
                }
                line = input.ReadLine();
            }
            if (sb.Length > 0)
            {
                fortunes.Add(sb.ToString());
            }
        }
Exemplo n.º 30
0
 public Instruction[] Parse(TextReader reader)
 {
     Token token;
     mReader = reader;
     mScratchpad = new List<Instruction>();
     mState = Idle;
     while(mState != null && ReadNextToken(out token)) {
         mState = mState(token);
         if (mState == null) {
             mReader = null;
             mBuilder.Length = 0;
             mScratchpad.Clear();
             mBlock.Clear();
             return null;
         }
     }
     mReader = null;
     var result = mScratchpad.ToArray();
     mBuilder.Length = 0;
     mScratchpad.Clear();
     if (mBlock.Count > 0) {
         mBlock.Clear();
         return null;
     }
     return result;
 }
Exemplo n.º 31
0
 public object FromJson(Type type, TextReader reader)
 {
     return JSON.Deserialize(reader, type);
 }
Exemplo n.º 32
0
 public InputReader(bool fromFile)
 {
     input = fromFile ? new StreamReader("input.txt") : Console.In;
 }
Exemplo n.º 33
0
        public static Boolean RunWithReadersAndWriters(this Process process, TimeSpan timeout, TextReader stdin, TextWriter stdout, TextWriter stderr)
        {
            ReaderToWriterThread stdinRWThread = null, stdoutRWThread = null, stderrRWThread = null;
            Thread stdinThread = null, stdoutThread = null, stderrThread = null;

            if (stdin != null)
            {
                process.StartInfo.UseShellExecute       = false;
                process.StartInfo.RedirectStandardInput = true;
            }
            if (stdout != null)
            {
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.RedirectStandardOutput = true;
            }
            if (stderr != null)
            {
                process.StartInfo.UseShellExecute       = false;
                process.StartInfo.RedirectStandardError = true;
            }

            process.Start();

            if (stdin != null)
            {
                stdinRWThread            = new ReaderToWriterThread(null, stdin, process.StandardInput);
                stdinThread              = new Thread(stdinRWThread.Run);
                stdinThread.IsBackground = true;
                stdinThread.Start();
            }
            if (stdout != null)
            {
                stdoutRWThread            = new ReaderToWriterThread(null, process.StandardOutput, stdout);
                stdoutThread              = new Thread(stdoutRWThread.Run);
                stdoutThread.IsBackground = true;
                stdoutThread.Start();
            }
            if (stderr != null)
            {
                stderrRWThread            = new ReaderToWriterThread(null, process.StandardOutput, stderr);
                stderrThread              = new Thread(stderrRWThread.Run);
                stderrThread.IsBackground = true;
                stderrThread.Start();
            }
            if (timeout == TimeSpan.Zero)
            {
                process.WaitForExit();
                if (stdinThread != null)
                {
                    stdinThread.Join();
                }
                if (stdoutThread != null)
                {
                    stdoutThread.Join();
                }
                if (stdoutThread != null)
                {
                    stdoutThread.Join();
                }
                return(true);
            }
            else
            {
                if (process.WaitForExit((int)timeout.TotalMilliseconds))
                {
                    if (stdinThread != null)
                    {
                        stdinThread.Join();
                    }
                    if (stdoutThread != null)
                    {
                        stdoutThread.Join();
                    }
                    if (stdoutThread != null)
                    {
                        stdoutThread.Join();
                    }
                    return(true);
                }
                else
                {
                    if (stdinRWThread != null)
                    {
                        stdinRWThread.StopLooping();
                    }
                    if (stdoutRWThread != null)
                    {
                        stdoutRWThread.StopLooping();
                    }
                    if (stderrRWThread != null)
                    {
                        stderrRWThread.StopLooping();
                    }
                    return(false);
                }
            }
        }
Exemplo n.º 34
0
        public void Load(TextReader reader, bool headersOnly = false)
        {
            _HeadersOnly = headersOnly;
            Headers      = null;
            Body         = null;

            if (headersOnly)
            {
                RawHeaders = reader.ReadToEnd();
            }
            else
            {
                var    headers = new StringBuilder();
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Trim().Length == 0)
                    {
                        if (headers.Length == 0)
                        {
                            continue;
                        }
                        else
                        {
                            break;
                        }
                    }
                    headers.AppendLine(line);
                }
                RawHeaders = headers.ToString();

                string boundary = Headers.GetBoundary();
                if (!string.IsNullOrEmpty(boundary))
                {
                    //else this is a multipart Mime Message
                    using (var subreader = new StringReader(line + Environment.NewLine + reader.ReadToEnd()))
                        ParseMime(subreader, boundary);
                }
                else
                {
                    SetBody((line + Environment.NewLine + reader.ReadToEnd()).Trim());
                }

                if (string.IsNullOrEmpty(Body) && Attachments != null && Attachments.Count > 0)
                {
                    var att = Attachments.FirstOrDefault(x => !x.IsAttachment && x.ContentType.Is("text/plain"));
                    if (att == null)
                    {
                        att = Attachments.FirstOrDefault(x => !x.IsAttachment && x.ContentType.Contains("html"));
                    }

                    if (att != null)
                    {
                        Body = att.Body;
                        ContentTransferEncoding = att.Headers["Content-Transfer-Encoding"].RawValue;
                        ContentType             = att.Headers["Content-Type"].RawValue;
                    }
                }
            }

            Date      = Headers.GetDate();
            To        = Headers.GetAddresses("To");
            Cc        = Headers.GetAddresses("Cc");
            Bcc       = Headers.GetAddresses("Bcc");
            Sender    = Headers.GetAddresses("Sender").FirstOrDefault();
            ReplyTo   = Headers.GetAddresses("Reply-To").FirstOrDefault();
            From      = Headers.GetAddresses("From").FirstOrDefault();
            MessageID = Headers["Message-ID"].RawValue;

            Importance = Headers.GetEnum <MailPriority>("Importance");
            Subject    = Headers["Subject"].RawValue;
        }
Exemplo n.º 35
0
        private int _rowIndex = 1; // 从第1行开始

        protected bool ParseReader(TextReader oReader)
        {
            // 首行
            var headLine = oReader.ReadLine();

            if (headLine == null)
            {
                OnException(TableFileExceptionType.HeadLineNull);
                return(false);
            }

            var metaLine = oReader.ReadLine(); // 声明行

            if (metaLine == null)
            {
                OnException(TableFileExceptionType.MetaLineNull);
                return(false);
            }

            //NOTE 如果第一行为null则会exception
            string[] firstLineSplitString = headLine.Split(_config.Separators, StringSplitOptions.None);  // don't remove RemoveEmptyEntries!

            var metaLineArr = metaLine.Split(_config.Separators, StringSplitOptions.None);

            string[] firstLineDef = new string[metaLineArr.Length];
            Console.WriteLine("headLine.length={0},headMeta.length={1}", firstLineSplitString.Length, metaLineArr.Length);
            Array.Copy(metaLineArr, 0, firstLineDef, 0, metaLineArr.Length);  // 拷贝,确保不会超出表头的

            for (int i = 0; i < firstLineSplitString.Length; i++)
            {
                var headerString = firstLineSplitString[i];

                var headerInfo = new HeaderInfo
                {
                    ColumnIndex = i,
                    HeaderName  = headerString,
                    HeaderMeta  = firstLineDef[i],
                };

                Headers[headerInfo.HeaderName] = headerInfo;
            }
            _colCount = firstLineSplitString.Length;  // 標題

            // 读取行内容

            string sLine = "";

            while (sLine != null)
            {
                sLine = oReader.ReadLine();
                if (sLine != null)
                {
                    string[] splitString1 = sLine.Split(_config.Separators, StringSplitOptions.None);

                    TabInfo[_rowIndex] = splitString1;

                    T newT = (T)Activator.CreateInstance(typeof(T), _rowIndex, Headers);  // the New Object may not be used this time, so cache it!

                    newT.Values = splitString1;

                    if (!newT.IsAutoParse)
                    {
                        newT.Parse(splitString1);
                    }
                    else
                    {
                        AutoParse(newT, splitString1);
                    }

                    if (newT.GetPrimaryKey() != null)
                    {
                        TableFileRow oldT;
                        if (!PrimaryKey2Row.TryGetValue(newT.GetPrimaryKey(), out oldT))  // 原本不存在,使用new的,释放cacheNew,下次直接new
                        {
                            PrimaryKey2Row[newT.GetPrimaryKey()] = newT;
                        }
                        else  // 原本存在,使用old的, cachedNewObj(newT)因此残留, 留待下回合使用
                        {
                            TableFileRow toT = oldT;
                            // Check Duplicated Primary Key, 使用原来的,不使用新new出来的, 下回合直接用_cachedNewObj
                            OnException(TableFileExceptionType.DuplicatedKey, toT.GetPrimaryKey().ToString());
                            newT = (T)toT;
                        }
                    }

                    Rows[_rowIndex] = newT;
                    _rowIndex++;
                }
            }

            return(true);
        }
Exemplo n.º 36
0
 public TextUI(ExtendedTextWriter writer, TextReader reader)
     : this(writer, reader, new NUnitLiteOptions()) { }
Exemplo n.º 37
0
 public TextUI(ExtendedTextWriter writer, TextReader reader, NUnitLiteOptions options)
 {
     _options = options;
     _writer = writer;
     _reader = reader;
 }
Exemplo n.º 38
0
        protected override Query[] PrepareQueries()
        {
            Analyzer anlzr = NewAnalyzerTask.CreateAnalyzer(m_config.Get("analyzer",
                                                                         "Lucene.Net.Analysis.Standard.StandardAnalyzer, Lucene.Net.Analysis.Common"));
            string      defaultField = m_config.Get("file.query.maker.default.field", DocMaker.BODY_FIELD);
            QueryParser qp           = new QueryParser(
#pragma warning disable 612, 618
                LuceneVersion.LUCENE_CURRENT,
#pragma warning restore 612, 618
                defaultField, anlzr);

            qp.AllowLeadingWildcard = true;

            List <Query> qq       = new List <Query>();
            string       fileName = m_config.Get("file.query.maker.file", null);

            if (fileName != null)
            {
                FileInfo   file   = new FileInfo(fileName);
                TextReader reader = null;
                // note: we use a decoding reader, so if your queries are screwed up you know
                if (file.Exists)
                {
                    reader = IOUtils.GetDecodingReader(file, Encoding.UTF8);
                }
                else
                {
                    //see if we can find it as a resource
                    Stream asStream = typeof(FileBasedQueryMaker).GetTypeInfo().Assembly.FindAndGetManifestResourceStream(typeof(FileBasedQueryMaker), fileName);
                    if (asStream != null)
                    {
                        reader = IOUtils.GetDecodingReader(asStream, Encoding.UTF8);
                    }
                }
                if (reader != null)
                {
                    try
                    {
                        string line    = null;
                        int    lineNum = 0;
                        while ((line = reader.ReadLine()) != null)
                        {
                            line = line.Trim();
                            if (line.Length != 0 && !line.StartsWith("#", StringComparison.Ordinal))
                            {
                                try
                                {
                                    qq.Add(qp.Parse(line));
                                }
                                catch (ParseException e)
                                {
                                    Console.Error.WriteLine("Exception: " + e.Message + " occurred while parsing line: " + lineNum + " Text: " + line);
                                }
                            }
                            lineNum++;
                        }
                    }
                    finally
                    {
                        reader.Dispose();
                    }
                }
                else
                {
                    Console.Error.WriteLine("No Reader available for: " + fileName);
                }
            }
            return(qq.ToArray());
        }
Exemplo n.º 39
0
        private static bool VerifyConfigHeader(TextReader reader)
        {
            string l = reader.ReadLine();

            return(l == GCConst.CONFIG_HEADER);
        }
Exemplo n.º 40
0
 public T FromJson<T>(TextReader reader)
 {
     return JSON.Deserialize<T>(reader);
 }
Exemplo n.º 41
0
 public Program(TextReader input, TextWriter output)
 {
     this.input  = input;
     this.output = output;
     scanner     = new Scanner(input);
 }
Exemplo n.º 42
0
        public static T ToObject <T> (TextReader reader)
        {
            JsonReader json_reader = new JsonReader(reader);

            return((T)ReadValue(typeof(T), json_reader));
        }
Exemplo n.º 43
0
 /**
  * Creates a new scanner
  * There is also a System.IO.Stream version of this constructor.
  *
  * @param   in  the System.IO.TextReader to read input from.
  */
 internal JrpcgenScanner(TextReader @in)
 {
     this.zzReader = @in;
 }
Exemplo n.º 44
0
        private static void LoadConfigFiles(string dir, InitialAction act)
        {
            if (Win32.WaitForSingleObject(_globalMutex, 10000) != Win32.WAIT_OBJECT_0)
            {
                throw new Exception("Global mutex lock error");
            }

            try {
                string optionfile    = dir + "options.conf";
                bool   config_loaded = false;
                bool   macro_loaded  = false;

                TextReader reader = null;
                try {
                    if (File.Exists(optionfile))
                    {
                        reader = new StreamReader(File.Open(optionfile, FileMode.Open, FileAccess.Read), Encoding.Default);
                        if (VerifyConfigHeader(reader))
                        {
                            ConfigNode root = new ConfigNode("root", reader).FindChildConfigNode("poderosa");
                            if (root != null)
                            {
                                _options.Load(root);
                                config_loaded = true;
                                _history.Load(root);
                                _macroManager.Load(root);
                                macro_loaded = true;
                            }
                        }
                    }
                }
                catch (Exception ex) {
                    //_errorOccurredOnBoot = true;
                    Debug.WriteLine(ex.StackTrace);
                    GUtil.WriteDebugLog(ex.StackTrace);
                    act.AddMessage("Failed to read the configuration file.\n" + ex.Message);
                }
                finally {
                    if (!config_loaded)
                    {
                        _options.Init();
                    }
                    if (!macro_loaded)
                    {
                        _macroManager.SetDefault();
                    }
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }

                GEnv.Options = _options;                 //これでDefaultRenderProfileが初期化される

                string kh = dir + "ssh_known_hosts";
                if (File.Exists(kh))
                {
                    try {
                        _sshKnownHosts.Load(kh);
                    }
                    catch (Exception ex) {
                        _sshKnownHosts.Clear();
                        act.AddMessage("Failed to read the 'ssh_known_hosts' file.\n" + ex.Message);
                    }
                }
            }
            finally {
                Win32.ReleaseMutex(_globalMutex);
            }
        }
Exemplo n.º 45
0
            public Edge(TextReader input)
            {
                var r = input.ReadInts();

                A = r[0] - 1; B = r[1] - 1;
            }
Exemplo n.º 46
0
 public Scanner(TextReader reader)
 {
     this.reader = reader;
 }
Exemplo n.º 47
0
        public override sealed TokenStreamComponents CreateComponents(string fieldName, TextReader aReader)
        {
            var wrappedAnalyzer = GetWrappedAnalyzer(fieldName);
            var component       = wrappedAnalyzer.CreateComponents(fieldName, aReader);

            return(WrapComponents(fieldName, component));
        }
Exemplo n.º 48
0
 public static T DeserializeFromReader <T>(TextReader reader)
 {
     return(DeserializeFromString <T>(reader.ReadToEnd()));
 }
Exemplo n.º 49
0
 public override TextReader InitReader(string fieldName, TextReader reader)
 {
     return(GetWrappedAnalyzer(fieldName).InitReader(fieldName, WrapReader(fieldName, reader)));
 }
Exemplo n.º 50
0
 public TestCase(TextReader input)
 {
     N     = input.ReadInts()[0];
     Edges = Enumerable.Range(0, N - 1).Select(i => new Edge(input)).ToArray();
 }
Exemplo n.º 51
0
 public static Dictionary <string, object> ReadCsdl(TextReader payload)
 {
     return(BuildElementJsonObject(XElement.Load(payload)));
 }
Exemplo n.º 52
0
 /// <summary>
 /// Wraps / alters the given Reader. Through this method AnalyzerWrappers can
 /// implement <seealso cref="#initReader(String, Reader)"/>. By default, the given reader
 /// is returned.
 /// </summary>
 /// <param name="fieldName">
 ///          name of the field which is to be analyzed </param>
 /// <param name="reader">
 ///          the reader to wrap </param>
 /// <returns> the wrapped reader </returns>
 protected virtual TextReader WrapReader(string fieldName, TextReader reader)
 {
     return(reader);
 }
Exemplo n.º 53
0
 public PeekingTextReader(TextReader reader)
 {
     _reader = reader;
 }
Exemplo n.º 54
0
 /// <summary>
 /// Opens the specified file.
 /// </summary>
 /// <param name="filename">The filename.</param>
 /// <returns></returns>
 public TextReader Open(string filename)
 {
     Reader = File.OpenText(filename);
     return(Reader);
 }
 public override object Deserialize(TextReader tr) => Deserialize(tr.ReadToEnd());
Exemplo n.º 56
0
        /// <summary>
        /// Creates
        /// <see cref="TokenStreamComponents"/>
        /// used to tokenize all the text in the provided <see cref="TextReader"/>.
        /// </summary>
        /// <returns> <see cref="TokenStreamComponents"/>
        ///         built from a <see cref="StandardTokenizer"/> filtered with
        ///         <see cref="StandardFilter"/>, <see cref="LowerCaseFilter"/>, <see cref="StopFilter"/>,
        ///         and <see cref="CzechStemFilter"/> (only if version is >= LUCENE_31). If
        ///         a version is >= LUCENE_31 and a stem exclusion set is provided via
        ///         <see cref="CzechAnalyzer(LuceneVersion, CharArraySet, CharArraySet)"/> a
        ///         <see cref="SetKeywordMarkerFilter"/> is added before
        ///         <see cref="CzechStemFilter"/>. </returns>

        protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
        {
            Tokenizer   source = new StandardTokenizer(m_matchVersion, reader);
            TokenStream result = new StandardFilter(m_matchVersion, source);

            result = new LowerCaseFilter(m_matchVersion, result);
            result = new StopFilter(m_matchVersion, result, m_stopwords);
#pragma warning disable 612, 618
            if (m_matchVersion.OnOrAfter(LuceneVersion.LUCENE_31))
#pragma warning restore 612, 618
            {
                if (this.stemExclusionTable.Count > 0)
                {
                    result = new SetKeywordMarkerFilter(result, stemExclusionTable);
                }
                result = new CzechStemFilter(result);
            }
            return(new TokenStreamComponents(source, result));
        }
Exemplo n.º 57
0
 public object FromJson(Type type, TextReader reader)
 {
     return(_serializer.Deserialize(new JsonTextReader(reader), type));
 }
Exemplo n.º 58
0
        private void SetupNodes(TextReader setupXmlReader)
        {
            XPathDocument     document;
            XPathNodeIterator linkIterator;
            Node              linkNode;
            string            linkNodeName;
            XPathNavigator    navigator;
            Node              node;
            XPathNodeIterator nodeIterator;
            string            nodeName;
            XPathExpression   linkNameExpression;

            document  = new XPathDocument(setupXmlReader);
            navigator = document.CreateNavigator();
            numBats   = Convert.ToInt32(navigator.Evaluate("sum(/Wumpus/Bats/@number)"));
            if (numBats < 1)
            {
                numBats = DEFAULT_BATS;
            }
            numPits =
                Convert.ToInt32(navigator.Evaluate("sum(/Wumpus/Pits/@number)"));
            if (numPits < 1)
            {
                numPits = DEFAULT_PITS;
            }

            linkNameExpression = navigator.Compile("Links/Link/@name");

            nodeIterator = navigator.Select("/Wumpus/Nodes/Node");
            while (nodeIterator.MoveNext())
            {
                nodeName = nodeIterator.Current.GetAttribute(
                    "name", string.Empty);
                if (nodeName != string.Empty)
                {
                    //Console.Write("{0}\n", nodeName);
                    node = nodes[nodeName] as Node;
                    if (node == null)
                    {
                        node            = new Node(nodeName);
                        nodes[nodeName] = node;
                    }
                    linkIterator =
                        nodeIterator.Current.Select(linkNameExpression);
                    while (linkIterator.MoveNext())
                    {
                        linkNodeName = linkIterator.Current.Value;
                        if (linkNodeName != string.Empty)
                        {
                            //Console.Write("\t{0}\n", linkNodeName);
                            linkNode = nodes[linkNodeName] as Node;
                            if (linkNode == null)
                            {
                                linkNode            = new Node(linkNodeName);
                                nodes[linkNodeName] = linkNode;
                            }
                            node.AddLinkedNode(linkNode);
                        }
                    }
                }
            }
        }
Exemplo n.º 59
0
 public T FromJson <T>(TextReader reader)
 {
     return(_serializer.Deserialize <T>(new JsonTextReader(reader)));
 }
Exemplo n.º 60
0
            protected override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
            {
                Tokenizer tokenizer = new KeywordTokenizer(reader);

                return(new TokenStreamComponents(tokenizer, new HindiStemFilter(tokenizer)));
            }