Find the raw event in string format from logFileContent based on character start index and end index.
331818
@Override
    public CloudTrailEventMetadata getMetadata(int charStart, int charEnd) {
        // Use Jackson getTokenLocation API only return the , (Comma) position, we need to advance to first open curly brace.
        String rawEvent = logFile.substring(charStart, charEnd+1);
        int offset = rawEvent.indexOf("{");
        rawEvent = rawEvent.substring(offset);
        CloudTrailEventMetadata metadata = new LogDeliveryInfo(ctLog, charStart + offset, charEnd, rawEvent);
        return metadata;
    }
815069
def find_next_character(code, position, char):
    """"""
    end = LineCol(code, *position)
    while not end.eof and end.char() in WHITESPACE:
        end.inc()

    if not end.eof and end.char() == char:
        return end.tuple(), inc_tuple(end.tuple())
    return None, None
147663
function (formatString, mapping) {
    var len = formatString.length;
    var i = 0;
    var startIndex = -1;
    var lastChar = null;
    var currentChar = "";
    var resultString = "";

    for (; i < len; i++) {
      currentChar = formatString.charAt(i);

      if (lastChar === null || lastChar !== currentChar) {
        // change detected
        resultString = _appendMappedString(formatString, mapping, startIndex, i, resultString);

        startIndex = i;
      }

      lastChar = currentChar;
    }

    return _appendMappedString(formatString, mapping, startIndex, i, resultString);
  }
582139
def parse_root(raw):
    ""
    if sys.version < '3':
        fp = StringIO(raw)
    else:
        fp = BytesIO(raw.encode('UTF-8'))
    for event, element in etree.iterparse(fp, events=('start',)):
        return (element.tag, element.attrib)
890772
def debug_dump(message, file_prefix="dump"):
    

    global index
    index += 1

    with open("%s_%s.dump" % (file_prefix, index), 'w') as f:
        f.write(message.SerializeToString())
        f.close()
329940
public static String getStringBefore(final String src, final String toSearch, final int start) {
		final int ind = src.indexOf(toSearch, start);
		if (ind == -1)
			return "";

		return src.substring(start, ind);
	}
1153912
def extract(self, content, output):
    """"""

    for table in self['tables']:

        # First apply default options.
        plugin_settings = DEFAULT_OPTIONS.copy()
        plugin_settings.update(table)
        table = plugin_settings

        # Validate settings
        assert 'start' in table, 'Table start regex missing'
        assert 'end' in table, 'Table end regex missing'
        assert 'body' in table, 'Table body regex missing'

        start = re.search(table['start'], content)
        end = re.search(table['end'], content)

        if not start or not end:
            logger.warning('no table body found - start %s, end %s', start, end)
            continue

        table_body = content[start.end(): end.start()]

        for line in re.split(table['line_separator'], table_body):
            # if the line has empty lines in it , skip them
            if not line.strip('').strip('\n') or not line:
                continue

            match = re.search(table['body'], line)
            if match:
                for field, value in match.groupdict().items():
                    # If a field name already exists, do not overwrite it
                    if field in output:
                        continue

                    if field.startswith('date') or field.endswith('date'):
                        output[field] = self.parse_date(value)
                        if not output[field]:
                            logger.error("Date parsing failed on date '%s'", value)
                            return None
                    elif field.startswith('amount'):
                        output[field] = self.parse_number(value)
                    else:
                        output[field] = value
            logger.debug('ignoring *%s* because it doesn\'t match anything', line)
169668
function LocationIndex(string) {
        // ensure newline termination
        if (string[string.length - 1] !== '\n') {
            string += '\n';
        }
        this._stringLength = string.length;
        /*
         * Each triple in _lineStartEndTriples consists of:
         * [0], the 0-based line index of the line the triple represents
         * [1], the 0-based code unit index (into the string) of the start of the line (inclusive)
         * [2], the 0-based code unit index (into the string) of the start of the next line (or the length of the string, if it is the last line)
         * A line starts with a non-newline character,
         * and always ends in a newline character, unless it is the very last line in the string.
         */
        this._lineStartEndTriples = [[0, 0]];
        var nextLineIndex = 1;
        var charIndex = 0;
        while (charIndex < string.length) {
            charIndex = string.indexOf('\n', charIndex);
            if (charIndex === -1) {
                /* istanbul ignore next */
                break;
            }
            charIndex++;// go past the newline
            this._lineStartEndTriples[this._lineStartEndTriples.length - 1].push(charIndex);
            this._lineStartEndTriples.push([nextLineIndex, charIndex]);

            nextLineIndex++;
        }
        this._lineStartEndTriples.pop();
    }
662581
def _parse_line(self, line):
        
        # first isolate the timestamp and the event type
        try:
            self._line_parsed = self._line_parsed + 1

            m = RE_LINE_REG.match(line)
            if m is None:
                m = RE_LINE_EXT.match(line)
            if m is None:
                return False
            self.log.debug("Matching line found %s" % line)
            (tstamp, event_type, remainder) = m.groups()
            tstamp = int(tstamp)

            # skip passive checks reports by default for spamminess
            if event_type == 'PASSIVE SERVICE CHECK' and not self.passive_checks:
                return False
            # then retrieve the event format for each specific event type
            fields = EVENT_FIELDS.get(event_type, None)
            if fields is None:
                self.log.warning("Ignoring unknown nagios event for line: %s" % (line[:-1]))
                return False
            elif fields is False:
                # Ignore and skip
                self.log.debug("Ignoring Nagios event for line: %s" % (line[:-1]))
                return False

            # and parse the rest of the line
            parts = [p.strip() for p in remainder.split(';')]
            # Chop parts we don't recognize
            parts = parts[: len(fields._fields)]

            event = self.create_event(tstamp, event_type, self.hostname, fields._make(parts), tags=self.tags)

            self._event(event)
            self.log.debug("Nagios event: %s" % (event))

            return True
        except Exception:
            self.log.exception("Unable to create a nagios event from line: [%s]" % (line))
            return False
132069
@SuppressWarnings("deprecation")
    public static CharStream of(final CharSequence str, final int startIndex, final int endIndex) {
        N.checkFromToIndex(startIndex, endIndex, N.len(str));

        if (N.isNullOrEmpty(str)) {
            return empty();
        }

        if (str instanceof String) {
            return of(StringUtil.getCharsForReadOnly((String) str), startIndex, endIndex);
        }

        final CharIteratorEx iter = new CharIteratorEx() {
            private int cursor = startIndex;

            @Override
            public boolean hasNext() {
                return cursor < endIndex;
            }

            @Override
            public char nextChar() {
                return str.charAt(cursor++);
            }

            @Override
            public long count() {
                return endIndex - cursor;
            }
        };

        return new IteratorCharStream(iter);
    }
27345
private static void getTreeFormat(StringBuffer sb, Event event, Boolean includeContextInfo,
			int noOfTabs, long currentNanoTime, int spacesRequiredForDuration) {
		//Defect 166820
		//Check for events that got added after we started dumping the tree.
		//We ignore these events.
		if(currentNanoTime < event.getStartTime()){
			return;
		}
		
		String executionTimeStr = getExecutionTimeStringFormat(currentNanoTime,
				event); // Convert the execution time into string with 3 decimal
						// places..
		try {
			/**
			 * If its root event add header to table and set the
			 * spacesRequiredForDuration field
			 */
			if (event.getParentEvent() == null) {
				if (spacesRequiredForDuration == 0)
					spacesRequiredForDuration = executionTimeStr.length() + 5;
				sb.append(appendHeader(event, executionTimeStr));
			}
			// Append the execution time
			if (event.getEndTime() == 0) {
				sb.append(String.format(
						"%n%" + spacesRequiredForDuration + "s",
						executionTimeStr + "ms + "));
			} else {
				sb.append(String.format(
						"%n%" + spacesRequiredForDuration + "s",
						executionTimeStr + "ms   "));
			}

			// Append tabs for Child Events
			if (event.getParentEvent() != null) {
				for (int i = 0; i < noOfTabs; i++) {
					sb.append("    ");
				}
			}

			// Append Type + Context information to string...
			if (includeContextInfo && event.getContextInfo() != null) {
				sb.append(event.getType()
						+ RequestProbeConstants.EVENT_CONTEXT_INFO_SEPARATOR
						+ event.getContextInfo());
			} else {
				sb.append(event.getType());
			}

			//Iterating using indices instead of the list iterator to avoid ConcurrentModificationException
			//It is safe to do it this way as we only add elements to the list
			List<Event> list = event.getChildEvents();
			for(int i = 0; i < list.size(); i++){
				//Defect 165134
				//for (Event eventChild : event.getChildEvents()) {
				// Call recursively for child events ..
				getTreeFormat(sb, list.get(i), includeContextInfo, noOfTabs + 1, currentNanoTime,
						spacesRequiredForDuration);
			}
		} catch (Exception e) {

			FFDCFilter.processException(e, EventStackFormatter.class.getName(),
					"94", event);
		}
	}
94740
def x(self):
        """"""
        self._log_after_del = False
        passed_string = self.string
        if self.log_func:
            self.log_func(self)
        else:
            print_info(
                "Timer [%(passed)s]: %(name)s, start at %(start)s."
                % (
                    dict(
                        name=self.name, start=ttime(self.start_at), passed=passed_string
                    )
                )
            )
        return passed_string
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
851216
def process_log_event(event, context):
    """"""
    init()
    serialized = event['awslogs'].pop('data')
    data = json.loads(zlib.decompress(
        base64.b64decode(serialized), 16 + zlib.MAX_WBITS))

    # Fetch additional logs for context (20s window)
    timestamps = [e['timestamp'] for e in data['logEvents']]
    start = min(timestamps) - 1000 * 15
    end = max(timestamps) + 1000 * 5

    events = logs.get_log_events(
        logGroupName=data['logGroup'],
        logStreamName=data['logStream'],
        startTime=start,
        endTime=end,
        startFromHead=True)['events']

    message = [
        "An error was detected",
        "",
        "Log Group: %s" % data['logGroup'],
        "Log Stream: %s" % data['logStream'],
        "Log Owner: %s" % data['owner'],
        "",
        "Log Contents",
        ""]

    # We may get things delivered from log sub that are not in log events
    for evt in data['logEvents']:
        if evt not in events:
            events.append(evt)

    for evt in events:
        message.append(message_event(evt))
        message.append("")

    params = dict(
        TopicArn=config['topic'],
        Subject=config['subject'],
        Message='\n'.join(message))

    sns.publish(**params)
360586
def recoverString(self, strIndex, withIndex=False):
        '''
        
        '''
        retNums = []
        indices = []
        
        #figure out the first hop backwards
        currIndex = strIndex
        prevChar = self.getCharAtIndex(currIndex)
        currIndex = self.getOccurrenceOfCharAtIndex(prevChar, currIndex)
        
        #while we haven't looped back to the start
        while currIndex != strIndex:
            #update the string
            retNums.append(prevChar)
            if withIndex:
                indices.append(currIndex)
        
            #figure out where to go from here
            prevChar = self.getCharAtIndex(currIndex)
            currIndex = self.getOccurrenceOfCharAtIndex(prevChar, currIndex)
        
        for i in xrange(0, self.vcLen):
            if strIndex < self.endIndex[i]:
                retNums.append(i)
                break
                
        if withIndex:
            indices.append(strIndex)
        
        #reverse the numbers, convert to characters, and join them in to a single sequence
        ret = ''.join(self.numToChar[retNums[::-1]])
        
        #return what we found
        if withIndex:
            return (ret, indices[::-1])
        else:
            return ret
245224
function stringEndsWith (str, val, startIndex) {
  var rest = '' + str
  return arguments.length === 1 ? rest.indexOf(val) === rest.length - 1 : rest.substring(0, startIndex).indexOf(val) === startIndex - 1
}
1114695
private XMLEvent nextEvent(String location) throws Exception {
        XMLEvent event = reader.nextEvent();
//        System.out.println(location + event.toString().replace('\n', ' ') + " " + event.getClass().getSimpleName());
        return event;
    }