This function assumes that all lines are ATOM or HETATM lines.
           resid should have the proper PDB format i.e. an integer left-padded
           to length 4 followed by the insertion code which may be a blank space.
968792
def getAtomLine(self, chain, resid):
        ''''''
        for line in self.lines:
            fieldtype = line[0:6].strip()
            assert(fieldtype == "ATOM" or fieldtype == "HETATM")
            if line[21:22] == chain and resid == line[22:27]:
                return line
        raise Exception("Could not find the ATOM/HETATM line corresponding to chain '%(chain)s' and residue '%(resid)s'." % vars())
578411
def _set_raw_return(self, sep):
        
        raw = ''
        if self.dst.style['out'] == 'numpydoc':
            raw += '\n'
            spaces = ' ' * 4
            with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + spaces + l.lstrip() if i > 0 else l for i, l in enumerate(s.splitlines())])
            raw += self.dst.numpydoc.get_key_section_header('return', self.docs['out']['spaces'])
            if self.docs['out']['rtype']:
                rtype = self.docs['out']['rtype']
            else:
                rtype = 'type'
            # case of several returns
            if type(self.docs['out']['return']) is list:
                for ret_elem in self.docs['out']['return']:
                    # if tuple (name, desc, rtype) else string desc
                    if type(ret_elem) is tuple and len(ret_elem) == 3:
                        rtype = ret_elem[2]
                        if rtype is None:
                            rtype = ''
                        raw += self.docs['out']['spaces']
                        if ret_elem[0]:
                            raw += ret_elem[0] + ' : '
                        raw += rtype + '\n' + self.docs['out']['spaces'] + spaces + with_space(ret_elem[1]).strip() + '\n'
                    else:
                        # There can be a problem
                        raw += self.docs['out']['spaces'] + rtype + '\n'
                        raw += self.docs['out']['spaces'] + spaces + with_space(str(ret_elem)).strip() + '\n'
            # case of a unique return
            elif self.docs['out']['return'] is not None:
                raw += self.docs['out']['spaces'] + rtype
                raw += '\n' + self.docs['out']['spaces'] + spaces + with_space(self.docs['out']['return']).strip() + '\n'
        elif self.dst.style['out'] == 'google':
            raw += '\n'
            spaces = ' ' * 2
            with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + spaces +\
                                                    l.lstrip() if i > 0 else\
                                                    l for i, l in enumerate(s.splitlines())])
            raw += self.dst.googledoc.get_key_section_header('return', self.docs['out']['spaces'])
            if self.docs['out']['rtype']:
                rtype = self.docs['out']['rtype']
            else:
                rtype = None
            # case of several returns
            if type(self.docs['out']['return']) is list:
                for ret_elem in self.docs['out']['return']:
                    # if tuple (name=None, desc, rtype) else string desc
                    if type(ret_elem) is tuple and len(ret_elem) == 3:
                        rtype = ret_elem[2]
                        if rtype is None:
                            rtype = ''
                        raw += self.docs['out']['spaces'] + spaces
                        raw += rtype + ': ' + with_space(ret_elem[1]).strip() + '\n'
                    else:
                        # There can be a problem
                        if rtype:
                            raw += self.docs['out']['spaces'] + spaces + rtype + ': '
                            raw += with_space(str(ret_elem)).strip() + '\n'
                        else:
                            raw += self.docs['out']['spaces'] + spaces + with_space(str(ret_elem)).strip() + '\n'
            # case of a unique return
            elif self.docs['out']['return'] is not None:
                if rtype:
                    raw += self.docs['out']['spaces'] + spaces + rtype + ': '
                    raw += with_space(self.docs['out']['return']).strip() + '\n'
                else:
                    raw += self.docs['out']['spaces'] + spaces + with_space(self.docs['out']['return']).strip() + '\n'
        elif self.dst.style['out'] == 'groups':
            pass
        else:
            with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + l if i > 0 else l for i, l in enumerate(s.splitlines())])
            if self.docs['out']['return']:
                if not self.docs['out']['params']:
                    raw += '\n'
                raw += self.docs['out']['spaces'] + self.dst.get_key('return', 'out') + sep + with_space(self.docs['out']['return'].rstrip()).strip() + '\n'
            if self.docs['out']['rtype']:
                if not self.docs['out']['params']:
                    raw += '\n'
                raw += self.docs['out']['spaces'] + self.dst.get_key('rtype', 'out') + sep + self.docs['out']['rtype'].rstrip() + '\n'
        return raw
640123
static private StringBuilder formatLineId(StringBuilder buffer, int value) {
        char[] chars = new char[4];
        for (int i = 3; i >= 0; i--) {
            chars[i] = (char) HEX_BYTES[(value % 16) & 0xF];
            value >>= 4;
        }
        return buffer.append(chars);
    }
7497
public static ResidueNumber fromString(String pdb_code) {
		if(pdb_code == null)
			return null;

		ResidueNumber residueNumber = new ResidueNumber();
		Integer resNum = null;
		String icode = null;

		try {
			resNum = Integer.parseInt(pdb_code);
		} catch ( NumberFormatException e){
			// there is an insertion code..

			// Split at any position that's either:
			// preceded by a digit and followed by a non-digit, or
			// preceded by a non-digit and followed by a digit.
			String[] spl = pdb_code.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
			if ( spl.length == 2){
				resNum = Integer.parseInt(spl[0]);
				icode = spl[1];
			}

		}

		residueNumber.setSeqNum(resNum);
		if ( icode == null)
			residueNumber.setInsCode(null);
		else if ( icode.length() > 0)
			residueNumber.setInsCode(icode.charAt(0));
		return residueNumber;
	}
1252351
def makeWritePacket(ID, reg, values=None):
	
	pkt = makePacket(ID, xl320.XL320_WRITE, reg, values)
	return pkt
1183474
public void ENaddpattern( String id ) throws EpanetException {
        int errcode = epanet.ENaddpattern(id);
        checkError(errcode);
    }
150660
def _get_pdb_id(self, elem, **kwargs):
        ''''''
        id = elem.attrib['ID']
        if self.restrict_to_transmembrane_proteins:
            tmp = elem.attrib['TMP']
            assert(tmp == 'no' or tmp == 'yes' or tmp == 'not')
            if tmp == 'yes':
                self.ids[id] = PDBTM._get_tm_type(elem)
        else:
            self.ids[id] = self.ids.get(id, 0) + 1
1323181
function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
    var valueDim = opt.valueDim;
    var symbolBoundingData = itemModel.get('symbolBoundingData');
    var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
    var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
    var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
    var boundingLength;

    if (zrUtil.isArray(symbolBoundingData)) {
        var symbolBoundingExtent = [
            convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
            convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
        ];
        symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
        boundingLength = symbolBoundingExtent[pxSignIdx];
    }
    else if (symbolBoundingData != null) {
        boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
    }
    else if (symbolRepeat) {
        boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
    }
    else {
        boundingLength = layout[valueDim.wh];
    }

    output.boundingLength = boundingLength;

    if (symbolRepeat) {
        output.repeatCutLength = layout[valueDim.wh];
    }

    output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
}
1042621
def parse_atoms(self, pdb):
    """"""
    
    atomre = re.compile("ATOM")
    
    atomlines = [line for line in pdb.lines if atomre.match(line)]
    
    chainresnums = {}
    
    for line in atomlines:
      chain = line[21]
      resname = line[17:20]
      resnum = line[22:27]
      #print resnum
      chainresnums.setdefault(chain, [])
      
      if resnum in chainresnums[chain]:
        assert self[chain][chainresnums[chain].index(resnum)] == resname
      else:
        if resnum[-1] == ' ':
          self.setdefault(chain, [])
          self[chain] += [resname]
          chainresnums[chain] += [resnum]
    
    return chainresnums
224894
def split_pdb_residue(s):
    ''''''
    if s.isdigit():
        return (int(s), ' ')
    else:
        assert(s[:-1].isdigit())
        return ((s[:-1], s[-1]))
1088993
def process_pad_frame(self,
                          id=None,
                          msg=None):
        

        # normalize into a dataframe
        df = json_normalize(msg)
        # convert to a flattened dictionary
        dt = json.loads(df.to_json())

        flat_msg = {}

        for k in dt:
            new_key = "pad_{}".format(k)
            flat_msg[new_key] = dt[k]["0"]
            if new_key not in self.pad_keys:
                self.pad_keys[new_key] = k
        # end of capturing all unique keys

        dt["pad_id"] = id
        self.all_pad.append(dt)

        log.debug("PAD data updated:")
        log.debug(self.pad_keys)
        log.debug(self.all_pad)
        log.debug("")

        return flat_msg
233608
def write_pdb(self, mol, filename, name=None, num=None):
        

        # ugly hack to get around the openbabel issues with inconsistent
        # residue labelling.
        scratch = tempfile.gettempdir()
        with ScratchDir(scratch, copy_to_current_on_exit=False) as _:
            mol.to(fmt="pdb", filename="tmp.pdb")
            bma = BabelMolAdaptor.from_file("tmp.pdb", "pdb")

        num = num or 1
        name = name or "ml{}".format(num)

        # bma = BabelMolAdaptor(mol)
        pbm = pb.Molecule(bma._obmol)
        for i, x in enumerate(pbm.residues):
            x.OBResidue.SetName(name)
            x.OBResidue.SetNum(num)

        pbm.write(format="pdb", filename=filename, overwrite=True)
1322607
def get_differing_atom_residue_ids(self, pdb_name, pdb_list = []):
        ''''''

        # partition_by_sequence is a map pdb_name -> Int where two pdb names in the same equivalence class map to the same integer (i.e. it is a partition)
        # representative_pdbs is a map Int -> pdb_object mapping the equivalence classes (represented by an integer) to a representative PDB file
        # self.pdb_name_to_structure_mapping : pdb_name -> pdb_object

        # Sanity checks
        assert(pdb_name in self.pdb_names)
        assert(set(pdb_list).intersection(set(self.pdb_names)) == set(pdb_list)) # the names in pdb_list must be in pdb_names

        # 1. Get the representative structure for pdb_name
        representative_pdb_id = self.partition_by_sequence[pdb_name]
        representative_pdb = self.representative_pdbs[representative_pdb_id]

        # 2. Get the other representative structures as dictated by pdb_list
        other_representative_pdbs = set()
        other_representative_pdb_ids = set()
        if not pdb_list:
            pdb_list = self.pdb_names
        for opdb_name in pdb_list:
            orepresentative_pdb_id = self.partition_by_sequence[opdb_name]
            other_representative_pdb_ids.add(orepresentative_pdb_id)
            other_representative_pdbs.add(self.representative_pdbs[orepresentative_pdb_id])
        other_representative_pdbs.discard(representative_pdb)
        other_representative_pdb_ids.discard(representative_pdb_id)

        # Early out if pdb_list was empty (or all pdbs were in the same equivalence class)
        if not other_representative_pdbs:
            return []

        # 3. Return all residues of pdb_name's representative which differ from all the other representatives
        differing_atom_residue_ids = set()
        for other_representative_pdb_id in other_representative_pdb_ids:
            differing_atom_residue_ids = differing_atom_residue_ids.union(set(self.differing_atom_residue_ids[(representative_pdb_id, other_representative_pdb_id)]))

        return sorted(differing_atom_residue_ids)
1330297
def padDigitalData(self, dig_data, n):
        
        n = int(n)
        l0 = len(dig_data)
        if l0 % n == 0:
            return dig_data  # no need of padding
        else:
            ladd = n - (l0 % n)
            dig_data_add = np.zeros(ladd, dtype="uint32")
            dig_data_add.fill(dig_data[-1])
            return np.concatenate((dig_data, dig_data_add))
114171
def indentsize(line):
    """"""
    expline = string.expandtabs(line)
    return len(expline) - len(string.lstrip(expline))
332217
private static int getPositionForPDBresunm(String pdbresnum, String authId , Atom[] atoms){
		ResidueNumber residueNumber =  ResidueNumber.fromString(pdbresnum);
		residueNumber.setChainName(authId);

		boolean blankChain = authId == null || authId.equalsIgnoreCase("null") || authId.equals("_");

		for ( int i =0; i< atoms.length ;i++){
			Group g = atoms[i].getGroup();

			// match _ to any chain
			if( blankChain ) {
				residueNumber.setChainName(g.getChain().getName());
			}

			//System.out.println(g.getResidueNumber() + "< ? >" + residueNumber +"<");
			if ( g.getResidueNumber().equals(residueNumber)){
				//System.out.println(g + " == " + residueNumber );
				Chain c = g.getChain();
				if ( blankChain || c.getName().equals(authId)){
					return i;
				}
			}
		}
		return -1;
	}
609733
function getIdStringFromIdParts(source, idParts) {
        if (idParts.length === 1) {
            return null;
        }
        var i, l, idPart, idPartType, check = 0, nextIdNameCode;
        for (i = 0, l = idParts.length; i < l; i++) {
            if (idParts[i].type) {
                check = 1;
                break;
            }
        }
        if (check) {
            var ret = [];
            for (i = 0, l = idParts.length; i < l; i++) {
                idPart = idParts[i];
                idPartType = idPart.type;
                if (idPartType) {
                    nextIdNameCode = xtplAstToJs[idPartType](idPart);
                    pushToArray(source, nextIdNameCode.source);
                    ret.push(nextIdNameCode.exp);
                } else {
                    // literal a.x
                    ret.push(wrapByDoubleQuote(idPart));
                }
            }
            return ret;
        } else {
            return null;
        }
    }