Note: an alternative is to use the RCSB API e.g. http://www.rcsb.org/pdb/rest/hmmer?structureId=1cdg.
18605
def get_pfam_accession_numbers_from_pdb_chain(self, pdb_id, chain):
        ''''''
        return self.pdb_chain_to_pfam_mapping.get(pdb_id.lower(), {}).get(chain)
98242
def retrieve(pdb_id, cache_dir = None, strict = True, parse_ligands = False):
        ''''''

        # Check to see whether we have a cached copy
        pdb_id = pdb_id.upper()
        if cache_dir:
            filename = os.path.join(cache_dir, "%s.pdb" % pdb_id)
            if os.path.exists(filename):
                return PDB(read_file(filename), strict = strict, parse_ligands = parse_ligands)

        # Get a copy from the RCSB
        contents = rcsb.retrieve_pdb(pdb_id)

        # Create a cached copy if appropriate
        if cache_dir:
            write_file(os.path.join(cache_dir, "%s.pdb" % pdb_id), contents)

        # Return the object
        return PDB(contents, strict = strict, parse_ligands = parse_ligands)
455172
def from_block(cls, block):
        """"""
        rseqs = cma.realign_seqs(block)
        records = (SeqRecord(Seq(rseq, extended_protein),
                    id=bseq['id'],
                    description=bseq['description'],
                    dbxrefs=bseq['dbxrefs'].values(),   # list of strings
                    annotations=dict(
                        index=bseq['index'],
                        length=bseq['length'],
                        dbxrefs=bseq['dbxrefs'],
                        phylum=bseq['phylum'],
                        taxchar=bseq['taxchar'],
                        head_seq=bseq['head_seq'],
                        tail_seq=bseq['tail_seq'],
                        head_len=bseq['head_len'],
                        tail_len=bseq['tail_len'],      # dict
                        ),
                    # ENH: annotate with conservation levels
                    # letter_annotations=bseq['x'],
                    )
                for bseq, rseq in zip(block['sequences'], rseqs))
        return cls(records,
                # CMA attributes
                # block['one'],
                block['level'],
                block['name'],
                block['params'],
                block['query_length'],
                block['query_chars'],
                )
1320792
private ManageableRepository getRepository(RepositoryService rs) throws ResourceException
   {
      ManageableRepository mRepository = null;
      try
      {
         mRepository = repository == null ? rs.getCurrentRepository() : rs.getRepository(repository);
      }
      catch (Exception e)
      {
         throw new ResourceException("Could not get the "
            + (repository == null ? "current repository." : "repository '" + repository + "'"), e);
      }
      if (mRepository == null)
      {
         throw new ResourceException("Could not find the "
            + (repository == null ? "current repository." : "repository '" + repository + "'"));
      }
      if (LOG.isDebugEnabled())
      {
         LOG.debug("getRepository: repository = " + (repository == null ? "current." : repository));
      }

      return mRepository;
   }
983360
def rest_xml
      doc = REXML::Document.new APIConnection::XML_HEADER
      obj = doc.add_element RSRC_OBJECT_KEY.to_s
      obj.add_element('invitation_type').text = invitation_type
      obj.add_element('create_account_if_does_not_exist').text = create_account_if_does_not_exist
      if expiration_date_epoch
        obj.add_element('expiration_date_epoch').text = expiration_date_epoch
      end
      obj.add_element('ssh_username').text = ssh_username
      obj.add_element('hide_account').text = hide_account
      obj.add_element('invitation_status').text = invitation_status
      obj.add_element('multiple_uses_allowed').text = multiple_uses_allowed
      add_site_to_xml(doc)
      doc.to_s
    end
982058
public static long getMBRss(Client client) {
        assert(client != null);
        long rssMax = 0;
        try {
            ClientResponse r = client.callProcedure("@Statistics", "MEMORY", 0);
            VoltTable stats = r.getResults()[0];
            stats.resetRowPosition();
            while (stats.advanceRow()) {
                long rss = stats.getLong("RSS") / 1024;
                if (rss > rssMax) {
                    rssMax = rss;
                }
            }
            return rssMax;
        }
        catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
            return 0;
        }
    }
337775
async def CharmArchiveSha256(self, urls):
        '''
        
        '''
        # map input types to rpc msg
        _params = dict()
        msg = dict(type='Uniter',
                   request='CharmArchiveSha256',
                   version=5,
                   params=_params)
        _params['urls'] = urls
        reply = await self.rpc(msg)
        return reply
483763
def _cluster(param, tom, imtls, gsims, grp_ids, pmap):
    
    pmapclu = AccumDict({grp_id: ProbabilityMap(len(imtls.array), len(gsims))
                         for grp_id in grp_ids})
    # Get temporal occurrence model
    # Number of occurrences for the cluster
    first = True
    for nocc in range(0, 50):
        # TODO fix this once the occurrence rate will be used just as
        # an object attribute
        ocr = tom.occurrence_rate
        prob_n_occ = tom.get_probability_n_occurrences(ocr, nocc)
        if first:
            pmapclu = prob_n_occ * (~pmap)**nocc
            first = False
        else:
            pmapclu += prob_n_occ * (~pmap)**nocc
    pmap = ~pmapclu
    return pmap
1303551
def retrieve(pdb_id, cache_dir = None):
        ''''''

        pdb_contents = None
        xml_contents = None
        pdb_id = pdb_id.upper()

        if cache_dir:
            # Check to see whether we have a cached copy of the PDB file
            filename = os.path.join(cache_dir, "%s.pdb" % pdb_id)
            if os.path.exists(filename):
                pdb_contents = read_file(filename)

            # Check to see whether we have a cached copy of the XML file
            filename = os.path.join(cache_dir, "%s.xml" % pdb_id)
            if os.path.exists(filename):
                xml_contents = read_file(filename)

        # Get any missing files from the RCSB and create cached copies if appropriate
        if not pdb_contents:
            pdb_contents = rcsb.retrieve_pdb(pdb_id)
            if cache_dir:
                write_file(os.path.join(cache_dir, "%s.pdb" % pdb_id), pdb_contents)

        if not xml_contents:
            xml_contents = rcsb.retrieve_xml(pdb_id)
            if cache_dir:
                write_file(os.path.join(cache_dir, "%s.xml" % pdb_id), xml_contents)

        # Return the object
        return PDBML_slow(xml_contents, pdb_contents)
787969
public JsMessage transcribeToJmf() throws MessageCopyFailedException
                                          , IncorrectMessageTypeException
                                          , UnsupportedEncodingException {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "transcribeToJmf");
    JsMsgObject newJmo = null;

    // Try/catch block in case we get an MFPUnsupportedEncodingRuntimeException because the
    // payload is in an unsupported codepage.   d252277.2
    try {

     if (this instanceof JsJmsMessageImpl) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Transcribing from JsJmsMessageImpl");
        newJmo = jmo.transcribeToJmf();
      }

      else {
        // Non-JMS messages are not supported - they should have been converted into JMS by now
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Non-JMS Messages are not yet supported");
        String exString = nls.getFormattedMessage("UNEXPECTED_MESSAGE_TYPE_CWSIF0102"
                                                 ,new Object[] {getJsMessageType(), MessageType.JMS}
                                                 ,"The Message can not be represented as a pure JMF Message");
        throw new IncorrectMessageTypeException(exString);

      }
    }
    catch (MFPUnsupportedEncodingRuntimeException e) {
      FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.JsMessageImpl.transcribeToJmf", "721");
      // Throw the original UnsupportedEncodingException
      throw (UnsupportedEncodingException)e.getCause();
    }

    JsMessage newMsg;
    // if we have a new jmo, create a new message from it
    if (newJmo != this.jmo) {
      newMsg = createNewGeneralized(newJmo);
    }
    // otherwise, just return ourself
    else {
      newMsg = this;
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "transcribeToJmf", newMsg);
    return newMsg;
  }
453986
def retrieve(pdb_id, cache_dir = None, bio_cache = None):
        ''''''

        pdb_contents = None
        xml_contents = None
        pdb_id = pdb_id.upper()

        if bio_cache:
            pdb_contents = bio_cache.get_pdb_contents(pdb_id)
            xml_contents = bio_cache.get_pdbml_contents(pdb_id)

        if cache_dir:
            if not pdb_contents:
                # Check to see whether we have a cached copy of the PDB file
                filename = os.path.join(cache_dir, "%s.pdb" % pdb_id)
                if os.path.exists(filename):
                    pdb_contents = read_file(filename)

            if not xml_contents:
                # Check to see whether we have a cached copy of the XML file
                filename = os.path.join(cache_dir, "%s.xml" % pdb_id)
                if os.path.exists(filename):
                    xml_contents = read_file(filename)

        # Get any missing files from the RCSB and create cached copies if appropriate
        if not pdb_contents:
            pdb_contents = rcsb.retrieve_pdb(pdb_id)
            if cache_dir:
                write_file(os.path.join(cache_dir, "%s.pdb" % pdb_id), pdb_contents)

        if not xml_contents:
            xml_contents = rcsb.retrieve_xml(pdb_id)
            if cache_dir:
                write_file(os.path.join(cache_dir, "%s.xml" % pdb_id), xml_contents)

        # Return the object
        handler = PDBML(xml_contents, pdb_contents, bio_cache = bio_cache, pdb_id = pdb_id)
        xml.sax.parseString(xml_contents, handler)
        return handler
1000613
public void loadFromDirectAccess(){
		String pdbId = "1A4W";

		StructureProvider pdbreader = new MMCIFFileReader();

		try {
			Structure s = pdbreader.getStructureById(pdbId);

			System.out.println("Getting chain H of 1A4W");

			List<Chain> hs = s.getNonPolyChainsByPDB("H");

			Chain h = hs.get(0);
			List<Group> ligands = h.getAtomGroups();

			System.out.println("These ligands have been found in chain " + h.getName());

			for (Group l:ligands){
				System.out.println(l);
			}

			System.out.println("Accessing QWE directly: ");
			Group qwe = s.getNonPolyChainsByPDB("H").get(2).getGroupByPDB(new ResidueNumber("H",373,null));

			System.out.println(qwe.getChemComp());

			System.out.println(h.getSeqResSequence());
			System.out.println(h.getAtomSequence());
			System.out.println(h.getAtomGroups(GroupType.HETATM));

			System.out.println("Entities: " + s.getEntityInfos());

		} catch (Exception e) {
			e.printStackTrace();
		}


	}
1352536
async def serialize_rctsig_base(self, ar, inputs, outputs):
        
        await self._msg_field(ar, idx=0)
        if self.type == RctType.Null:
            return
        if self.type != RctType.Full and self.type != RctType.FullBulletproof and \
                self.type != RctType.Simple and self.type != RctType.SimpleBulletproof:
            raise ValueError('Unknown type')

        await self._msg_field(ar, idx=1)
        if self.type == RctType.Simple:
            await ar.tag('pseudoOuts')
            await ar.begin_array()
            await ar.prepare_container(inputs, eref(self, 'pseudoOuts'), KeyV)
            if ar.writing and len(self.pseudoOuts) != inputs:
                raise ValueError('pseudoOuts size mismatch')

            for i in range(inputs):
                await ar.field(eref(self.pseudoOuts, i), KeyV.ELEM_TYPE)
            await ar.end_array()

        await ar.tag('ecdhInfo')
        await ar.begin_array()
        await ar.prepare_container(outputs, eref(self, 'ecdhInfo'), EcdhTuple)
        if ar.writing and len(self.ecdhInfo) != outputs:
            raise ValueError('EcdhInfo size mismatch')

        for i in range(outputs):
            if self.type == RctType.Bulletproof2:
                am8 = [self.ecdhInfo[i].amount[0:8] if ar.writing else bytearray(0)]
                await ar.field(eref(am8, 0), Hash8)
                if not ar.writing:
                    x.set_elem(eref(self.ecdhInfo[i], 'amount'), am8[0] + bytearray(24))
                    x.set_elem(eref(self.ecdhInfo[i], 'mask'), bytearray(32))
            else:
                await ar.field(eref(self.ecdhInfo, i), EcdhInfo.ELEM_TYPE)
        await ar.end_array()

        await ar.tag('outPk')
        await ar.begin_array()
        await ar.prepare_container((outputs), eref(self, 'outPk'), CtKey)
        if ar.writing and len(self.outPk) != outputs:
            raise ValueError('outPk size mismatch')

        for i in range(outputs):
            await ar.field(eref(self.outPk[i], 'mask'), ECKey)
        await ar.end_array()
836105
def decode_response(client_message, to_object=None):
    
    parameters = dict(value=None, replica_timestamps=None, replica_count=None)
    parameters['value'] = client_message.read_long()

    replica_timestamps_size = client_message.read_int()
    replica_timestamps = []
    for _ in range(0, replica_timestamps_size):
        replica_timestamps_item = (client_message.read_str(), client_message.read_long())
        replica_timestamps.append(replica_timestamps_item)

    parameters['replica_timestamps'] = ImmutableLazyDataList(replica_timestamps, to_object)
    parameters['replica_count'] = client_message.read_int()
    return parameters
248479
def from_resource_deeper(
        cls, resource_id=None, limit_depth=1000000, db_session=None, *args, **kwargs
    ):
        
        tablename = cls.model.__table__.name
        raw_q = """
            WITH RECURSIVE subtree AS (
                    SELECT res.*, 1 AS depth, LPAD(res.ordering::CHARACTER VARYING, 7, '0') AS sorting,
                    res.resource_id::CHARACTER VARYING AS path
                    FROM {tablename} AS res WHERE res.resource_id = :resource_id
                  UNION ALL
                    SELECT res_u.*, depth+1 AS depth,
                    (st.sorting::CHARACTER VARYING || '/' || LPAD(res_u.ordering::CHARACTER VARYING, 7, '0') ) AS sorting,
                    (st.path::CHARACTER VARYING || '/' || res_u.resource_id::CHARACTER VARYING ) AS path
                    FROM {tablename} res_u, subtree st
                    WHERE res_u.parent_id = st.resource_id
            )
            SELECT * FROM subtree WHERE depth<=:depth ORDER BY sorting;
        """.format(
            tablename=tablename
        )  # noqa
        db_session = get_db_session(db_session)
        text_obj = sa.text(raw_q)
        query = db_session.query(cls.model, "depth", "sorting", "path")
        query = query.from_statement(text_obj)
        query = query.params(resource_id=resource_id, depth=limit_depth)
        return query
1362685
def json(self, attribs=None, recurse=True, ignorelist=False):
        
        jsonnode = {}

        jsonnode['type'] = self.XMLTAG
        if self.id:
            jsonnode['id'] = self.id
        if self.set:
            jsonnode['set'] = self.set
        if self.cls:
            jsonnode['class'] = self.cls
        if self.annotator:
            jsonnode['annotator'] = self.annotator
        if self.annotatortype:
            if self.annotatortype == AnnotatorType.AUTO:
                jsonnode['annotatortype'] = "auto"
            elif self.annotatortype == AnnotatorType.MANUAL:
                jsonnode['annotatortype'] = "manual"
        if self.confidence is not None:
            jsonnode['confidence'] = self.confidence
        if self.n:
            jsonnode['n'] = self.n
        if self.auth:
            jsonnode['auth'] = self.auth
        if self.datetime:
            jsonnode['datetime'] = self.datetime.strftime("%Y-%m-%dT%H:%M:%S")

        if recurse: #pylint: disable=too-many-nested-blocks
            jsonnode['children'] = []
            if self.TEXTCONTAINER:
                jsonnode['text'] = self.text()
            if self.PHONCONTAINER:
                jsonnode['phon'] = self.phon()
            for child in self:
                if self.TEXTCONTAINER and isstring(child):
                    jsonnode['children'].append(child)
                elif not self.PHONCONTAINER:
                    #check ignore list
                    ignore = False
                    if ignorelist:
                        for e in ignorelist:
                            if isinstance(child,e):
                                ignore = True
                                break
                    if not ignore:
                        jsonnode['children'].append(child.json(attribs,recurse,ignorelist))

        if attribs:
            for attrib in attribs:
                jsonnode[attrib] = attribs

        return jsonnode
842619
def post_rsrc(rsrc, xml = '')
      validate_connected

      # convert CRs & to &#13;
      xml.gsub!(/\r/, '&#13;') if xml

      # send the data
      @last_http_response = @cnx[rsrc].post xml, content_type: 'text/xml', accept: :json
    rescue RestClient::ExceptionWithResponse => e
      handle_http_error e
    end