Parse molfile part into molecule object

    Args:
        lines (list): lines of molfile part

    Raises:
        ValueError: Symbol not defined in periodictable.yaml
                    (Polymer expression not supported yet)
975665
def molecule(lines):
    
    count_line = lines[3]
    num_atoms = int(count_line[0:3])
    num_bonds = int(count_line[3:6])
    # chiral_flag = int(count_line[12:15])  # Not used
    # num_prop = int(count_line[30:33])  # "No longer supported"
    compound = Compound()
    compound.graph._node = atoms(lines[4: num_atoms+4])
    compound.graph._adj = bonds(lines[num_atoms+4: num_atoms+num_bonds+4],
                                compound.graph._node.keys())
    props = properties(lines[num_atoms+num_bonds+4:])
    add_properties(props, compound)
    return compound
482791
def lines(self, lines):
        
        if self.cache_content:
            self.cached_content = ''.join([b2u(l) for l in lines])

        try:
            with self._open_dockerfile('wb') as dockerfile:
                dockerfile.writelines([u2b(l) for l in lines])
        except (IOError, OSError) as ex:
            logger.error("Couldn't write lines to dockerfile: %r", ex)
            raise
122148
def parse_line(line: str, char_index=0) -> Tuple[ListingType, str]:
    """"""

    entry_name = str.rpartition(line, ' ')[-1]
    entry_type = LISTING_FLAG_MAP.get(line[char_index], ListingType.other)
    return entry_type, entry_name
621026
def __parse(self, lines):
        

        # Every line in the file must consist of either a comment
        # or a key-value pair. A key-value pair is a line consisting
        # of a key which is a combination of non-white space characters
        # The separator character between key-value pairs is a '=',
        # ':' or a whitespace character not including the newline.
        # If the '=' or ':' characters are found, in the line, even
        # keys containing whitespace chars are allowed.

        # A line with only a key according to the rules above is also
        # fine. In such case, the value is considered as the empty string.
        # In order to include characters '=' or ':' in a key or value,
        # they have to be properly escaped using the backslash character.

        # Some examples of valid key-value pairs:
        #
        # key     value
        # key=value
        # key:value
        # key     value1,value2,value3
        # key     value1,value2,value3 \
        #         value4, value5
        # key
        # This key= this value
        # key = value1 value2 value3

        # Any line that starts with a '#' or '!' is considerered a comment
        # and skipped. Also any trailing or preceding whitespaces
        # are removed from the key/value.

        # This is a line parser. It parses the
        # contents like by line.

        lineno=0
        i = iter(lines)

        for line in i:
            lineno += 1
            line = line.strip()
            # Skip null lines
            if not line: continue
            # Skip lines which are comments
            if line[0] in ('#','!'): continue
            # Some flags
            escaped=False
            # Position of first separation char
            sepidx = -1
            # A flag for performing wspace re check
            flag = 0
            # Check for valid space separation
            # First obtain the max index to which we
            # can search.
            m = self.othercharre.search(line)
            if m:
                first, last = m.span()
                start, end = 0, first
                flag = 1
                wspacere = re.compile(r'(?<![\\\=\:])(\s)')
            else:
                if self.othercharre2.search(line):
                    # Check if either '=' or ':' is present
                    # in the line. If they are then it means
                    # they are preceded by a backslash.

                    # This means, we need to modify the
                    # wspacere a bit, not to look for
                    # : or = characters.
                    wspacere = re.compile(r'(?<![\\])(\s)')
                start, end = 0, len(line)

            m2 = wspacere.search(line, start, end)
            if m2:
                # print 'Space match=>',line
                # Means we need to split by space.
                first, last = m2.span()
                sepidx = first
            elif m:
                # print 'Other match=>',line
                # No matching wspace char found, need
                # to split by either '=' or ':'
                first, last = m.span()
                sepidx = last - 1
                # print line[sepidx]


            # If the last character is a backslash
            # it has to be preceded by a space in which
            # case the next line is read as part of the
            # same property
            while line[-1] == '\\':
                # Read next line
                nextline = next(i)
                nextline = nextline.strip()
                lineno += 1
                # This line will become part of the value
                line = line[:-1] + nextline

            # Now split to key,value according to separation char
            if sepidx != -1:
                key, value = line[:sepidx], line[sepidx+1:]
            else:
                key,value = line,''
            self._keyorder.append(key)
            self.process_pair(key, value)
1162594
def _process_line(self, line):
        
        fields = self._extract_fields(line)
        if not self._fields_valid(fields):
            self.log.warning("Missing required fields for line: {line}".format(
                line=line))

        metric_path_base = []
        graphite_prefix = fields.get('GRAPHITEPREFIX')
        graphite_postfix = fields.get('GRAPHITEPOSTFIX')

        if graphite_prefix:
            metric_path_base.append(graphite_prefix)

        hostname = fields['HOSTNAME'].lower()
        metric_path_base.append(hostname)

        datatype = fields['DATATYPE']
        if datatype == 'HOSTPERFDATA':
            metric_path_base.append('host')
        elif datatype == 'SERVICEPERFDATA':
            service_desc = fields.get('SERVICEDESC')
            graphite_postfix = fields.get('GRAPHITEPOSTFIX')
            if graphite_postfix:
                metric_path_base.append(graphite_postfix)
            else:
                metric_path_base.append(service_desc)

        perfdata = fields[datatype]
        counters = self._parse_perfdata(perfdata)

        for (counter, value) in counters:
            metric_path = metric_path_base + [counter]
            metric_path = [self._sanitize(x) for x in metric_path]
            metric_name = '.'.join(metric_path)
            self.publish(metric_name, value)
305068
def _parse_metadatas(self, text_lines):
        
        if not text_lines:
            return {}
        expr_metadata = re.compile(r'^#\+([a-zA-Z]+):(.*)')
        return {
            expr_metadata.match(line).group(1).lower()
            : expr_metadata.match(line).group(2).strip()
            for line in text_lines
        }
947999
def _parse_jing_line(line):
    
    parts = line.split(':', 4)
    filename, line, column, type_, message = [x.strip() for x in parts]
    if type_ == 'fatal':
        if message in KNOWN_FATAL_MESSAGES_MAPPING:
            message = KNOWN_FATAL_MESSAGES_MAPPING[message]
    return ErrorLine(filename, line, column, type_, message)
39754
def parse_line(self, line: str):
        
        for i in KEYPAIR_RE.finditer(line):
            key = i.group(1)
            value = urllib.parse.unquote(i.group(2))
            self[key] = value
709290
function parse(lines) {
  var i, line, key, parts, values;

  for(i = 0;i < lines.length;i++) {
    line = lines[i];
    this.lineNumber++;

    // ignore comments and whitespace lines
    if(COMMENT.test(line) || WHITESPACE.test(line)) {
      continue;
    // got something to parse
    }else{

      // strip empty entires, leading whitespace is allowed
      parts = line.split(/\s+/).filter(function(p) {
        return p;
      })

      // get the config key
      key = parts[0];

      // remaining parts to parse as values
      values = parts.slice(1);
      try {
        this.conf.add(key, values, this.lineNumber);
      }catch(e) {
        throw new ConfigError(this.lineNumber, line, this.file, e);
      }
    }
  }
}
562888
def ParseLines(self, input_lines):
    
    current_macro = None
    for line in input_lines:
      if line.startswith('PDDM-'):
        directive = line.split(' ', 1)[0]
        if directive == 'PDDM-DEFINE':
          name, args = self._ParseDefineLine(line)
          if self._macros.get(name):
            raise PDDMError('Attempt to redefine macro: "%s"' % line)
          current_macro = self.MacroDefinition(name, args)
          self._macros[name] = current_macro
          continue
        if directive == 'PDDM-DEFINE-END':
          if not current_macro:
            raise PDDMError('Got DEFINE-END directive without an active macro:'
                            ' "%s"' % line)
          current_macro = None
          continue
        raise PDDMError('Hit a line with an unknown directive: "%s"' % line)

      if current_macro:
        current_macro.AppendLine(line)
        continue

      # Allow blank lines between macro definitions.
      if line.strip() == '':
        continue

      raise PDDMError('Hit a line that wasn\'t a directive and no open macro'
                      ' definition: "%s"' % line)
121504
def convert(self, line=None, is_end=True):
        
        if line is not None:
            self.line = line
        if not self.line:
            raise TomlDecodeError(self.parser.lineno,
                                  'EOF is hit!')
        token = None
        self.line = self.line.lstrip()
        for key, pattern in self.patterns:
            m = pattern.match(self.line)
            if m:
                self.line = self.line[m.end():]
                handler = getattr(self, 'convert_%s' % key)
                token = handler(m)
                break
        else:
            raise TomlDecodeError(self.parser.lineno,
                                  'Parsing error: %r' % self.line)
        if is_end and not BLANK_RE.match(self.line):
            raise TomlDecodeError(self.parser.lineno,
                                  'Something is remained: %r' % self.line)
        return token
1034871
def _scan_line(self, line):
        
        is_quote_header = self.QUOTE_HDR_REGEX.match(line) is not None
        is_quoted = self.QUOTED_REGEX.match(line) is not None
        is_header = is_quote_header or self.HEADER_REGEX.match(line) is not None

        if self.fragment and len(line.strip()) == 0:
            if self.SIG_REGEX.match(self.fragment.lines[-1].strip()):
                self.fragment.signature = True
                self._finish_fragment()

        if self.fragment \
                and ((self.fragment.headers == is_header and self.fragment.quoted == is_quoted) or
                         (self.fragment.quoted and (is_quote_header or len(line.strip()) == 0))):

            self.fragment.lines.append(line)
        else:
            self._finish_fragment()
            self.fragment = Fragment(is_quoted, line, headers=is_header)
698394
def parse_blocks(lines):  # type: (List[str]) -> List[List[str]]
    
    blocks = []

    while lines:
        if lines[0] == '':
            lines.pop(0)
        else:
            blocks.append(parse_block(lines))

    return blocks
487923
def parse(cls, line, ns={}):
        
        parses  = [p for p in cls.opts_spec.scanString(line)]
        if len(parses) != 1:
            raise SyntaxError("Invalid specification syntax.")
        else:
            e = parses[0][2]
            processed = line[:e]
            if (processed.strip() != line.strip()):
                raise SyntaxError("Failed to parse remainder of string: %r" % line[e:])

        grouped_paths = cls._group_paths_without_options(cls.opts_spec.parseString(line))
        parse = {}
        for pathspecs, group in grouped_paths:
            options = {}

            normalization = cls.process_normalization(group)
            if normalization is not None:
                options['norm'] = normalization

            if 'plot_options' in group:
                plotopts =  group['plot_options'][0]
                opts = cls.todict(plotopts, 'brackets', ns=ns)
                options['plot'] = {cls.aliases.get(k,k):v for k,v in opts.items()}

            if 'style_options' in group:
                styleopts = group['style_options'][0]
                opts = cls.todict(styleopts, 'parens', ns=ns)
                options['style'] = {cls.aliases.get(k,k):v for k,v in opts.items()}

            for pathspec in pathspecs:
                parse[pathspec] = merge_option_dicts(parse.get(pathspec, {}), options)

        return {
            cls.apply_deprecations(path): {
                option_type: Options(**option_pairs)
                for option_type, option_pairs in options.items()
            }
            for path, options in parse.items()
        }
153907
def atoms(lines):
    
    # Convert sdf style charge to actual charge
    conv_charge_table = {0: 0, 1: 3, 2: 2, 3: 1, 4: 0, 5: -1, 6: -2, 7: -3}
    results = {}
    for i, line in enumerate(lines):
        symbol = line[31:34].rstrip()
        try:
            atom = Atom(symbol)
        except KeyError:
            raise ValueError(symbol)
        xpos = float(line[0:10])
        ypos = float(line[10:20])
        zpos = float(line[20:30])
        atom.coords = (xpos, ypos, zpos)
        atom.mass_diff = int(line[34:37])
        old_sdf_charge = int(line[37:40])
        atom.charge = conv_charge_table[old_sdf_charge]
        if old_sdf_charge == 4:
            atom.radical = 1
        # atom.stereo_flag = int(line[40:43])  # Not used
        # valence = int(line[46:49])
        # if valence:
        #     atom.valence = valence
        results[i + 1] = {"atom": atom}
    return results
1220538
def parse_results_mol2(mol2_outpath):
    
    docked_ligands = pd.DataFrame()

    lines = [line.strip() for line in open(mol2_outpath, 'r')]
    props = {}

    for i, line in enumerate(lines):
        if line.startswith('########## Name:'):
            ligand = line.strip().strip('##########').replace(' ', '').replace('\t', '').split(':')[1]
            line = lines[i + 1]
            props = {}
            props['Ligand'] = ligand
        if line.startswith('##########'):
            splitter = line.strip().strip('##########').replace(' ', '').replace('\t', '').split(':')
            props[splitter[0]] = float(splitter[1])
        if line.startswith('@<TRIPOS>MOLECULE'):
            if props:
                docked_ligands = docked_ligands.append(props, ignore_index=True)

    return docked_ligands
1040872
def parse(self, fo):
        
        motifs = []
        nucs = {"A":0,"C":1,"G":2,"T":3}

        lines = fo.readlines()
        for i in range(0, len(lines), 5):
            align = []
            pwm = []
            pfm = []
            m_id = ""
            line = lines[i].strip()
            m_id = line[1:]
            number = m_id.split("_")[0][1:]
            if os.path.exists("%s.seq" % number):
                with open("%s.seq" % number) as f:
                    for l in f:
                        if "x" not in l and "n" not in l:
                            l = l.strip().upper()
                            align.append(l)
                            if not pfm:
                                pfm = [[0 for x in range(4)] for x in range(len(l))]
                            for p in range(len(l)):
                                pfm[p][nucs[l[p]]] += 1
    
            m = [l.strip().split(" ")[1].split("\t") for l in lines[i + 1: i + 5]]

            pwm = [[float(m[x][y]) for x in range(4)] for y in range(len(m[0]))]


            motifs.append(Motif(pwm))
            motifs[-1].id = "{}_{}".format(self.name, m_id)
            #motifs[-1].pwm = pwm
            if align:
                motifs[-1].pfm = pfm
                motifs[-1].align = align

        return motifs