Parse and digest capture script output.
979677
def process_casperjs_stdout(stdout):
    
    for line in stdout.splitlines():
        bits = line.split(':', 1)
        if len(bits) < 2:
            bits = ('INFO', bits)
        level, msg = bits

        if level == 'FATAL':
            logger.fatal(msg)
            raise CaptureError(msg)
        elif level == 'ERROR':
            logger.error(msg)
        else:
            logger.info(msg)
286834
def extract_value_from_output(canary, split_offset, kal_out):
    
    retval = ""
    while retval == "":
        for line in kal_out.splitlines():
            if canary in line:
                retval = str(line.split()[split_offset])
        if retval == "":
            retval = None
    return retval
434095
function parse(contents, retained, parser) {
    var errors = [], data = [], lines = 0;

    // optional parser
    if (!parser) parser = JSON;

    // process each line of the file
    contents.toString().split('\n').forEach(function(line) {
        if (!line) return;
        lines++;
        try {
            data.push(parser.parse(line));
        } catch (e) {
            e.line = line;
            errors.push(e);
        }
    });

    // if no errors/data, don't return an empty array
    var ret = {};
    if (errors.length) ret.errors = errors;
    if (data.length) ret.data = data;

    // if every line failed, probably not line-delimited
    if (errors.length == lines) ret.errors = retained;

    return ret;
}
769141
def _create_output_from_match(self, match_result):
        """"""
        full_path = match_result['full_path']
        path = self._get_relative_path(full_path)
        return LinterOutput(self.name, path, match_result['msg'])
1166798
def _parse (self):
        """"""

        feedparser = FeedParser (Message)
        binarychunks = {}
        sizeinfo = None
        headxml = None
        self.fp.seek (0, 0)

        while True:
            data = self.fp.readline ()
            if not data:
                break

            feedparser.feed (data)

            skip = (data == '\n' and
                    len (feedparser._msgstack) == 3 and
                    feedparser._msgstack[-1].get_content_type () in ('application/octet-stream',
                                                                     'binary/octet-stream'))
            if skip:
                # We just finished reading the headers for a huge binary blob.
                # Time to remember where the data chunk is and pretend it doesn't
                # exist.
                msg = feedparser._msgstack[-1]
                ident = msg['Content-Location']
                assert ident.endswith ('.bin'), 'confusion #1 in hacky MIME parsing!'
                binarychunks[ident] = self.fp.tell ()
                if sizeinfo is None:
                    headxml, sizeinfo, tagpfx = _extract_size_info (feedparser)
                kind = ident.split ('/')[-1]
                assert kind in sizeinfo, 'no size info for binary chunk kind %s in MIME!' % kind
                self.fp.seek (sizeinfo[kind] + 1, 1) # skip ahead by data chunk size
                sample = self.fp.read (16)
                assert sample.startswith ('--MIME'), 'crap, unexpected chunk size in MIME parsing: %r' % sample
                self.fp.seek (-16, 1) # go back

            # check that two major kinds of data are read at least once
            if any([k.split('/')[3] == '3' for k in binarychunks.iterkeys()]):
                break

        if headxml is None:
            raise RuntimeError ('never found any binary data')

        self.mimemsg = feedparser.close ()
        self.headxml = headxml
        self.sizeinfo = sizeinfo
        self.binarychunks = binarychunks

        headsize, intsize = self.calc_intsize()

        # Compute some miscellaneous parameters that we'll need.
#        self.n_integrations = len (self.mimemsg.get_payload ()) - 1
        self.n_integrations = os.stat(self.fp.name).st_size/intsize
        self.n_antennas = int (headxml.find (tagpfx + nanttag).text)
        self.n_baselines = (self.n_antennas * (self.n_antennas - 1)) // 2

        ds = headxml.find (tagpfx + dstag)
        nbb = 0
        nspw = 0
        nchan = 0
        crosspolstr = None

        for bb in ds.findall (tagpfx + basebandtag):
            nbb += 1

            for spw in bb.getchildren ():
                nspw += 1
                nchan += int (spw.get ('numSpectralPoint'))

                if crosspolstr is None:
                    crosspolstr = spw.get ('crossPolProducts')
                elif spw.get ('crossPolProducts') != crosspolstr:
                    raise Exception ('can only handle spectral windows with identical cross pol products')

        self.n_basebands = nbb
        self.n_spws = nspw
        self.n_channels = nchan
        self.crosspols = crosspolstr.split ()
        self.n_pols = len(self.crosspols)

        # if bdf info pkl not present, write it
        if os.path.exists(os.path.dirname(self.pklname)) and self.pklname and (not os.path.exists(self.pklname)):
            logger.info('Writing bdf pkl info to %s...' % (self.pklname))
            with open(self.pklname,'wb') as pkl:
                # Compute some miscellaneous parameters that we'll need.
                pickle.dump( (self.mimemsg, self.headxml, self.sizeinfo, self.binarychunks, self.n_integrations, self.n_antennas, self.n_baselines, self.n_basebands, self.n_spws, self.n_channels, self.crosspols), pkl)

        return self
805218
def read(src):
	''
	parser, buff_agg = Parser(), ''
	while True:
		buff = parser.read(src)
		if not buff: break # EOF
		buff_agg += buff
		while True:
			buff_agg, ev = parser.process(buff_agg)
			if ev is None: break
			yield ev
1365149
def read(self):
        """"""

        for line in self.io.read():
            with self.parse_line(line) as j:
                yield j
703617
def captures(self, uuid, withTitles=False):
        """"""
        picker = lambda x: x.get('capture', [])
        return self._get((uuid,), picker, withTitles='yes' if withTitles else 'no')
637436
def parse_xmlsec_output(output):
    
    for line in output.splitlines():
        if line == 'OK':
            return True
        elif line == 'FAIL':
            raise XmlsecError(output)
    raise XmlsecError(output)
43648
def dump(self):
        """"""
        text = ''

        for result in self.objects:
            if result.is_failure or result.is_error:
                text += '\n#{red}#{bright}'
                text += '{}\n'.format(''.ljust(79, '='))

                status = 'FAILED' if result.is_failure else 'ERROR'
                text += '{}: {}\n'.format(status, result.process)
                text += '{}\n#{{reset_all}}'.format(''.ljust(79, '='))

                if result.output:
                    text += result.output

                if result.error:
                    if result.output:
                        text += '\n{}\n'.format(''.ljust(79, '-'))
                        text += 'Additional error output:\n'
                        text += '{}\n'.format(''.ljust(79, '-'))
                    text += result.error

                if not text.endswith('\n'):
                    text += '\n'

        if self.has_modified_files:
            text += '\n#{{yellow}}#{{bright}}{}\n'.format(''.ljust(79, '-'))
            text += 'Modified files:\n'
            text += '{}\n'.format(''.ljust(79, '-'))
            for path, modified_by in self.modified_files:
                text += '#{{reset_all}}{} #{{cyan}}<- {}\n'.format(path, ', '.join(modified_by))

        return text
277864
function processZtagOutput(output) {
  return output.split('\n').reduce(function(memo, line) {
    var match, key, value;
      match = ztagRegex.exec(line);
      if(match) {
        key = match[1];
        value = match[2];
        memo[key] = value;
      }
      return memo;
  }, {});
}
709089
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
            knowledge_base):
    """"""
    _ = stderr, time_taken, args, knowledge_base  # Unused.
    self.CheckReturn(cmd, return_val)
    result = rdf_protodict.AttributedDict()
    for entry in self._field_parser.ParseEntries(stdout):
      line_str = " ".join(entry)
      mount_rslt = self.mount_re.match(line_str)
      if mount_rslt:
        device, mount_point, fs_type, option_str = mount_rslt.groups()
        result = rdf_client_fs.Filesystem()
        result.device = device
        result.mount_point = mount_point
        result.type = fs_type
        # Parse these options as a dict as some items may be key/values.
        # KeyValue parser uses OrderedDict as the native parser method. Use it.
        options = KeyValueParser(term=",").ParseToOrderedDict(option_str)
        # Keys without values get assigned [] by default. Because these keys are
        # actually true, if declared, change any [] values to True.
        for k, v in iteritems(options):
          options[k] = v or [True]
        result.options = rdf_protodict.AttributedDict(**options)
        yield result
314970
def get_scripts():
    """"""
    proc = Popen(['npm', 'run-script'], stdout=PIPE)
    should_yeild = False
    for line in proc.stdout.readlines():
        line = line.decode()
        if 'available via `npm run-script`:' in line:
            should_yeild = True
            continue

        if should_yeild and re.match(r'^  [^ ]+', line):
            yield line.strip().split(' ')[0]
954667
def output_hook(output)
      idx = output.index(COMMAND_PREFIX)
      return yield output.gsub(@prompt, '') if idx.nil?

      yield output.slice!(0, idx)
      cmd, args = output.slice(COMMAND_PREFIX.size..-1).split(' ', 2)
      # only support ruby and pry now.
      return yield output unless %w[ruby pry rsource].include?(cmd)

      args = case cmd
             when 'pry' then '__send__(:invoke_pry)'
             when 'rsource' then File.read(File.expand_path(args.strip))
             else args
             end
      args = '__send__(:invoke_pry)' if cmd == 'pry'
      # gdb by default set tty
      # hack it
      `stty opost onlcr`
      begin
        eval_context.instance_eval(args)
      rescue StandardError, ScriptError => e
        $stdout.puts("#{e.class}: #{e}")
      end
      @tube.puts('END')
      @tube.readuntil(@prompt)
      nil
    end
278614
def captured_output(stream_name):
    
    orig_stdout = getattr(sys, stream_name)
    setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout))
    try:
        yield getattr(sys, stream_name)
    finally:
        setattr(sys, stream_name, orig_stdout)
610594
function parseResult(text, callback) {
  var errors = [], i = 0, l, errBlock, match, match2, lines;

  text = text.replace(/\r/g, '');
  lines = text.split('\n');

  match = skippingRegex.exec(lines[i]);
  if (match) {
    i++;
  }

  match = successRegex.exec(lines[i]);
  if (match) {
    callback(null, createParseSuccessObj(match));
    return;
  }

  for (l = lines.length; i < l; i++) {
    match = fileRegex.exec(lines[i]);
    if (match) {
      match2 = errorRegex.exec(lines[++i]);
      errBlock = createFailObj(match);
      for (var j = i; match2 && j < lines.length;) {
        errBlock.errors.push(createErrorObj(match2));
        match2 = errorRegex.exec(lines[++j]);
      }
      i = --j;
      errors.push(errBlock);
    } else {
      match = abstractRegex.exec(lines[i]);
      if (match) {
        callback(createErrorGJSLintFailed(match, errors));
        return;
      }
    }
  }
  callback(createParseErrorUnknown(lines));

}
284597
def get_output(script):
    
    if six.PY2:
        logs.warn('Experimental instant mode is Python 3+ only')
        return None

    if 'THEFUCK_OUTPUT_LOG' not in os.environ:
        logs.warn("Output log isn't specified")
        return None

    if const.USER_COMMAND_MARK not in os.environ.get('PS1', ''):
        logs.warn(
            "PS1 doesn't contain user command mark, please ensure "
            "that PS1 is not changed after The Fuck alias initialization")
        return None

    try:
        with logs.debug_time(u'Read output from log'):
            fd = os.open(os.environ['THEFUCK_OUTPUT_LOG'], os.O_RDONLY)
            buffer = mmap.mmap(fd, const.LOG_SIZE_IN_BYTES, mmap.MAP_SHARED, mmap.PROT_READ)
            _skip_old_lines(buffer)
            lines = _get_output_lines(script, buffer)
            output = '\n'.join(lines).strip()
            logs.debug(u'Received output: {}'.format(output))
            return output
    except OSError:
        logs.warn("Can't read output log")
        return None
    except ScriptNotInLog:
        logs.warn("Script not found in output log")
        return None