read ahead without blocking and attempt to match the pattern
324097
private String waitForPattern(long timeout, TailLogBufferedReader bufferedReader, Pattern pattern, boolean searchWithinLines, long timeoutInSeconds) throws IOException {
        StringBuilder sb = new StringBuilder();
        String result;
        label:
        while(true) {
            while ( bufferedReader.ready() ) {
                int c = bufferedReader.read();
                if ( c != -1 ) {
                    if (c == '\n' || c == '\r') {
                        if (sb.length() > 0) {
                            Matcher m = pattern.matcher(sb);
                            boolean match = searchWithinLines ? m.find() : m.matches();
                            if (match) {
                                result = sb.toString();
                                break label;
                            } else {
                                sb.setLength(0);
                            }
                        }
                    } else {
                        sb.append((char) c);
                    }
                }
            }

            //nothing more to read, does the current output match the pattern?
            if ( sb.length() > 0 && searchWithinLines) {
                Matcher m = pattern.matcher(sb);
                if ( m.find() ) {
                    result = m.group(0);
                    break label;
                }
            }

            try {
                Thread.sleep(10); //avoid a busy loop since we are using nonblocking ready() / read()
            } catch (InterruptedException e) {}

            checkTimeout(timeout, timeoutInSeconds);

            if ( process.isStopped() && ! bufferedReader.ready()) {
                ChorusAssert.fail(
                        process.isExitWithFailureCode() ?
                                "Process stopped with error code " + process.getExitCode() + " while waiting for match" :
                                "Process stopped while waiting for match"
                );
            }
        }
        return result;
    }
1142755
def read_next_block(infile, block_size=io.DEFAULT_BUFFER_SIZE):
    """"""
    chunk = infile.read(block_size)

    while chunk:
        yield chunk

        chunk = infile.read(block_size)
696151
def _next_pattern(self):
        """"""
        current_state = self.state_stack[-1]
        position = self._position
        for pattern in self.patterns:
            if current_state not in pattern.states:
                continue

            m = pattern.regex.match(self.source, position)
            if not m:
                continue

            position = m.end()
            token = None

            if pattern.next_state:
                self.state_stack.append(pattern.next_state)

            if pattern.action:
                callback = getattr(self, pattern.action, None)
                if callback is None:
                    raise RuntimeError(
                        "No method defined for pattern action %s!" %
                        pattern.action)

                if "token" in m.groups():
                    value = m.group("token")
                else:
                    value = m.group(0)
                token = callback(string=value, match=m,
                                 pattern=pattern)

            self._position = position

            return token

        self._error("Don't know how to match next. Did you forget quotes?",
                    start=self._position, end=self._position + 1)
784693
function checkIfMatch(req, res, next) {
    var clientETags;
    var cur;
    var etag = res.etag || res.getHeader('etag') || '';
    var ifMatch;
    var matched = false;

    if ((ifMatch = req.headers['if-match'])) {

        clientETags = ifMatch.split(/\s*,\s*/);

        for (var i = 0; i < clientETags.length; i++) {
            cur = clientETags[i];

            // only strong comparison

            cur = cur.replace(/^W\//, '');
            cur = cur.replace(/^"(\w*)"$/, '$1');

            if (cur === '*' || cur === etag) {
                matched = true;
                break;
            }
        }

        if (!matched) {
            var err = new PreconditionFailedError(IF_MATCH_FAIL,
                ifMatch,
                etag);
            return (next(err));
        }
    }

    return (next());
}
608783
def get_pattern_context(pattern, index):
    """"""

    last = 0
    current_line = 1
    col = 1
    text = []
    line = 1

    # Split pattern by newline and handle the text before the newline
    for m in RE_PATTERN_LINE_SPLIT.finditer(pattern):
        linetext = pattern[last:m.start(0)]
        if not len(m.group(0)) and not len(text):
            indent = ''
            offset = -1
            col = index - last + 1
        elif last <= index < m.end(0):
            indent = '--> '
            offset = (-1 if index > m.start(0) else 0) + 3
            col = index - last + 1
        else:
            indent = '    '
            offset = None
        if len(text):
            # Regardless of whether we are presented with `\r\n`, `\r`, or `\n`,
            # we will render the output with just `\n`. We will still log the column
            # correctly though.
            text.append('\n')
        text.append('{}{}'.format(indent, linetext))
        if offset is not None:
            text.append('\n')
            text.append(' ' * (col + offset) + '^')
            line = current_line

        current_line += 1
        last = m.end(0)

    return ''.join(text), line, col
1366488
def process_text(self, kind, context):
		""""""
		
		result = None
		
		while True:
			chunk = yield None
			
			if chunk is None:
				if result:
					yield result.clone(line=repr(result.line))
				
				return
			
			if not result:
				result = chunk
				continue
			
			result.line += chunk.line
1196371
function lookahead (n) {
    let counter = current
    const target = current + n
    let res = ''
    while (counter < target) {
      res += input[++counter]
    }
    return res
  }
117244
void skipLine() {
        int ch;
        do {
            try {
                ch = reader.read();
            } catch( IOException ex ) {
                throw new LessException( ex );
            }
            incLineColumn( ch );
        } while( ch != '\n' && ch != -1 );
    }
1179418
def find_backwards(self, sub, in_current_line=False, ignore_case=False, count=1):
        
        if in_current_line:
            before_cursor = self.current_line_before_cursor[::-1]
        else:
            before_cursor = self.text_before_cursor[::-1]

        flags = re.IGNORECASE if ignore_case else 0
        iterator = re.finditer(re.escape(sub[::-1]), before_cursor, flags)

        try:
            for i, match in enumerate(iterator):
                if i + 1 == count:
                    return - match.start(0) - len(sub)
        except StopIteration:
            pass
695987
def findTextBackward(self, block, column, needle):
        
        if column is not None:
            index = block.text()[:column].rfind(needle)
        else:
            index = block.text().rfind(needle)

        if index != -1:
            return block, index

        for block in self.iterateBlocksBackFrom(block.previous()):
            column = block.text().rfind(needle)
            if column != -1:
                return block, column

        raise ValueError('Not found')
575126
def attempt_match
    matches_before = matches.length
    match_length_before = match_length
    (yield && match_length > match_length_before).tap do |success|  # match_length test returns failure if no progress is made (our source position isn't advanced)
      unless success
        @matches = matches[0..matches_before-1]
        update_match_length
      end
    end
  end
212904
def tee_lookahead(t, i):
    
    for value in islice(t.__copy__(), i, None):
        return value
    raise IndexError(i)
616032
def _iterateDocumentCharsForward(self, block, startColumnIndex):
        
        # Chars in the start line
        endTime = time.time() + self._MAX_SEARCH_TIME_SEC
        for columnIndex, char in list(enumerate(block.text()))[startColumnIndex:]:
            yield block, columnIndex, char
        block = block.next()

        # Next lines
        while block.isValid():
            for columnIndex, char in enumerate(block.text()):
                yield block, columnIndex, char

            if time.time() > endTime:
                raise _TimeoutException('Time is over')

            block = block.next()
234407
static private long skipForward(InputStream is, long toSkip)
                throws IOException {

        long eachSkip = 0;
        long skipped = 0;

        while (skipped != toSkip) {
            eachSkip = is.skip(toSkip - skipped);

            // check if EOF is reached
            if (eachSkip <= 0) {
                if (is.read() == -1) {
                    return skipped ;
                } else {
                    skipped++;
                }
            }
            skipped += eachSkip;
        }
        return skipped;
    }
1278551
def seek_line_forward(self):
        
        pos = start_pos = self.file.tell()

        bytes_read, read_str = self.read(self.read_size)

        start = 0
        if bytes_read and read_str[0] in self.line_terminators:
            # The first charachter is a line terminator, don't count this one
            start += 1

        while bytes_read > 0:          
            # Scan forwards, counting the newlines in this bufferfull
            i = start
            while i < bytes_read:
                if read_str[i] in self.line_terminators:
                    self.seek(pos + i + 1)
                    return self.file.tell()
                i += 1

            pos += self.read_size
            self.seek(pos)

            bytes_read, read_str = self.read(self.read_size)

        return None
46873
def match(self, context, line):
		""""""
		stripped = line.stripped
		return stripped.startswith('#') and not stripped.startswith('#{')
353002
protected void skipLinesAlreadyRead(Iterator it) {
        long linesRead = getItemsRead();
        if (linesRead > 0) {
            for (long i = 0; i < linesRead; i++) {
                if (it.hasNext()) {
                    it.next();
                }
            }
        }
    }