Exemple #1
0
        private void ReadHeader(ILineReader lineReader)
        {
            // TODO: Cope with truncated headers
            string header1 = lineReader.ReadLine();

            string[] fields1 = header1.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            parameters.JNum = Int32.Parse(fields1[1]);
            parameters.IInc = Double.Parse(fields1[2]);
            parameters.JInc = Double.Parse(fields1[3]);

            string header2 = lineReader.ReadLine();

            string[] fields2 = header2.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            parameters.XOrigin = Double.Parse(fields2[0]);
            parameters.XMax    = Double.Parse(fields2[1]);
            parameters.YOrigin = Double.Parse(fields2[2]);
            parameters.YMax    = Double.Parse(fields2[3]);

            string header3 = lineReader.ReadLine();

            string[] fields3 = header3.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            parameters.INum        = Int32.Parse(fields3[0]);
            parameters.Orientation = Double.Parse(fields3[1]);
            // Two other unused fields here

            lineReader.ReadLine(); // Header 4 - Always seems to contain seven zeros

            parameters.VerifyAndCompleteParameters();
            parameters.Build(builder);
        }
Exemple #2
0
        public ObjReaderState(Obj obj, ILineReader reader)
        {
            Obj    = obj ?? throw new ArgumentNullException(nameof(obj));
            Reader = reader ?? throw new ArgumentNullException(nameof(reader));

            GroupNames = new List <string>();
        }
Exemple #3
0
        /// <inheritdoc />
        public EndCodeSearchResult FindEndCode(ILineReader reader)
        {
            var lastIndex  = reader.Line.Length - 1;
            var startIndex = reader.Index;

            for (; ;)
            {
                var match = _endCodeRegex.Match(reader.Line, startIndex);
                if (!match.Success)
                {
                    return(null);
                }

                var foundIndex = match.Index;
                if (foundIndex == lastIndex)
                {
                    return(foundIndex);
                }

                if (reader.Line[foundIndex + 1] != _endChar)
                {
                    return(foundIndex);
                }

                startIndex = foundIndex + 2;
            }
        }
Exemple #4
0
        // TODO: Factor this method out somhow - pass in grid
        //       parameters. Modify grid parameters to contain
        //       information on whether the grid is stored in
        //       RowMajor or ColumnMajor order, and in order ot
        //       increasing or decreasing I and J
        private void ReadRowMajorGrid(ILineReader lineReader)
        {
            Debug.Assert(parameters.INum.HasValue);
            string line;
            int    counter = 0;

            while ((line = lineReader.ReadLine()) != null)
            {
                string[] fields = line.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                //string[] fields = Patterns.Whitespace.Split(line.Trim());
                foreach (string field in fields)
                {
                    double z;
                    if (double.TryParse(field, out z))
                    {
                        if (z != parameters.ZNull)
                        {
                            int i = counter % parameters.INum.Value;
                            int j = counter / parameters.INum.Value;
                            builder[i, j] = -z; // Irap Classic is in depth
                        }
                        ++counter;
                    }
                    else
                    {
                        StringBuilder message = new StringBuilder();
                        message.AppendFormat("Bad grid data '{0}' at line {1}", field, lineReader.PhysicalLineNumber);
                        throw new OpenException(message.ToString());
                    }
                }
            }
        }
Exemple #5
0
        private ILineReader WriteSql(ILineReader reader)
        {
            var content = reader.ReadString(reader.Length);

            _context.OnBatchSql(new SqlBatchCollectorEventArgs(content, true));
            return(reader.Advance(reader.Length));
        }
Exemple #6
0
        private void ReadAsciiBody(ILineReader reader)
        {
            Debug.Assert(parameters.INum.HasValue);
            string line;
            int    counter = 0;

            while ((line = reader.ReadLine()) != null)
            {
                string[] fields = Regex.Split(line.Trim(), @"\s+");
                foreach (string field in fields)
                {
                    double z;
                    if (double.TryParse(field, out z))
                    {
                        if (z != parameters.ZNull && z >= parameters.ZMin && z <= parameters.ZMax)
                        {
                            int i = counter % parameters.INum.Value;
                            int j = counter / parameters.INum.Value;
                            builder[i, j] = z;
                        }
                        ++counter;
                    }
                    else
                    {
                        StringBuilder message = new StringBuilder();
                        message.AppendFormat("Bad grid data '{0}' at line {1}", field, reader.PhysicalLineNumber);
                        throw new OpenException(message.ToString());
                    }
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Constructs a new instance of Searcher.
        /// </summary>
        /// <param name="files">
        /// The list of files to search.
        /// </param>
        /// <param name="matcher">
        /// The <see cref="IFileMatcher"/> to obtain <see cref="FileMatch"/>es from.
        /// </param>
        /// <param name="reader">
        /// The <see cref="ILineReader"/> used to read lines from the file.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="files"/>, <paramref name="matcher"/>, or
        /// <paramref name="reader"/> are null.
        /// </exception>
        public Searcher(IEnumerable<string> files, IFileMatcher matcher, ILineReader reader)
        {
            if (files == null)
            {
                throw new ArgumentNullException("files");
            }

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

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

            _matches = new List<FileMatch>();

            _files = files;

            _matcher = matcher;

            _reader = reader;
        }
        private void ReadBody(ILineReader lineReader)
        {
            Debug.Assert(parameters.INum.HasValue);
            // Parse the body of the grid
            string line;
            int    counter = 0;

            while ((line = lineReader.ReadLine()) != null)
            {
                string[] fields = SplitOnWhitespace(line);
                foreach (string field in fields)
                {
                    double z;
                    if (double.TryParse(field, out z))
                    {
                        int i = counter / parameters.JNum.Value;
                        int j = parameters.JNum.Value - (counter % parameters.JNum.Value);
                        if (z != parameters.ZNull)
                        {
                            builder[i, j] = z;
                        }
                        ++counter;
                    }
                    else
                    {
                        StringBuilder message = new StringBuilder();
                        message.AppendFormat("Bad grid data '{0}' at line {1}", field, lineReader.PhysicalLineNumber);
                        throw new OpenException(message.ToString());
                    }
                }
            }
        }
Exemple #9
0
 private ILineReader WriteSql(ILineReader reader, RangeStart info)
 {
     if (info.Searcher.IsComment && _context.StripComments)
     {
         return(WriteSql(reader, info.Index, info.Searcher.StartCodeLength));
     }
     return(WriteSql(reader, info.Index + info.Searcher.StartCodeLength));
 }
 public TokenStream(ILineReader initialFile, IFileReader fileReader, ILogger logger)
 {
     this.fileReader = fileReader;
     this.logger     = logger;
     definitionsMap  = new Dictionary <string, Token[]>(StringComparer.OrdinalIgnoreCase);
     stack           = new Stack <ILineReader>();
     stack.Push(initialFile);
     ReadLine();
 }
Exemple #11
0
 public BlockDispatcher(
     IBlockBuilder blockBuilder,
     IDispatcher <Block> dispatcher,
     ILineReader lineReader)
 {
     this.blockBuilder = blockBuilder;
     this.dispatcher   = dispatcher;
     this.lineReader   = lineReader;
 }
Exemple #12
0
        public static string Find(this ILineReader reader, [Implicit] ICallContext context, string text, bool flushIfNotFound = false)
        {
            System.Diagnostics.Debug.WriteLine("Reader.Find: " + text);
            reader.DebugDump();
            //if (context != null && context.LoggingEnabled) context.Logger.Log("Find", "\"" + text + "\"");
            var comparer = StringUtils.CreateComparer(text);

            return(Find(reader, context, comparer, flushIfNotFound));
        }
Exemple #13
0
        /// <inheritdoc />
        public int FindStartCode(ILineReader reader)
        {
            var match = _startCodeRegex.Match(reader.Line, reader.Index);

            if (!match.Success)
            {
                return(-1);
            }
            return(match.Index);
        }
Exemple #14
0
        public static bool Matches(this ILineReader reader, Func <string, string> comparer)
        {
            ILineReaderEntry entry = reader.Current;

            if (entry == null)
            {
                return(false);
            }
            return(comparer(entry.Text) != null);
        }
        /// <inheritdoc />
        public SpecialTokenInfo Find(ILineReader reader)
        {
            var match = _regex.Match(reader.Line);

            if (!match.Success)
            {
                return(null);
            }
            return(new SpecialTokenInfo(match.Index, match.Length, match.Value));
        }
Exemple #16
0
        /// <inheritdoc />
        public EndCodeSearchResult FindEndCode(ILineReader reader)
        {
            var match = _endCodeRegex.Match(reader.Line, reader.Index);

            if (!match.Success)
            {
                return(null);
            }
            return(match.Index);
        }
Exemple #17
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="SearchStatus" /> class
 /// </summary>
 /// <param name="context">The search context</param>
 /// <param name="reader">The reader to be read from</param>
 /// <param name="activeRanges">The stack of active ranges</param>
 /// <param name="foundToken">The found special token</param>
 private SearchStatus(SearchContext context,
                      ILineReader reader,
                      Stack <IRangeSearcher> activeRanges,
                      SpecialTokenInfo foundToken)
 {
     _context      = context;
     _reader       = reader;
     _activeRanges = activeRanges;
     _foundToken   = foundToken;
 }
Exemple #18
0
        public LfdReader(ILineReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            this.reader     = reader;
            this.context    = new Stack <LfdLine>();
            this.lineNumber = 0;
        }
Exemple #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SearchStatus"/> class
 /// </summary>
 /// <param name="context">The search context</param>
 /// <param name="reader">The reader to be read from</param>
 /// <param name="activeRanges">The stack of active ranges</param>
 /// <param name="foundToken">The found special token</param>
 private SearchStatus(
     [NotNull] SearchContext context,
     [NotNull] ILineReader reader,
     [NotNull, ItemNotNull] Stack <IRangeSearcher> activeRanges,
     [CanBeNull] SpecialTokenInfo foundToken)
 {
     _context      = context;
     _reader       = reader;
     _activeRanges = activeRanges;
     _foundToken   = foundToken;
 }
Exemple #20
0
        /// <summary>
        ///     Handle the case where a new range start sequence was found
        /// </summary>
        /// <param name="reader">The reader where the sequence was found</param>
        /// <param name="info">Information about the start sequence</param>
        /// <returns>A new search status</returns>

        private SearchStatus UseNewRange(ILineReader reader, RangeStart info)
        {
            var nextReader = WriteSql(reader, info);

            if (nextReader == null)
            {
                throw new InvalidOperationException($"Missing end of range ({info.Searcher.GetType().Name})");
            }
            _activeRanges.Push(info.Searcher);
            return(new SearchStatus(_context, nextReader, _activeRanges, null));
        }
Exemple #21
0
    public void Part1(ILineReader lines)
    {
        var(template, rules) = Parse(lines);

        var frequencies = CalculateFrequencies(template, 10, rules);

        var max = frequencies.Values.Max();
        var min = frequencies.Values.Min();

        Console.WriteLine(max - min);
    }
Exemple #22
0
        private ILineReader WriteSql(ILineReader reader, int itemIndex, int skipLength = 0)
        {
            var readLength  = itemIndex - reader.Index;
            var content     = reader.ReadString(readLength);
            var isEndOfLine = readLength == reader.Length;

            if (!string.IsNullOrEmpty(content) || isEndOfLine)
            {
                _context.OnBatchSql(new SqlBatchCollectorEventArgs(content, isEndOfLine));
            }
            return(reader.Advance(readLength + skipLength));
        }
Exemple #23
0
        private static string DetermineType(ILineReader lineReader)
        {
            string line = lineReader.ReadLine();

            if (line.StartsWith("@"))
            {
                string[] fields = line.Split(',');
                string   type   = fields[1].Trim();
                return(type);
            }
            return("Unknown");
        }
Exemple #24
0
        public static string Await(this ILineReader reader, [Implicit] ICallContext context, string text, TimeSpan timeout, bool removeFound = true)
        {
            System.Diagnostics.Debug.WriteLine("Reader.Await: " + text);
            if (context != null && context.LoggingEnabled)
            {
                context.Logger.Log("Await", "\"" + text + "\"");
            }
            var comparer = StringUtils.CreateComparer(text);

            reader.DebugDump();

            // If the reader has timestampe, set the timeout relative to the time of the current entry; otherwise just use current wall time.
            DateTime entry = (reader.LinesHaveTimestamp && reader.Current != null) ? reader.Current.Timestamp : DateTime.Now;

            // The time where the timeout expires.
            DateTime to = (timeout == TimeSpan.MaxValue) ? DateTime.MaxValue : entry + timeout;

            //bool sleep = false;
            do
            {
                var result = reader.Find(null, comparer, true);
                if (result != null)
                {
                    if (removeFound)
                    {
                        reader.Next();
                    }
                    return(result);
                }
                lock (reader.Sync)
                {
                    if (reader.Current == null)
                    {
                        Monitor.Wait(reader.Sync, 50);
                    }
                }
                //sleep = true;
            } while (DateTime.Now.TimeTill(to) > TimeSpan.Zero);

            if ((context as IScriptCallContext) != null)
            {
                var ctx        = context as IScriptCallContext;
                var readerName = reader.Source.Name;
                if (readerName == null)
                {
                    readerName = "log reader";
                }
                ctx.ReportFailure($"No entry matching \"{text}\" was found in {readerName}.");
            }
            return(null);
        }
Exemple #25
0
 private ILineReader WriteSql(ILineReader reader, IRangeSearcher searcher,
                              EndCodeSearchResult info)
 {
     if (searcher.IsComment && _context.StripComments)
     {
         var length = info.Index - reader.Index + searcher.EndCodeLength;
         if (length == reader.Length)
         {
             _context.OnBatchSql(new SqlBatchCollectorEventArgs(string.Empty, true));
         }
         return(reader.Advance(length));
     }
     return(WriteSql(_reader, info.Index + searcher.EndCodeLength));
 }
Exemple #26
0
        private async IAsyncEnumerable <string> GetProcessedLinesAsync(ILineReader reader)
        {
            string?line;

            while ((line = await reader.ReadLineAsync()) != null)
            {
                var processResult = _patcher.Process(line);

                if (processResult.LineAction != LineAction.Remove)
                {
                    yield return(processResult.Line);
                }
            }
        }
Exemple #27
0
        /// <summary>
        ///     Search for the start of a range
        /// </summary>
        /// <param name="reader">The reader where the range start token should be searched in</param>
        /// <param name="searchers">The collection of searchers to test</param>
        /// <returns><c>null</c> when no range could be found</returns>

        private static RangeStart FindRangeStart(ILineReader reader,
                                                 IEnumerable <IRangeSearcher> searchers)
        {
            RangeStart result = null;

            foreach (var searcher in searchers)
            {
                var index = searcher.FindStartCode(reader);
                if (index != -1 && (result == null || result.Index > index))
                {
                    result = new RangeStart(searcher, index);
                }
            }
            return(result);
        }
Exemple #28
0
        /// <summary>
        ///     Search a special token
        /// </summary>
        /// <param name="reader">The reader where the token should be searched in</param>
        /// <param name="searchers">The collection of searchers to test</param>
        /// <returns><c>null</c> when no token could be found</returns>

        private static SpecialTokenInfo FindToken(ILineReader reader,
                                                  IEnumerable <ISpecialTokenSearcher> searchers)
        {
            SpecialTokenInfo result = null;

            foreach (var searcher in searchers)
            {
                var searcherResult = searcher.Find(reader);
                if (searcherResult != null && (result == null || result.Index > searcherResult.Index))
                {
                    result = searcherResult;
                }
            }
            return(result);
        }
Exemple #29
0
        public async Task RunAsync(ILineReader reader, ILineWriter writer)
        {
            await using var enumerator = GetProcessedLinesAsync(reader).GetAsyncEnumerator();

            if (!await enumerator.MoveNextAsync())
            {
                return;
            }

            await writer.WriteAsync(enumerator.Current);

            while (await enumerator.MoveNextAsync())
            {
                await writer.AppendLineAsync(enumerator.Current);
            }
        }
Exemple #30
0
        /// <inheritdoc />
        public SpecialTokenInfo Find(ILineReader reader)
        {
            if (reader.Index != 0)
            {
                return(null);
            }
            var match = _regex.Match(reader.Line);

            if (!match.Success)
            {
                return(null);
            }
            var token      = match.Groups["statement"].Value;
            var count      = GetGoCount(match) ?? 1;
            var parameters = new GoSearcherParameters(count);

            return(new SpecialTokenInfo(0, reader.Line.Length, token, parameters));
        }
Exemple #31
0
 public LogReader(ILineReader LineReader, IStringMatcher LogPrefixMatcher, IStringMatcher DiscardLogMatcher)
 {
     if (LogPrefixMatcher == null)
     {
         throw new ArgumentNullException("LogPrefixMatcher");
     }
     if (LineReader == null)
     {
         throw new ArgumentNullException("LineReader");
     }
     if (DiscardLogMatcher == null)
     {
         throw new ArgumentNullException("DiscardLogMatcher");
     }
     this.lineReader        = LineReader;
     this.logPrefixMatcher  = LogPrefixMatcher;
     this.discardLogMatcher = DiscardLogMatcher;
 }