Instruction:
Given the following Python 3 function, write the documentation
async def get_non_secret(
            self,
            typ: str,
            filt: Union[dict, str] = None,
            canon_wql: Callable[[dict], dict] = None,
            limit: int = None) -> dict:
        """
        Return dict mapping each non-secret storage record of interest by identifier or,
        for no filter specified, mapping them all. If wallet has no such item, return empty dict.

        :param typ: non-secret storage record type
        :param filt: non-secret storage record identifier or WQL json (default all)
        :param canon_wql: WQL canonicalization function (default von_anchor.canon.canon_non_secret_wql())
        :param limit: maximum number of results to return (default no limit)
        :return: dict mapping identifiers to non-secret storage records
        """

        LOGGER.debug('Wallet.get_non_secret >>> typ: %s, filt: %s, canon_wql: %s', typ, filt, canon_wql)

        if not self.handle:
            LOGGER.debug('Wallet.get_non_secret <!< Wallet %s is closed', self.name)
            raise WalletState('Wallet {} is closed'.format(self.name))

        records = []
        if isinstance(filt, str):  # ordinary lookup by value
            try:
                records = [json.loads(await non_secrets.get_wallet_record(
                    self.handle,
                    typ,
                    filt,
                    json.dumps({
                        'retrieveType': False,
                        'retrieveValue': True,
                        'retrieveTags': True
                    })))]
            except IndyError as x_indy:
                if x_indy.error_code == ErrorCode.WalletItemNotFound:
                    pass
                else:
                    LOGGER.debug(
                        'Wallet.get_non_secret <!< Wallet %s lookup raised indy exception %s',
                        self.name,
                        x_indy.error_code)
                    raise
        else:
            canon = canon_wql or canon_non_secret_wql
            s_handle = await non_secrets.open_wallet_search(
                self.handle,
                typ,
                json.dumps(canon(filt or {})),
                json.dumps({
                    'retrieveRecords': True,
                    'retrieveTotalCount': True,
                    'retrieveType': False,
                    'retrieveValue': True,
                    'retrieveTags': True
                }))

            records = []
            cardinality = int(json.loads(
                await non_secrets.fetch_wallet_search_next_records(self.handle, s_handle, 0))['totalCount'])
            chunk = min(cardinality, limit or cardinality, Wallet.DEFAULT_CHUNK)
            if limit:
                cardinality = min(limit, cardinality)
            try:
                while len(records) != cardinality:
                    batch = json.loads(
                        await non_secrets.fetch_wallet_search_next_records(self.handle, s_handle, chunk))['records']
                    records.extend(batch)
                    if len(batch) < chunk:
                        break
                if len(records) != cardinality:
                    LOGGER.warning(
                        'Non-secret search/limit indicated %s results but fetched %s',
                        cardinality,
                        len(records))
            finally:
                await non_secrets.close_wallet_search(s_handle)

        rv = {record['id']: StorageRecord(typ, record['value'], record['tags'], record['id']) for record in records}
        LOGGER.debug('Wallet.get_non_secret <<< %s', rv)
        return rv

Response: Get non - secret storage records for the specified type and filter.


Instruction:
Implement a Python 3 function for
encrypting plaintext for owner of DID anonymously or via authenticated encryption scheme.

Response:
async def encrypt(
            self,
            message: bytes,
            authn: bool = False,
            to_verkey: str = None,
            from_verkey: str = None) -> bytes:
        """
        Encrypt plaintext for owner of DID, anonymously or via authenticated encryption scheme.
        Raise AbsentMessage for missing message, or WalletState if wallet is closed.

        :param message: plaintext, as bytes
        :param authn: whether to use authenticated encryption scheme
        :param to_verkey: verification key of recipient, None for anchor's own
        :param from_verkey: verification key of sender for authenticated encryption, None for anchor's own
        :return: ciphertext, as bytes
        """

        LOGGER.debug(
            'Wallet.encrypt >>> message: %s, authn: %s, to_verkey: %s, from_verkey: %s',
            message,
            authn,
            to_verkey,
            from_verkey)

        if not message:
            LOGGER.debug('Wallet.encrypt <!< No message to encrypt')
            raise AbsentMessage('No message to encrypt')

        if not self.handle:
            LOGGER.debug('Wallet.encrypt <!< Wallet %s is closed', self.name)
            raise WalletState('Wallet {} is closed'.format(self.name))

        if authn:
            rv = await crypto.auth_crypt(self.handle, from_verkey or self.verkey, to_verkey or self.verkey, message)
        else:
            rv = await crypto.anon_crypt(to_verkey or self.verkey, message)

        LOGGER.debug('Wallet.auth_encrypt <<< %s', rv)
        return rv


Instruction:
How would you explain what the following Python 3 function does
async def pack(
            self,
            message: str,
            recip_verkeys: Union[str, Sequence[str]] = None,
            sender_verkey: str = None) -> bytes:
        """
        Pack a message for one or more recipients (default anchor only).
        Raise AbsentMessage for missing message, or WalletState if wallet is closed.

        :param message: message to pack
        :param recip_verkeys: verification keys of recipients (default anchor's own, only)
        :param sender_verkey: sender verification key (default anonymous encryption)
        :return: packed message
        """

        LOGGER.debug(
            'Wallet.pack >>> message: %s, recip_verkeys: %s, sender_verkey: %s',
            message,
            recip_verkeys,
            sender_verkey)

        if message is None:
            LOGGER.debug('Wallet.pack <!< No message to pack')
            raise AbsentMessage('No message to pack')

        rv = await crypto.pack_message(
            self.handle,
            message,
            [recip_verkeys] if isinstance(recip_verkeys, str) else list(recip_verkeys or [self.verkey]),
            sender_verkey)

        LOGGER.debug('Wallet.pack <<< %s', rv)
        return rv

Response: Pack a message for one or more recipients.


Instruction:
Implement a function in Python 3 to
generate new verification key. Raise WalletState if wallet is closed.

Response:
async def reseed_init(self, next_seed: str = None) -> str:
        """
        Begin reseed operation: generate new key. Raise WalletState if wallet is closed.

        :param next_seed: incoming replacement seed (default random)
        :return: new verification key
        """

        LOGGER.debug('Wallet.reseed_init >>> next_seed: [SEED]')

        if not self.handle:
            LOGGER.debug('Wallet.reseed_init <!< Wallet %s is closed', self.name)
            raise WalletState('Wallet {} is closed'.format(self.name))

        rv = await did.replace_keys_start(self.handle, self.did, json.dumps({'seed': next_seed} if next_seed else {}))
        LOGGER.debug('Wallet.reseed_init <<< %s', rv)
        return rv


Instruction:
Write a Python 3 script to
return new DIDInfo with new verification key and metadata for DID.

Response:
async def reseed_apply(self) -> DIDInfo:
        """
        Replace verification key with new verification key from reseed operation.
        Raise WalletState if wallet is closed.

        :return: DIDInfo with new verification key and metadata for DID
        """

        LOGGER.debug('Wallet.reseed_apply >>>')

        if not self.handle:
            LOGGER.debug('Wallet.reseed_init <!< Wallet %s is closed', self.name)
            raise WalletState('Wallet {} is closed'.format(self.name))

        await did.replace_keys_apply(self.handle, self.did)
        self.verkey = await did.key_for_local_did(self.handle, self.did)
        now = int(time())
        rv = DIDInfo(self.did, self.verkey, {'anchor': True, 'since': now, 'modified': now})
        await did.set_did_metadata(self.handle, self.did, json.dumps(rv.metadata))

        LOGGER.info('Wallet %s set seed hash metadata for DID %s', self.name, self.did)

        LOGGER.debug('Wallet.reseed_apply <<< %s', rv)
        return rv


Instruction:
How would you code a function in Python 3 to
send schema to ledger and retrieve it if it does not exist.

Response:
async def send_schema(self, schema_data_json: str) -> str:
        """
        Send schema to ledger, then retrieve it as written to the ledger and return it.
        Raise BadLedgerTxn on failure. Raise BadAttribute for attribute name with spaces or
        reserved for indy-sdk.

        If schema already exists on ledger, log error and return schema.

        :param schema_data_json: schema data json with name, version, attribute names; e.g.,

        ::

            {
                'name': 'my-schema',
                'version': '1.234',
                'attr_names': ['favourite_drink', 'height', 'last_visit_date']
            }

        :return: schema json as written to ledger (or existed a priori)
        """

        LOGGER.debug('Origin.send_schema >>> schema_data_json: %s', schema_data_json)

        schema_data = json.loads(schema_data_json)
        for attr in schema_data['attr_names']:
            if not (re.match(r'(?=[^- ])[-_a-zA-Z0-9 ]+(?<=[^- ])$', attr)) or attr.strip().lower() == 'hash':
                LOGGER.debug('Origin.send_schema <!< Bad attribute name [%s]', attr)
                raise BadAttribute('Bad attribute name [{}]'.format(attr))

        s_id = schema_id(self.did, schema_data['name'], schema_data['version'])
        s_key = schema_key(s_id)
        rv_json = None
        with SCHEMA_CACHE.lock:
            try:
                rv_json = await self.get_schema(s_key)
                LOGGER.error(
                    'Schema %s version %s already exists on ledger for origin-did %s: not sending',
                    schema_data['name'],
                    schema_data['version'],
                    self.did)
            except AbsentSchema:  # OK - about to create and send it
                (_, schema_json) = await anoncreds.issuer_create_schema(
                    self.did,
                    schema_data['name'],
                    schema_data['version'],
                    json.dumps(schema_data['attr_names']))
                req_json = await ledger.build_schema_request(self.did, schema_json)
                await self._sign_submit(req_json)

                for _ in range(16):  # reasonable timeout
                    try:
                        rv_json = await self.get_schema(s_key)  # adds to cache
                        break
                    except AbsentSchema:
                        await sleep(1)
                        LOGGER.info('Sent schema %s to ledger, waiting 1s for its appearance', s_id)

                if not rv_json:
                    LOGGER.debug('Origin.send_schema <!< timed out waiting on sent schema %s', s_id)
                    raise BadLedgerTxn('Timed out waiting on sent schema {}'.format(s_id))

        LOGGER.debug('Origin.send_schema <<< %s', rv_json)
        return rv_json


Instruction:
Implement a Python 3 function for
returning the indy - sdk null role for a tails sync anchor which does not need write access.

Response:
def least_role() -> Role:
        """
        Return the indy-sdk null role for a tails sync anchor, which does not need write access.

        :return: USER role
        """

        LOGGER.debug('NominalAnchor.least_role >>>')

        rv = Role.USER

        LOGGER.debug('NominalAnchor.least_role <<< %s', rv)
        return rv


Instruction:
Create a Python 3 function for
closing the current object.

Response:
async def close(self) -> None:
        """
        Explicit exit. If so configured, populate cache to prove for any creds on schemata,
        cred defs, and rev regs marked of interest in configuration at initialization,
        archive cache, and purge prior cache archives.

        :return: current object
        """

        LOGGER.debug('OrgHubAnchor.close >>>')

        archive_caches = False
        if self.config.get('archive-holder-prover-caches-on-close', False):
            archive_caches = True
            await self.load_cache_for_proof(False)
        if self.config.get('archive-verifier-caches-on-close', {}):
            archive_caches = True
            await self.load_cache_for_verification(False)
        if archive_caches:
            ArchivableCaches.archive(self.dir_cache)
            ArchivableCaches.purge_archives(self.dir_cache, True)

        # Do not close wallet independently: allow for sharing open wallet over many anchor lifetimes
        # await self.wallet.close() #1.7.8
        # Do not close pool independently: let relying party decide when to go on-line and off-line

        for path_rr_id in Tails.links(self._dir_tails):
            rr_id = basename(path_rr_id)
            try:
                await HolderProver._sync_revoc_for_proof(self, rr_id)
            except ClosedPool:
                LOGGER.warning('OrgHubAnchor sync-revoc on close required ledger for %s but pool was closed', rr_id)

        LOGGER.debug('OrgHubAnchor.close <<<')


Instruction:
Explain what the following Python 3 code does
def canon_cred_wql(query: dict) -> dict:

    for k in [qk for qk in query]:  # copy: iteration alters query keys
        attr_match = re.match('attr::([^:]+)::(marker|value)$', k)
        if isinstance(query[k], dict):  # only subqueries are dicts: recurse
            query[k] = canon_cred_wql(query[k])
        if k == '$or':
            if not isinstance(query[k], list):
                raise BadWalletQuery('Bad WQL; $or value must be a list in {}'.format(json.dumps(query)))
            query[k] = [canon_cred_wql(subq) for subq in query[k]]
        if attr_match:
            qkey = 'attr::{}::{}'.format(canon(attr_match.group(1)), canon(attr_match.group(2)))
            query[qkey] = query.pop(k)
            tag_value = query[qkey]
            if isinstance(tag_value, dict) and len(tag_value) == 1:
                if '$in' in tag_value:
                    tag_value['$in'] = [raw(val) for val in tag_value.pop('$in')]
                else:
                    wql_op = set(tag_value.keys()).pop()  # $neq, $gt, $gte, etc.
                    tag_value[wql_op] = raw(tag_value[wql_op])
            else:  # equality
                query[qkey] = raw(query[qkey])

    return query

Response: Canonicalize WQL query to get all the keys that match the input to indy - sdk wallet credential filtration.


Instruction:
Here you have a function in Python 3, explain what it does
def canon_pairwise_wql(query: dict = None) -> dict:

    if not query:
        return {
            '~their_did': {
                '$neq': ''
            }
        }

    for k in [qk for qk in query]:  # copy: iteration alters query keys
        if isinstance(query[k], dict):  # only subqueries are dicts: recurse
            query[k] = canon_pairwise_wql(query[k])
        if k == '$or':
            if not isinstance(query[k], list):
                raise BadWalletQuery('Bad WQL; $or value must be a list in {}'.format(json.dumps(query)))
            query[k] = [canon_pairwise_wql(subq) for subq in query[k]]
        elif k == '$not':
            query[k] = canon_pairwise_wql(query.pop(k))
        elif k not in WQL_1_OPS:
            qkey = canon_pairwise_tag(k)
            query[qkey] = query.pop(k)
            tag_value = query[qkey]
            if isinstance(tag_value, dict) and len(tag_value) == 1:
                if '$in' in tag_value:
                    tag_value['$in'] = [raw(val) for val in tag_value['$in']]
                else:
                    wql_op = set(tag_value.keys()).pop()  # $neq, $gt, $gt, etc.
                    tag_value[wql_op] = raw(tag_value[wql_op])
            else:
                query[qkey] = raw(query.pop(qkey))

    return query

Response: Canonicalize WQL tags to unencrypted storage specification.


Instruction:
Can you tell what is the following Python 3 function doing
def parse_requirements(filename):

    try:
        with open(filename) as fh_req:
            return [line.strip() for line in fh_req if line.strip() and not line.startswith('#')]
    except FileNotFoundError:
        print('File not found: {}'.format(realpath(filename)), file=stderr)
        raise

Response: Load a pip requirements file and return a list of strings


Instruction:
Here you have a function in Python 3, explain what it does
async def add_config(self, name: str, genesis: str = None) -> None:

        LOGGER.debug('NodePoolManager.__init__ >>> name: %s, genesis: %s', name, genesis)

        if name in await self.list():
            LOGGER.debug('NodePoolManager.add_config: <!< Node pool %s configuration already present', name)
            raise ExtantPool('Node pool {} configuration already present'.format(name))

        genesis_tmp = None
        path_gen = realpath(expanduser(expandvars(genesis)))
        try:
            if not isfile(path_gen):
                genesis_tmp = NamedTemporaryFile(mode='w+b', buffering=0, delete=False)
                with genesis_tmp:
                    genesis_tmp.write(genesis.encode())
            await pool.create_pool_ledger_config(
                name,
                json.dumps({
                    'genesis_txn': path_gen if isfile(path_gen) else genesis_tmp.name
                }))
        finally:
            if genesis_tmp:
                remove(genesis_tmp.name)

        LOGGER.debug('NodePoolManager.__init__ <<<')

Response: Add node pool ledger configuration to indy home directory.


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def list(self) -> List[str]:

        LOGGER.debug('NodePoolManager.list >>>')

        rv = [p['pool'] for p in await pool.list_pools()]

        LOGGER.debug('NodePoolManager.list <<< %s', rv)
        return rv

Response: Return list of pool names configured empty list for none.


Instruction:
Here you have a function in Python 3, explain what it does
def get(self, name: str, config: dict = None) -> NodePool:

        LOGGER.debug('NodePoolManager.node_pool >>>')

        rv = NodePool(name, self.protocol, config)

        LOGGER.debug('NodePoolManager.node_pool <<< %s', rv)
        return rv

Response: Return node pool in input name and optional configuration.


Instruction:
Create a Python 3 function to
remove serialized pool info if it exists. Abstain from removing open node pool.

Response:
async def remove(self, name: str) -> None:
        """
        Remove serialized pool info if it exists. Abstain from removing open node pool.
        """

        LOGGER.debug('NodePoolManager.remove >>> name: %s', name)

        try:
            await pool.delete_pool_ledger_config(name)
        except IndyError as x_indy:
            LOGGER.info('Abstaining from node pool removal; indy-sdk error code %s', x_indy.error_code)

        LOGGER.debug('NodePool.remove <<<')


Instruction:
Can you tell what is the following Python 3 function doing
def authnkey(self) -> dict:

        return {k: self._pubkey[k] for k in self._pubkey if self._pubkey[k].authn}

Response: Return a dict of public keys marked as authentication keys.


Instruction:
Can you generate the documentation for the following Python 3 function
def set(self, item: Union[Service, PublicKey]) -> 'DIDDoc':

        if isinstance(item, Service):
            self.service[item.id] = item
        elif isinstance(item, PublicKey):
            self.pubkey[item.id] = item
        else:
            raise BadDIDDocItem('Cannot add item {} to DIDDoc on DID {}'.format(item, self.did))

Response: Add or replace service or public key to current DIDDoc.


Instruction:
Explain what the following Python 3 code does
def serialize(self) -> str:

        return {
            '@context': DIDDoc.CONTEXT,
            'id': canon_ref(self.did, self.did),
            'publicKey': [pubkey.to_dict() for pubkey in self.pubkey.values()],
            'authentication': [{
                'type': pubkey.type.authn_type,
                'publicKey': canon_ref(self.did, pubkey.id)
            } for pubkey in self.pubkey.values() if pubkey.authn],
            'service': [service.to_dict() for service in self.service.values()]
        }

Response: Dump current object to a JSON - compatible dictionary.


Instruction:
Make a summary of the following Python 3 code
def add_service_pubkeys(self, service: dict, tags: Union[Sequence[str], str]) -> List[PublicKey]:

        rv = []
        for tag in [tags] if isinstance(tags, str) else list(tags):

            for svc_key in service.get(tag, {}):
                canon_key = canon_ref(self.did, svc_key)
                pubkey = None

                if '#' in svc_key:
                    if canon_key in self.pubkey:
                        pubkey = self.pubkey[canon_key]
                    else:  # service key refers to another DID doc
                        LOGGER.debug(
                            'DIDDoc.add_service_pubkeys <!< DID document %s has no public key %s',
                            self.did,
                            svc_key)
                        raise AbsentDIDDocItem('DID document {} has no public key {}'.format(self.did, svc_key))
                else:
                    for existing_pubkey in self.pubkey.values():
                        if existing_pubkey.value == svc_key:
                            pubkey = existing_pubkey
                            break
                    else:
                        pubkey = PublicKey(
                            self.did,
                            ident=svc_key[-9:-1],  # industrial-grade uniqueness
                            value=svc_key)
                        self._pubkey[pubkey.id] = pubkey

                if pubkey and pubkey not in rv:  # perverse case: could specify same key multiple ways; append once
                    rv.append(pubkey)

        return rv

Response: Add public keys specified in service. Return list of public keys so discovered. Raise AbsentDIDDocItem for public key reference not present in DID document.


Instruction:
Write a Python 3 script to
construct DIDDoc object from dict representation.

Response:
def deserialize(cls, did_doc: dict) -> 'DIDDoc':
        """
        Construct DIDDoc object from dict representation.

        Raise BadIdentifier for bad DID.

        :param did_doc: DIDDoc dict reprentation.
        :return: DIDDoc from input json.
        """

        rv = None
        if 'id' in did_doc:
            rv = DIDDoc(did_doc['id'])
        else:  # get DID to serve as DID document identifier from first public key
            if 'publicKey' not in did_doc:
                LOGGER.debug('DIDDoc.deserialize <!< no identifier in DID document')
                raise AbsentDIDDocItem('No identifier in DID document')
            for pubkey in did_doc['publicKey']:
                pubkey_did = canon_did(resource(pubkey['id']))
                if ok_did(pubkey_did):
                    rv = DIDDoc(pubkey_did)
                    break
            else:
                LOGGER.debug('DIDDoc.deserialize <!< no identifier in DID document')
                raise AbsentDIDDocItem('No identifier in DID document')

        for pubkey in did_doc['publicKey']:  # include public keys and authentication keys by reference
            pubkey_type = PublicKeyType.get(pubkey['type'])
            authn = any(
                canon_ref(rv.did, ak.get('publicKey', '')) == canon_ref(rv.did, pubkey['id'])
                for ak in did_doc.get('authentication', {}) if isinstance(ak.get('publicKey', None), str))
            key = PublicKey(  # initialization canonicalizes id
                rv.did,
                pubkey['id'],
                pubkey[pubkey_type.specifier],
                pubkey_type,
                canon_did(pubkey['controller']),
                authn)
            rv.pubkey[key.id] = key

        for akey in did_doc.get('authentication', {}):  # include embedded authentication keys
            pk_ref = akey.get('publicKey', None)
            if pk_ref:
                pass  # got it already with public keys
            else:
                pubkey_type = PublicKeyType.get(akey['type'])
                key = PublicKey(  # initialization canonicalized id
                    rv.did,
                    akey['id'],
                    akey[pubkey_type.specifier],
                    pubkey_type,
                    canon_did(akey['controller']),
                    True)
                rv.pubkey[key.id] = key

        for service in did_doc.get('service', {}):
            endpoint = service['serviceEndpoint']
            svc = Service(  # initialization canonicalizes id
                rv.did,
                service.get('id', canon_ref(rv.did, 'assigned-service-{}'.format(len(rv.service)), ';')),
                service['type'],
                rv.add_service_pubkeys(service, 'recipientKeys'),
                rv.add_service_pubkeys(service, ['mediatorKeys', 'routingKeys']),
                canon_ref(rv.did, endpoint, ';') if ';' in endpoint else endpoint,
                service.get('priority', None))
            rv.service[svc.id] = svc

        return rv


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get(version: str) -> 'Protocol':

        return Protocol.V_13 if version == Protocol.V_13.value.name else Protocol.DEFAULT

Response: Get the class corresponding to the input version value.


Instruction:
Can you write a function in Python 3 where it
returns the tag for the current version of node protocol.

Response:
def cd_id_tag(self, for_box_id: bool = False) -> str:
        """
        Return (place-holder) credential definition identifier tag for current version of node protocol.
        At present, von_anchor always uses the tag of 'tag' if the protocol calls for one.

        :param for_box_id: whether to prefix a colon, if current protocol uses one, in constructing
            a cred def id or rev reg id.
        :return: cred def id tag
        """

        if for_box_id:
            return '' if self == Protocol.V_13 else ':tag'
        return 'tag'


Instruction:
Write a Python 3 function that can
return the identifier for input issuer DID and schema sequence number.

Response:
def cred_def_id(self, issuer_did: str, schema_seq_no: int) -> str:
        """
        Return credential definition identifier for input issuer DID and schema sequence number.

        :param issuer_did: DID of credential definition issuer
        :param schema_seq_no: schema sequence number
        :return: credential definition identifier
        """

        return '{}:3:CL:{}{}'.format(  # 3 marks indy cred def id, CL is sig type
            issuer_did,
            schema_seq_no,
            self.cd_id_tag(True))


Instruction:
Make a summary of the following Python 3 code
def txn_data2schema_key(self, txn: dict) -> SchemaKey:

        rv = None
        if self == Protocol.V_13:
            rv = SchemaKey(txn['identifier'], txn['data']['name'], txn['data']['version'])
        else:
            txn_txn = txn.get('txn', None) or txn  # may have already run this txn through txn2data() below
            rv = SchemaKey(
                txn_txn['metadata']['from'],
                txn_txn['data']['data']['name'],
                txn_txn['data']['data']['version'])

        return rv

Response: Return schema key from ledger transaction data.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def txn2data(self, txn: dict) -> str:

        rv_json = json.dumps({})
        if self == Protocol.V_13:
            rv_json = json.dumps(txn['result'].get('data', {}))
        else:
            rv_json = json.dumps((txn['result'].get('data', {}) or {}).get('txn', {}))  # "data": null for no such txn

        return rv_json

Response: Given ledger transaction return its data json.


Instruction:
Can you create a Python 3 function that
gives ledger transaction return its epoch time.

Response:
def txn2epoch(self, txn: dict) -> int:
        """
        Given ledger transaction, return its epoch time.

        :param txn: transaction as dict
        :return: transaction time
        """

        rv = None
        if self == Protocol.V_13:
            rv = txn['result']['txnTime']
        else:
            rv = txn['result']['txnMetadata']['txnTime']

        return rv


Instruction:
Implement a function in Python 3 to
give a genesis transaction return its node host and port.

Response:
def genesis_host_port(self, genesis_txn: dict) -> tuple:
        """
        Given a genesis transaction, return its node host and port.

        :param genesis_txn: genesis transaction as dict
        :return: node host and port
        """

        txn_data = genesis_txn['data'] if self == Protocol.V_13 else genesis_txn['txn']['data']['data']
        return (txn_data['node_ip'], txn_data['node_port'])


Instruction:
Implement a function in Python 3 to
open reader handle and return current object.

Response:
async def open(self) -> 'Tails':
        """
        Open reader handle and return current object.

        :return: current object
        """

        LOGGER.debug('Tails.open >>>')

        self._reader_handle = await blob_storage.open_reader('default', self._tails_config_json)

        LOGGER.debug('Tails.open <<<')
        return self


Instruction:
Can you implement a function in Python 3 that
returns whether input token looks like a valid tails hash.

Response:
def ok_hash(token: str) -> bool:
        """
        Whether input token looks like a valid tails hash.

        :param token: candidate string
        :return: whether input token looks like a valid tails hash
        """

        LOGGER.debug('Tails.ok_hash >>> token: %s', token)

        rv = re.match('[{}]{{42,44}}$'.format(B58), token) is not None
        LOGGER.debug('Tails.ok_hash <<< %s', rv)
        return rv


Instruction:
Implement a Python 3 function for
associating tails file with a revocation registry id.

Response:
def associate(base_dir: str, rr_id: str, tails_hash: str) -> None:
        """
        Create symbolic link to tails file named tails_hash for rev reg id rr_id.

        :param rr_id: rev reg id
        :param tails_hash: hash of tails file, serving as file name
        """

        LOGGER.debug('Tails.associate >>> base_dir: %s, rr_id: %s, tails_hash: %s', base_dir, rr_id, tails_hash)

        if not ok_rev_reg_id(rr_id):
            LOGGER.debug('Tails.associate <!< Bad rev reg id %s', rr_id)
            raise BadIdentifier('Bad rev reg id {}'.format(rr_id))

        if not Tails.ok_hash(tails_hash):
            LOGGER.debug('Tails.associate <!< Bad tails hash %s', tails_hash)
            raise BadIdentifier('Bad tails hash {}'.format(tails_hash))

        cd_id = rev_reg_id2cred_def_id(rr_id)
        directory = join(base_dir, cd_id)
        cwd = getcwd()
        makedirs(directory, exist_ok=True)
        chdir(directory)
        symlink(tails_hash, rr_id)
        chdir(cwd)

        LOGGER.debug('Tails.associate <<<')


Instruction:
Here you have a function in Python 3, explain what it does
def dir(base_dir: str, rr_id: str) -> str:

        LOGGER.debug('Tails.dir >>> base_dir: %s, rr_id: %s', base_dir, rr_id)

        if not ok_rev_reg_id(rr_id):
            LOGGER.debug('Tails.dir <!< Bad rev reg id %s', rr_id)
            raise BadIdentifier('Bad rev reg id {}'.format(rr_id))

        rv = join(base_dir, rev_reg_id2cred_def_id(rr_id))
        LOGGER.debug('Tails.dir <<< %s', rv)
        return rv

Response: Return correct subdirectory of input base dir for tails files corresponding to input rev reg id.


Instruction:
How would you implement a function in Python 3 that
gets the path to the tails file associated with a revocation registry identifier.

Response:
def linked(base_dir: str, rr_id: str) -> str:
        """
        Get, from the specified directory, the path to the tails file associated with
        the input revocation registry identifier, or None for no such file.

        :param base_dir: base directory for tails files, thereafter split by cred def id
        :param rr_id: rev reg id
        :return: (stringified) path to tails file of interest, or None for no such file.
        """

        LOGGER.debug('Tails.linked >>> base_dir: %s, rr_id: %s', base_dir, rr_id)

        if not ok_rev_reg_id(rr_id):
            LOGGER.debug('Tails.linked <!< Bad rev reg id %s', rr_id)
            raise BadIdentifier('Bad rev reg id {}'.format(rr_id))

        cd_id = rev_reg_id2cred_def_id(rr_id)
        link = join(base_dir, cd_id, rr_id)

        rv = join(base_dir, cd_id, readlink(link)) if islink(link) else None
        LOGGER.debug('Tails.linked <<< %s', rv)
        return rv


Instruction:
Create a Python 3 function for
returning set of all symbolic links in specified base tails directory recursively.

Response:
def links(base_dir: str, issuer_did: str = None) -> set:
        """
        Return set of all paths to symbolic links (rev reg ids) associating their
        respective tails files, in specified base tails directory recursively
        (omitting the .hopper subdirectory), on input issuer DID if specified.

        :param base_dir: base directory for tails files, thereafter split by cred def id
        :param issuer_did: issuer DID of interest
        :return: set of paths to symbolic links associating tails files
        """

        LOGGER.debug('Tails.links >>> base_dir: %s, issuer_did: %s', base_dir, issuer_did)

        if issuer_did and not ok_did(issuer_did):
            LOGGER.debug('Tails.links <!< Bad DID %s', issuer_did)
            raise BadIdentifier('Bad DID {}'.format(issuer_did))

        rv = set()
        for dir_path, dir_names, file_names in walk(base_dir, topdown=True):
            dir_names[:] = [d for d in dir_names if not d.startswith('.')]
            for file_name in file_names:
                if islink(join(dir_path, file_name)) and (not issuer_did or ok_rev_reg_id(file_name, issuer_did)):
                    rv.add(join(dir_path, file_name))

        LOGGER.debug('Tails.links <<< %s', rv)
        return rv


Instruction:
Create a Python 3 function for
returning all tails files in specified base directory and without symbolic links associating .

Response:
def unlinked(base_dir: str) -> set:
        """
        Return all paths to tails files, in specified tails base directory recursively
        (omitting the .hopper subdirectory), without symbolic links associating
        revocation registry identifiers.

        At an Issuer, tails files should not persist long without revocation registry identifier
        association via symbolic link. At a HolderProver, a newly downloaded tails file stays
        unlinked until the anchor stores a credential or creates a proof needing it, or else the
        anchor restarts.

        :param base_dir: base directory for tails files, thereafter split by cred def id
        :return: set of paths to tails files with no local symbolic links to them
        """

        LOGGER.debug('Tails.unlinked >>> base_dir: %s', base_dir)

        rv = set()
        for dir_path, dir_names, file_names in walk(base_dir, topdown=True):
            dir_names[:] = [d for d in dir_names if not d.startswith('.')]
            for file_name in file_names:
                if isfile(join(dir_path, file_name)) and Tails.ok_hash(file_name):
                    rv.add(join(dir_path, file_name))
        rv -= {join(dirname(path_link), readlink(path_link)) for path_link in Tails.links(base_dir)}

        LOGGER.debug('Tails.unlinked <<< %s', rv)
        return rv


Instruction:
How would you code a function in Python 3 to
return next available tag name for a new credential definition identifier.

Response:
def next_tag(base_dir: str, cd_id: str) -> (str, int):
        """
        Return the next tag name available for a new rev reg id on input cred def id in base directory,
        and suggested size of associated rev reg.

        :param base_dir: base directory for tails files, thereafter split by cred def id
        :param cd_id: credential definition identifier of interest
        :return: stringified least non-negative integer not yet used in a rev reg id associated with a tails file
            in base directory, and recommendation for next size to use
        """

        LOGGER.debug('Tails.next_tag >>> base_dir: %s, cd_id: %s', base_dir, cd_id)

        if not ok_cred_def_id(cd_id):
            LOGGER.debug('Tails.next_tag <!< Bad cred def id %s', cd_id)
            raise BadIdentifier('Bad cred def id {}'.format(cd_id))

        tag = 1 + max([int(rev_reg_id2tag(basename(f)))
            for f in Tails.links(base_dir) if cd_id in basename(f)] + [-1])  # -1: next tag is '0' if no tags so far
        size = min(2**(tag + 6), Tails.MAX_SIZE)

        rv = (tag, size)
        LOGGER.debug('Tails.next_tag <<< %s', rv)
        return rv


Instruction:
Explain what the following Python 3 code does
def current_rev_reg_id(base_dir: str, cd_id: str) -> str:

        LOGGER.debug('Tails.current_rev_reg_id >>> base_dir: %s, cd_id: %s', base_dir, cd_id)

        if not ok_cred_def_id(cd_id):
            LOGGER.debug('Tails.current_rev_reg_id <!< Bad cred def id %s', cd_id)
            raise BadIdentifier('Bad cred def id {}'.format(cd_id))

        tags = [int(rev_reg_id2tag(basename(f))) for f in Tails.links(base_dir)
            if cd_id in basename(f)]
        if not tags:
            raise AbsentTails('No tails files present for cred def id {}'.format(cd_id))

        rv = rev_reg_id(cd_id, str(max(tags)))  # ensure 10 > 9, not '9' > '10'
        LOGGER.debug('Tails.current_rev_reg_id <<< %s', rv)
        return rv

Response: Return revocation registry identifier for input credential definition identifier.


Instruction:
Given the following Python 3 function, write the documentation
def path(self) -> str:

        config = json.loads(self._tails_config_json)
        return join(config['base_dir'], config['file'])

Response: Returns the path to the current tails file.


Instruction:
Write a Python 3 script for
encoding a credential attribute value.

Response:
def encode(orig: Any) -> str:
    """
    Encode credential attribute value, purely stringifying any int32 and leaving numeric int32 strings alone,
    but mapping any other input to a stringified 256-bit (but not 32-bit) integer. Predicates in indy-sdk operate
    on int32 values properly only when their encoded values match their raw values.

    :param orig: original value to encode
    :return: encoded value
    """

    if isinstance(orig, int) and -I32_BOUND <= orig < I32_BOUND:
        return str(int(orig))  # python bools are ints

    try:
        i32orig = int(str(orig))  # don't encode floats as ints
        if -I32_BOUND <= i32orig < I32_BOUND:
            return str(i32orig)
    except (ValueError, TypeError):
        pass

    rv = int.from_bytes(sha256(raw(orig).encode()).digest(), 'big')
    while -I32_BOUND <= rv < I32_BOUND:
        rv = int.from_bytes(sha256(rv.encode()).digest(), 'big')  # sha256 maps no 32-bit int to another: terminates

    return str(rv)


Instruction:
Can you tell what is the following Python 3 function doing
def get(relation: str) -> 'Predicate':

        for pred in Predicate:
            if relation.upper() in (pred.value.fortran, pred.value.wql.upper(), pred.value.math):
                return pred
        return None

Response: Returns enum instance corresponding to input relation string


Instruction:
How would you explain what the following Python 3 function does
def to_int(value: Any) -> int:

        if isinstance(value, (bool, int)):
            return int(value)
        return int(str(value))

Response:
Cast a value as its equivalent int for indy predicate argument. Raise ValueError for any input but
 int or boolean. Raise ValueError for any input but
 int or boolean. Raise ValueError for any input but
 int or boolean.


Instruction:
Can you generate the documentation for the following Python 3 function
def get(token: Union[str, int] = None) -> 'Role':

        if token is None:
            return Role.USER

        for role in Role:
            if role == Role.ROLE_REMOVE:
                continue  # ROLE_REMOVE is not a sensible role to parse from any configuration
            if isinstance(token, int) and token in role.value:
                return role
            if str(token).upper() == role.name or token in (str(v) for v in role.value):  # could be numeric string
                return role

        return None

Response: Return the appropriate role for the given token.


Instruction:
Can you generate the documentation for the following Python 3 function
def token(self) -> str:

        return self.value[0] if self in (Role.USER, Role.ROLE_REMOVE) else self.name

Response: Return token identifying role to indy - sdk.


Instruction:
Given the following Python 3 function, write the documentation
def cached_get(timeout, *params):

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(view_or_request, *args, **kwargs):

            # The type of the request gets muddled when using a function based
            # decorator. We must use a function based decorator so it can be
            # used in urls.py.
            request = getattr(view_or_request, "request", view_or_request)

            if not hasattr(_thread_locals, "ultracache_request"):
                setattr(_thread_locals, "ultracache_request", request)

            # If request not GET or HEAD never cache
            if request.method.lower() not in ("get", "head"):
                return view_func(view_or_request, *args, **kwargs)

            # If request contains messages never cache
            l = 0
            try:
                l = len(request._messages)
            except (AttributeError, TypeError):
                pass
            if l:
                return view_func(view_or_request, *args, **kwargs)

            # Compute a cache key
            li = [str(view_or_request.__class__), view_func.__name__]

            # request.get_full_path is implicitly added it no other request
            # path is provided. get_full_path includes the querystring and is
            # the more conservative approach but makes it trivially easy for a
            # request to bust through the cache.
            if not set(params).intersection(set((
                "request.get_full_path()", "request.path", "request.path_info"
            ))):
                li.append(request.get_full_path())

            if "django.contrib.sites" in settings.INSTALLED_APPS:
                li.append(get_current_site_pk(request))

            # Pre-sort kwargs
            keys = list(kwargs.keys())
            keys.sort()
            for key in keys:
                li.append("%s,%s" % (key, kwargs[key]))

            # Extend cache key with custom variables
            for param in params:
                if not isinstance(param, str):
                    param = str(param)
                li.append(eval(param))

            s = ":".join([str(l) for l in li])
            hashed = hashlib.md5(s.encode("utf-8")).hexdigest()
            cache_key = "ucache-get-%s" % hashed
            cached = cache.get(cache_key, None)
            if cached is None:
                # The get view as outermost caller may bluntly set _ultracache
                request._ultracache = []
                response = view_func(view_or_request, *args, **kwargs)
                content = None
                if isinstance(response, TemplateResponse):
                    content = response.render().rendered_content
                elif isinstance(response, HttpResponse):
                    content = response.content
                if content is not None:
                    headers = getattr(response, "_headers", {})
                    cache.set(
                        cache_key,
                        {"content": content, "headers": headers},
                        timeout
                    )
                    cache_meta(request, cache_key)
            else:
                response = HttpResponse(cached["content"])
                # Headers has a non-obvious format
                for k, v in cached["headers"].items():
                    response[v[0]] = v[1]

            return response

        return _wrapped_view
    return decorator

Response: Decorator applied specifically to a view s get method.


Instruction:
Can you create a Python 3 function that
performs ancestor opening operations and synchronize revocation registry to tails tree content.

Response:
async def open(self) -> 'Issuer':
        """
        Explicit entry. Perform ancestor opening operations,
        then synchronize revocation registry to tails tree content.

        :return: current object
        """

        LOGGER.debug('Issuer.open >>>')

        await super().open()
        for path_rr_id in Tails.links(self.dir_tails, self.did):
            await self._sync_revoc_for_issue(basename(path_rr_id))

        LOGGER.debug('Issuer.open <<<')
        return self


Instruction:
How would you explain what the following Python 3 function does
async def _send_rev_reg_def(self, rr_id: str) -> None:

        LOGGER.debug('Issuer._send_rev_reg_def >>> rr_id: %s', rr_id)

        dir_tails_rr_id = self.rrb.dir_tails_top(rr_id)
        dir_target = self.rrb.dir_tails_target(rr_id)

        if not Tails.linked(dir_tails_rr_id, rr_id):
            LOGGER.debug(
                'Issuer._send_rev_reg_def <!< Tails file for rev reg %s not ready in dir %s',
                rr_id,
                dir_target)
            raise AbsentRevReg('Tails file for rev reg {} not ready in dir {}'.format(rr_id, dir_target))

        file_rr_def = join(dir_target, 'rr_def.json')
        if not isfile(file_rr_def):
            LOGGER.debug('Issuer._send_rev_reg_def <!< Rev reg def file %s not present', file_rr_def)
            raise AbsentRevReg('Rev reg def file {} not present'.format(file_rr_def))
        with open(file_rr_def, 'r') as fh_rr_def:
            rr_def_json = fh_rr_def.read()

        file_rr_ent = join(dir_target, 'rr_ent.json')
        if not isfile(file_rr_ent):
            LOGGER.debug('Issuer._send_rev_reg_def <!< Rev reg entry file %s not present', file_rr_ent)
            raise AbsentRevReg('Rev reg entry file {} not present'.format(file_rr_ent))
        with open(file_rr_ent, 'r') as fh_rr_ent:
            rr_ent_json = fh_rr_ent.read()

        file_tails = Tails.linked(dir_tails_rr_id, rr_id)
        if not file_tails:
            LOGGER.debug('Issuer._send_rev_reg_def <!< Tails link %s not present in dir %s', rr_id, dir_target)
            raise AbsentTails('Tails link {} not present in dir {}'.format(rr_id, dir_target))

        if self.rrbx:
            dir_cd_id = join(self.dir_tails, rev_reg_id2cred_def_id(rr_id))
            makedirs(dir_cd_id, exist_ok=True)
            rename(file_tails, join(dir_cd_id, basename(file_tails)))

        with REVO_CACHE.lock:
            rr_def_req_json = await ledger.build_revoc_reg_def_request(self.did, rr_def_json)
            await self._sign_submit(rr_def_req_json)
            await self.get_rev_reg_def(rr_id)  # add to cache en passant

        rr_ent_req_json = await ledger.build_revoc_reg_entry_request(self.did, rr_id, 'CL_ACCUM', rr_ent_json)
        await self._sign_submit(rr_ent_req_json)

        if self.rrbx:
            Tails.associate(self.dir_tails, rr_id, basename(file_tails))
            rmtree(dir_tails_rr_id)
        else:
            remove(file_rr_def)
            remove(file_rr_ent)

        LOGGER.debug('Issuer._send_rev_reg_def <<<')

Response: Sends revocation registry definition and initial entry to ledger and cache revocation registry definition.


Instruction:
How would you explain what the following Python 3 function does
async def _set_rev_reg(self, rr_id: str, rr_size: int) -> None:

        LOGGER.debug('Issuer._set_rev_reg >>> rr_id: %s, rr_size: %s', rr_id, rr_size)
        assert self.rrbx

        dir_hopper_rr_id = join(self.rrb.dir_tails_hopper, rr_id)

        while Tails.linked(dir_hopper_rr_id, rr_id) is None:
            await asyncio.sleep(1)
        await self._send_rev_reg_def(rr_id)

        cd_id = rev_reg_id2cred_def_id(rr_id)
        (next_tag, rr_size_suggested) = Tails.next_tag(self.dir_tails, cd_id)
        rr_id = rev_reg_id(cd_id, next_tag)
        self.rrb.mark_in_progress(rr_id, rr_size or rr_size_suggested)

        LOGGER.debug('Issuer._set_rev_reg <<<')

Response: Set revocation registry data from hopper into place within tails directory.


Instruction:
Can you tell what is the following Python 3 function doing
async def _sync_revoc_for_issue(self, rr_id: str, rr_size: int = None) -> None:

        LOGGER.debug('Issuer._sync_revoc_for_issue >>> rr_id: %s, rr_size: %s', rr_id, rr_size)

        if not ok_rev_reg_id(rr_id):
            LOGGER.debug('Issuer._sync_revoc_for_issue <!< Bad rev reg id %s', rr_id)
            raise BadIdentifier('Bad rev reg id {}'.format(rr_id))

        (cd_id, tag) = rev_reg_id2cred_def_id_tag(rr_id)

        try:
            await self.get_cred_def(cd_id)
        except AbsentCredDef:
            LOGGER.debug(
                'Issuer._sync_revoc_for_issue <!< tails tree %s may be for another ledger; no cred def found on %s',
                self.dir_tails,
                cd_id)
            raise AbsentCredDef('Tails tree {} may be for another ledger; no cred def found on {}'.format(
                self.dir_tails,
                cd_id))

        with REVO_CACHE.lock:
            revo_cache_entry = REVO_CACHE.get(rr_id, None)
            tails = None if revo_cache_entry is None else revo_cache_entry.tails
            if tails is None:  #  it's a new revocation registry, or not yet set in cache
                try:
                    tails = await Tails(self.dir_tails, cd_id, tag).open()
                except AbsentTails:   # it's a new revocation registry
                    if self.rrbx:
                        await self._set_rev_reg(rr_id, rr_size)
                    else:
                        await self.rrb.create_rev_reg(rr_id, rr_size)
                        await self._send_rev_reg_def(rr_id)
                    tails = await Tails(self.dir_tails, cd_id, tag).open()  # symlink should exist now

                if revo_cache_entry is None:
                    REVO_CACHE[rr_id] = RevoCacheEntry(None, tails)
                else:
                    REVO_CACHE[rr_id].tails = tails

        LOGGER.debug('Issuer._sync_revoc_for_issue <<<')

Response: Synchronize revocation registry with tails file reader.


Instruction:
Can you tell what is the following Python 3 function doing
def path_tails(self, rr_id: str) -> str:

        LOGGER.debug('Issuer.path_tails >>>')

        if not ok_rev_reg_id(rr_id):
            LOGGER.debug('Issuer.path_tails <!< Bad rev reg id %s', rr_id)
            raise BadIdentifier('Bad rev reg id {}'.format(rr_id))

        rv = Tails.linked(self.dir_tails, rr_id)
        LOGGER.debug('Issuer.path_tails <<< %s', rv)
        return rv

Response: Return path to tails file for input revocation registry identifier.


Instruction:
Here you have a function in Python 3, explain what it does
async def _create_cred_def(self, schema: dict, ledger_cred_def: dict, revo: bool) -> (str, bool):

        LOGGER.debug(
            'Issuer._create_cred_def >>> schema: %s, ledger_cred_def: %s, revo: %s',
            schema,
            ledger_cred_def,
            revo)

        cred_def_json = '{}'
        private_key_ok = True
        try:
            (_, cred_def_json) = await anoncreds.issuer_create_and_store_credential_def(
                self.wallet.handle,
                self.did,  # issuer DID
                json.dumps(schema),
                self.pool.protocol.cd_id_tag(False),  # expect only one cred def per schema and issuer
                'CL',
                json.dumps({'support_revocation': revo}))
            if ledger_cred_def:
                private_key_ok = False
                LOGGER.warning(
                    'New cred def on %s in wallet shadows existing one on ledger: private key not usable',
                    cred_def_id(self.did, schema['seqNo'], self.pool.protocol))
                    # carry on though, this anchor may have other capacities so public key may be good enough
        except IndyError as x_indy:
            if x_indy.error_code == ErrorCode.AnoncredsCredDefAlreadyExistsError:
                if ledger_cred_def:
                    LOGGER.info(
                        'Issuer wallet %s reusing existing cred def on schema %s version %s',
                        self.name,
                        schema['name'],
                        schema['version'])
                else:
                    LOGGER.debug('Issuer._create_cred_def <!< corrupt wallet %s', self.name)
                    raise CorruptWallet('Corrupt Issuer wallet {} has cred def on schema {} not on ledger'.format(
                        self.name,
                        schema['id']))
            else:
                LOGGER.debug(
                    'Issuer._create_cred_def <!< cannot store cred def in wallet %s: indy error code %s',
                    self.name,
                    x_indy.error_code)
                raise

        rv = (cred_def_json, private_key_ok)
        LOGGER.debug('Issuer._create_cred_def <<< %s', rv)
        return rv

Response: Create credential definition in wallet as part of the send_cred_def function sequence.


Instruction:
Can you write a function in Python 3 where it
sends a credential definition to the ledger.

Response:
async def send_cred_def(self, s_id: str, revo: bool = True, rr_size: int = None) -> str:
        """
        Create a credential definition as Issuer, store it in its wallet, and send it to the ledger.

        Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure
        to send credential definition to ledger if need be, WalletState for closed wallet,
        or IndyError for any other failure to create and store credential definition in wallet.

        :param s_id: schema identifier
        :param revo: whether to support revocation for cred def
        :param rr_size: size of initial revocation registry (default as per RevRegBuilder.create_rev_reg()),
            if revocation supported
        :return: json credential definition as it appears on ledger
        """

        LOGGER.debug('Issuer.send_cred_def >>> s_id: %s, revo: %s, rr_size: %s', s_id, revo, rr_size)

        if not ok_schema_id(s_id):
            LOGGER.debug('Issuer.send_cred_def <!< Bad schema id %s', s_id)
            raise BadIdentifier('Bad schema id {}'.format(s_id))

        if not self.wallet.handle:
            LOGGER.debug('Issuer.send_cred_def <!< Wallet %s is closed', self.name)
            raise WalletState('Wallet {} is closed'.format(self.name))

        if not self.pool:
            LOGGER.debug('Issuer.send_cred_def <!< issuer %s has no pool', self.name)
            raise AbsentPool('Issuer {} has no pool: cannot send cred def'.format(self.name))

        rv_json = json.dumps({})
        schema_json = await self.get_schema(schema_key(s_id))
        schema = json.loads(schema_json)

        cd_id = cred_def_id(self.did, schema['seqNo'], self.pool.protocol)
        private_key_ok = True
        with CRED_DEF_CACHE.lock:
            try:
                rv_json = await self.get_cred_def(cd_id)
                LOGGER.info(
                    'Cred def on schema %s version %s already exists on ledger; Issuer %s not sending another',
                    schema['name'],
                    schema['version'],
                    self.name)
            except AbsentCredDef:
                pass  # OK - about to create, store, and send it

            (cred_def_json, private_key_ok) = await self._create_cred_def(schema, json.loads(rv_json), revo)

            if not json.loads(rv_json):  # checking the ledger returned no cred def: send it
                req_json = await ledger.build_cred_def_request(self.did, cred_def_json)
                await self._sign_submit(req_json)

                for _ in range(16):  # reasonable timeout
                    try:
                        rv_json = await self.get_cred_def(cd_id)  # adds to cache
                        break
                    except AbsentCredDef:
                        await asyncio.sleep(1)
                        LOGGER.info('Sent cred def %s to ledger, waiting 1s for its appearance', cd_id)

                if not rv_json:
                    LOGGER.debug('Issuer.send_cred_def <!< timed out waiting on sent cred_def %s', cd_id)
                    raise BadLedgerTxn('Timed out waiting on sent cred_def {}'.format(cd_id))

                if revo:  # create new rev reg for tag '0'
                    if self.rrbx:
                        (_, rr_size_suggested) = Tails.next_tag(self.dir_tails, cd_id)
                        self.rrb.mark_in_progress(rev_reg_id(cd_id, '0'), rr_size or rr_size_suggested)

                    await self._sync_revoc_for_issue(rev_reg_id(cd_id, '0'), rr_size)  # sync rev reg on tag '0'

        if revo and private_key_ok:
            for tag in [str(t) for t in range(1, int(Tails.next_tag(self.dir_tails, cd_id)[0]))]:  # '1' to next-1
                await self._sync_revoc_for_issue(rev_reg_id(cd_id, tag), rr_size if tag == '0' else None)

        makedirs(join(self.dir_tails, cd_id), exist_ok=True)  # dir required for box id collection, revo or not

        LOGGER.debug('Issuer.send_cred_def <<< %s', rv_json)
        return rv_json


Instruction:
Make a summary of the following Python 3 code
async def create_cred_offer(self, schema_seq_no: int) -> str:

        LOGGER.debug('Issuer.create_cred_offer >>> schema_seq_no: %s', schema_seq_no)

        if not self.wallet.handle:
            LOGGER.debug('Issuer.create_cred_offer <!< Wallet %s is closed', self.name)
            raise WalletState('Wallet {} is closed'.format(self.name))

        if not self.pool:
            LOGGER.debug('Issuer.create_cred_offer <!< issuer %s has no pool', self.name)
            raise AbsentPool('Issuer {} has no pool: cannot create cred offer'.format(self.name))

        rv = None
        cd_id = cred_def_id(self.did, schema_seq_no, self.pool.protocol)
        try:
            rv = await anoncreds.issuer_create_credential_offer(self.wallet.handle, cd_id)
        except IndyError as x_indy:
            if x_indy.error_code == ErrorCode.WalletNotFoundError:
                LOGGER.debug(
                    'Issuer.create_cred_offer <!< did not issue cred definition from wallet %s',
                    self.name)
                raise CorruptWallet('Cannot create cred offer: did not issue cred definition from wallet {}'.format(
                    self.name))
            LOGGER.debug(
                'Issuer.create_cred_offer <!< cannot create cred offer, indy error code %s',
                x_indy.error_code)
            raise

        LOGGER.debug('Issuer.create_cred_offer <<< %s', rv)
        return rv

Response: Create credential offer for given schema sequence number.


Instruction:
Implement a function in Python 3 to
create new credential in revocation registry.

Response:
async def create_cred(
            self,
            cred_offer_json,
            cred_req_json: str,
            cred_attrs: dict,
            rr_size: int = None) -> (str, str):
        """
        Create credential as Issuer out of credential request and dict of key:value (raw, unencoded)
        entries for attributes.

        Return credential json, and if cred def supports revocation, credential revocation identifier.
        Raise WalletState for closed wallet.

        If the credential definition supports revocation, and the current revocation registry is full,
        the processing creates a new revocation registry en passant. Depending on the revocation
        registry size (by default starting at 64 and doubling iteratively through a maximum of 100000)
        and the revocation registry builder posture (see RevRegBuilder.__init__()), this operation may
        delay credential creation by several seconds. The use of an external revocation registry builder
        runs a parallel process, skirting this delay, but is more costly at initialization.

        :param cred_offer_json: credential offer json as created by Issuer
        :param cred_req_json: credential request json as created by HolderProver
        :param cred_attrs: dict mapping each attribute to its original value (the operation encodes it); e.g.,

        ::

            {
                'favourite_drink': 'martini',
                'height': 180,
                'last_visit_date': '2017-12-31',
                'weaknesses': None
            }

        :param rr_size: size of new revocation registry (default as per RevRegBuilder.create_rev_reg()) if necessary
        :return: tuple with newly issued credential json, credential revocation identifier (if cred def
            supports revocation, None otherwise).
        """

        LOGGER.debug(
            'Issuer.create_cred >>> cred_offer_json: %s, cred_req_json: %s, cred_attrs: %s, rr_size: %s',
            cred_offer_json,
            cred_req_json,
            cred_attrs,
            rr_size)

        if not self.wallet.handle:
            LOGGER.debug('Issuer.create_cred <!< Wallet %s is closed', self.name)
            raise WalletState('Wallet {} is closed'.format(self.name))

        cd_id = json.loads(cred_offer_json)['cred_def_id']
        if not ok_cred_def_id(cd_id):
            LOGGER.debug('Issuer.create_cred <!< Bad cred def id %s', cd_id)
            raise BadIdentifier('Bad cred def id {}'.format(cd_id))

        cred_def = json.loads(await self.get_cred_def(cd_id))  # ensure cred def is in cache

        if 'revocation' in cred_def['value']:
            with REVO_CACHE.lock:
                rr_id = Tails.current_rev_reg_id(self.dir_tails, cd_id)
                tails = REVO_CACHE[rr_id].tails
                assert tails  # at (re)start, at cred def, Issuer sync_revoc_for_issue() sets this index in revo cache

                try:
                    (cred_json, cred_revoc_id, _) = await anoncreds.issuer_create_credential(  # issue by default to rr
                        self.wallet.handle,
                        cred_offer_json,
                        cred_req_json,
                        json.dumps({k: cred_attr_value(cred_attrs[k]) for k in cred_attrs}),
                        rr_id,
                        tails.reader_handle)
                    rv = (cred_json, cred_revoc_id)

                except IndyError as x_indy:
                    if x_indy.error_code == ErrorCode.AnoncredsRevocationRegistryFullError:
                        (tag, rr_size_suggested) = Tails.next_tag(self.dir_tails, cd_id)
                        rr_id = rev_reg_id(cd_id, tag)
                        if self.rrbx:
                            await self._set_rev_reg(rr_id, rr_size)
                        else:
                            await self.rrb.create_rev_reg(rr_id, rr_size or rr_size_suggested)
                            await self._send_rev_reg_def(rr_id)

                        REVO_CACHE[rr_id].tails = await Tails(self.dir_tails, cd_id).open()  # symlink OK now
                        return await self.create_cred(cred_offer_json, cred_req_json, cred_attrs)

                    LOGGER.debug('Issuer.create_cred <!< cannot create cred, indy error code %s', x_indy.error_code)
                    raise
        else:
            try:
                (cred_json, _, _) = await anoncreds.issuer_create_credential(
                    self.wallet.handle,
                    cred_offer_json,
                    cred_req_json,
                    json.dumps({k: cred_attr_value(cred_attrs[k]) for k in cred_attrs}),
                    None,
                    None)
                rv = (cred_json, None)
            except IndyError as x_indy:
                LOGGER.debug('Issuer.create_cred <!< cannot create cred, indy error code %s', x_indy.error_code)
                raise

        LOGGER.debug('Issuer.create_cred <<< %s', rv)
        return rv


Instruction:
Create a Python 3 function for
revoking a revocation credential for the given revocation registry identifier and credential revocation identifier.

Response:
async def revoke_cred(self, rr_id: str, cr_id) -> int:
        """
        Revoke credential that input revocation registry identifier and
        credential revocation identifier specify.

        Return (epoch seconds) time of revocation.

        Raise AbsentTails if no tails file is available for input revocation registry identifier.
        Raise WalletState for closed wallet.
        Raise BadRevocation if issuer cannot revoke specified credential for any other reason
        (e.g., did not issue it, already revoked it).

        :param rr_id: revocation registry identifier
        :param cr_id: credential revocation identifier
        :return: time of revocation, in epoch seconds
        """

        LOGGER.debug('Issuer.revoke_cred >>> rr_id: %s, cr_id: %s', rr_id, cr_id)

        if not self.wallet.handle:
            LOGGER.debug('Issuer.revoke_cred <!< Wallet %s is closed', self.name)
            raise WalletState('Wallet {} is closed'.format(self.name))

        if not ok_rev_reg_id(rr_id):
            LOGGER.debug('Issuer.revoke_cred <!< Bad rev reg id %s', rr_id)
            raise BadIdentifier('Bad rev reg id {}'.format(rr_id))

        tails_reader_handle = (await Tails(
            self.dir_tails,
            *rev_reg_id2cred_def_id_tag(rr_id)).open()).reader_handle
        try:
            rrdelta_json = await anoncreds.issuer_revoke_credential(
                self.wallet.handle,
                tails_reader_handle,
                rr_id,
                cr_id)
        except IndyError as x_indy:
            LOGGER.debug(
                'Issuer.revoke_cred <!< Could not revoke revoc reg id %s, cred rev id %s: indy error code %s',
                rr_id,
                cr_id,
                x_indy.error_code)
            raise BadRevocation(
                'Could not revoke revoc reg id {}, cred rev id {}: indy error code {}'.format(
                    rr_id,
                    cr_id,
                    x_indy.error_code))

        rr_ent_req_json = await ledger.build_revoc_reg_entry_request(self.did, rr_id, 'CL_ACCUM', rrdelta_json)
        resp_json = await self._sign_submit(rr_ent_req_json)  # raises AbsentPool or ClosedPool if applicable
        resp = json.loads(resp_json)

        rv = self.pool.protocol.txn2epoch(resp)
        LOGGER.debug('Issuer.revoke_cred <<< %s', rv)
        return rv


Instruction:
Here you have a function in Python 3, explain what it does
async def get_box_ids_issued(self) -> str:

        LOGGER.debug('Issuer.get_box_ids_issued >>>')

        cd_ids = [
            d for d in listdir(self.dir_tails) if isdir(join(self.dir_tails, d)) and ok_cred_def_id(d, self.did)]
        s_ids = []
        for cd_id in cd_ids:
            try:
                s_ids.append(json.loads(await self.get_schema(cred_def_id2seq_no(cd_id)))['id'])
            except AbsentSchema:
                LOGGER.error(
                    'Issuer %s has issued cred def %s but no corresponding schema on ledger',
                    self.name,
                    cd_id)
        rr_ids = [basename(link) for link in Tails.links(self.dir_tails, self.did)]

        rv = json.dumps({
            'schema_id': s_ids,
            'cred_def_id': cd_ids,
            'rev_reg_id': rr_ids
        })
        LOGGER.debug('Issuer.get_box_ids_issued <<< %s', rv)
        return rv

Response: Get the set of unique box identifiers for all credential definitions and credentials issued.


Instruction:
How would you code a function in Python 3 to
give a URI reference return up to its delimiter or all of it if there is none.

Response:
def resource(ref: str, delimiter: str = None) -> str:
    """
    Given a (URI) reference, return up to its delimiter (exclusively), or all of it if there is none.

    :param ref: reference
    :param delimiter: delimiter character (default None maps to '#', or ';' introduces identifiers)
    """

    return ref.split(delimiter if delimiter else '#')[0]


Instruction:
Write a Python 3 script to
convert a URI into a DID if need be left - stripping did : if present.

Response:
def canon_did(uri: str) -> str:
    """
    Convert a URI into a DID if need be, left-stripping 'did:sov:' if present.
    Return input if already a DID. Raise BadIdentifier for invalid input.

    :param uri: input URI or DID
    :return: corresponding DID
    """

    if ok_did(uri):
        return uri

    if uri.startswith('did:sov:'):
        rv = uri[8:]
        if ok_did(rv):
            return rv
    raise BadIdentifier('Bad specification {} does not correspond to a sovrin DID'.format(uri))


Instruction:
Write a Python 3 function that can
give a DID and a reference in a DID document return a canonical form of a URI.

Response:
def canon_ref(did: str, ref: str, delimiter: str = None):
    """
    Given a reference in a DID document, return it in its canonical form of a URI.

    :param did: DID acting as the identifier of the DID document
    :param ref: reference to canonicalize, either a DID or a fragment pointing to a location in the DID doc
    :param delimiter: delimiter character marking fragment (default '#') or
        introducing identifier (';') against DID resource
    """

    if not ok_did(did):
        raise BadIdentifier('Bad DID {} cannot act as DID document identifier'.format(did))

    if ok_did(ref):  # e.g., LjgpST2rjsoxYegQDRm7EL
        return 'did:sov:{}'.format(did)

    if ok_did(resource(ref, delimiter)):  # e.g., LjgpST2rjsoxYegQDRm7EL#keys-1
        return 'did:sov:{}'.format(ref)

    if ref.startswith('did:sov:'):  # e.g., did:sov:LjgpST2rjsoxYegQDRm7EL, did:sov:LjgpST2rjsoxYegQDRm7EL#3
        rv = ref[8:]
        if ok_did(resource(rv, delimiter)):
            return ref
        raise BadIdentifier('Bad URI {} does not correspond to a sovrin DID'.format(ref))

    if urlparse(ref).scheme:  # e.g., https://example.com/messages/8377464
        return ref

    return 'did:sov:{}{}{}'.format(did, delimiter if delimiter else '#', ref)


Instruction:
Make a summary of the following Python 3 code
def ok_tags(tags: dict) -> bool:

        if not tags:
            return True
        depth = 0
        queue = [(i, depth+1) for i in tags.values() if isinstance(i, dict)]
        max_depth = 0
        while queue and max_depth < 2:
            sub, depth = queue.pop()
            max_depth = max(max_depth, depth)
            queue = queue + [(i, depth+1) for i in sub.values() if isinstance(i, dict)]

        return max_depth < 2 and all(isinstance(k, str) and isinstance(tags[k], str) for k in tags)

Response: Check if input tags dict is OK as an indy - sdk tags structure.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def tags(self, val: str) -> None:

        if not StorageRecord.ok_tags(val):
            LOGGER.debug('StorageRecord.__init__ <!< Tags %s must map strings to strings', val)
            raise BadRecord('Tags {} must map strings to strings'.format(val))

        self._tags = val or {}

Response: Set the tags of the record.


Instruction:
Given the following Python 3 function, write the documentation
def clear_tags(self) -> dict:

        return {t: self.tags[t] for t in (self.tags or {}) if t.startswith('~')} or None

Response: Accessor for record tags stored in the clear.


Instruction:
How would you explain what the following Python 3 function does
def encr_tags(self) -> dict:

        return {t: self._tags[t] for t in self.tags or {} if not t.startswith('~')} or None

Response: Accessor for record tags stored encrypted.


Instruction:
Write a Python 3 function for
fetching a dict of all hash suffixes from Pwned Passwords for a given a SHA - 1 prefix.

Response:
def _get_pwned(prefix):
    """
    Fetches a dict of all hash suffixes from Pwned Passwords for a
    given SHA-1 prefix.

    """
    try:
        response = requests.get(
            url=API_ENDPOINT.format(prefix),
            headers={'User-Agent': USER_AGENT},
            timeout=getattr(
                settings,
                'PWNED_PASSWORDS_API_TIMEOUT',
                REQUEST_TIMEOUT,
            ),
        )
        response.raise_for_status()
    except requests.RequestException as e:
        # Gracefully handle timeouts and HTTP error response codes.
        log.warning(
            'Skipped Pwned Passwords check due to error: %r', e
        )
        return None

    results = {}
    for line in response.text.splitlines():
        line_suffix, _, times = line.partition(':')
        results[line_suffix] = int(times)

    return results


Instruction:
Make a summary of the following Python 3 code
def pwned_password(password):
    if not isinstance(password, text_type):
        raise TypeError('Password values to check must be Unicode strings.')
    password_hash = hashlib.sha1(password.encode('utf-8')).hexdigest().upper()
    prefix, suffix = password_hash[:5], password_hash[5:]
    results = _get_pwned(prefix)
    if results is None:
        # Gracefully handle timeouts and HTTP error response codes.
        return None
    return results.get(suffix, 0)

Response: Checks a password against the Pwned Passwords database.


Instruction:
Make a summary of the following Python 3 code
def add_regularizer(self, proxfun, **kwargs):

        # if proxfun is a string, grab the corresponding function from operators.py
        if isinstance(proxfun, str):
            try:
                proxfun_name = proxfun.split(None, 1)[0]
                # Ignore everything after white space
                op = getattr(operators, proxfun_name)
                self.objectives.append(lambda theta, rho: op(theta.copy(), float(rho), **kwargs))

            except AttributeError as e:
                print(str(e) + '\n' + 'Could not find the function ' + proxfun + ' in the operators module!')

        # if proxfun is a function, add it as its own proximal operator
        elif hasattr(proxfun, '__call__'):
            self.objectives.append(lambda theta, rho: proxfun(theta.copy(), float(rho)))

        # type of proxfun must be a string or a function
        else:
            raise TypeError('The argument "proxfun" must be a string or a function!')

Response: Adds a regularizer to the objectives list for the given function in the operators module.


Instruction:
Can you create a Python 3 function that
adds a set of regularizers to the set of regularizers.

Response:
def set_regularizers(self, regularizers, clear=True):
        """
        Adds a set of regularizers

        Parameters
        ----------
        regularizers : dict
            Each key is the name of a corresponding proximal operator, and the
            value associated with that key is a set of keyword arguments

        clear : boolean, optional
            Whether or not to clear the existing regularizers. (Default: True)

        """

        # clear existing operators
        if clear:
            self.clear()

        # add new regularizers
        list([self.add_regularizer(proxfun, **regularizers[proxfun])
              for proxfun in regularizers.keys()])


Instruction:
Can you tell what is the following Python 3 function doing
def minimize(self, theta_init, max_iter=50, callback=None, disp=0, tau=(10., 2., 2.), tol=1e-3):

        # get list of objectives for this parameter
        num_obj = len(self.objectives)
        assert num_obj >= 1, "There must be at least one objective!"

        # initialize lists of primal and dual variable copies, one for each objective
        orig_shape = theta_init.shape
        primals = [theta_init.flatten() for _ in range(num_obj)]
        duals = [np.zeros(theta_init.size) for _ in range(num_obj)]
        theta_avg = np.mean(primals, axis=0).ravel()

        # initialize penalty parameter
        tau = namedtuple('tau', ('init', 'inc', 'dec'))(*tau)
        rho = tau.init

        # store cumulative runtimes of each iteration, starting now
        tstart = time.time()

        # clear metadata
        self.metadata = defaultdict(list)

        # run ADMM iterations
        self.converged = False
        for cur_iter in range(max_iter):

            # store the parameters from the previous iteration
            theta_prev = theta_avg

            # update each primal variable copy by taking a proximal step via each objective
            for varidx, dual in enumerate(duals):
                primals[varidx] = self.objectives[varidx]((theta_prev - dual).reshape(orig_shape), rho).ravel()

            # average primal copies
            theta_avg = np.mean(primals, axis=0)

            # update the dual variables (after primal update has finished)
            for varidx, primal in enumerate(primals):
                duals[varidx] += primal - theta_avg

            # compute primal and dual residuals
            primal_resid = float(np.sum([np.linalg.norm(primal - theta_avg) for primal in primals]))
            dual_resid = num_obj * rho ** 2 * np.linalg.norm(theta_avg - theta_prev)

            # update penalty parameter according to primal and dual residuals
            # (see sect. 3.4.1 of the Boyd and Parikh ADMM paper)
            if primal_resid > tau.init * dual_resid:
                rho *= float(tau.inc)
            elif dual_resid > tau.init * primal_resid:
                rho /= float(tau.dec)

            # update metadata for this iteration
            self.metadata['Primal resid'].append(primal_resid)
            self.metadata['Dual resid'].append(dual_resid)
            self.metadata['Time (s)'].append(time.time() - tstart)
            self.metadata['rho'].append(rho)

            # invoke the callback function with the current parameters and
            # history
            if callback is not None:

                # get the metadata from this iteration
                data = valmap(last, self.metadata)

                callback(theta_avg.reshape(orig_shape), data)

            # update the display
            self.update_display(cur_iter + 1, disp)

            # check for convergence
            if (primal_resid <= tol) & (dual_resid <= tol):
                self.converged = True
                break

        # clean up display
        self.update_display(-1, disp)

        # store and return final parameters
        self.theta = theta_avg.reshape(orig_shape)
        return self.theta

Response: Minimize a list of objectives using a proximal consensus algorithm.


Instruction:
Can you create a Python 3 function that
updates the display of the current iteration.

Response:
def update_display(self, iteration, disp_level, col_width=12):  # pragma: no cover
        """
        Prints information about the optimization procedure to standard output

        Parameters
        ----------
        iteration : int
            The current iteration. Must either a positive integer or -1, which indicates the end of the algorithm

        disp_level : int
            An integer which controls how much information to display, ranging from 0 (nothing) to 3 (lots of stuff)

        col_width : int
            The width of each column in the data table, used if disp_level > 1
        """

        # exit and print nothing if disp_level is zero
        if disp_level == 0:
            return

        else:

            # simple update, no table
            if disp_level == 1 and iteration >= 0:
                print('[Iteration %i]' % iteration)

            # fancy table updates
            if disp_level > 1:

                # get the metadata from this iteration
                data = valmap(last, self.metadata)

                # choose what keys to use
                keys = ['Time (s)', 'Primal resid', 'Dual resid', 'rho']

                # initial update. print out table headers
                if iteration == 1:
                    print(tableprint.header(keys, width=col_width))

                # print data
                print(tableprint.row([data[k] for k in keys], width=col_width, format_spec='4g'))

                if iteration == -1:
                    print(tableprint.bottom(len(keys), width=col_width) + '\n')

            # print convergence statement
            if iteration == -1 and self.converged:
                print('Converged after %i iterations!' % len(self.metadata['Primal resid']))


Instruction:
Make a summary of the following Python 3 code
def susvd(x, x_obs, rho, penalties):

    assert type(x) == Tensor, "Input array must be a Tensor"

    while True:

        # proximal operator for the Fro. norm
        x = squared_error(x, rho, x_obs)

        # sequential singular value thresholding
        for ix, penalty in enumerate(penalties):
            x = x.unfold(ix).svt(penalty / rho).fold()

        yield x

Response: Sequential unfolding SVD generator.


Instruction:
Can you write a function in Python 3 where it
builds the bytes from the python object.

Response:
def build(self, obj, context=None) -> bytes:
        """
        Build bytes from the python object.

        :param obj: Python object to build bytes from.
        :param context: Optional context dictionary.
        """
        stream = BytesIO()
        self.build_stream(obj, stream, context)
        return stream.getvalue()


Instruction:
Can you write a function in Python 3 where it
parses some python object from the data.

Response:
def parse(self, data: bytes, context=None):
        """
        Parse some python object from the data.

        :param data: Data to be parsed.
        :param context: Optional context dictionary.
        """
        stream = BytesIO(data)
        return self.parse_stream(stream, context)


Instruction:
Here you have a function in Python 3, explain what it does
def build_stream(self, obj, stream: BytesIO, context=None) -> None:
        if context is None:
            context = Context()
        if not isinstance(context, Context):
            context = Context(context)
        try:
            self._build_stream(obj, stream, context)
        except Error:
            raise
        except Exception as exc:
            raise BuildingError(str(exc))

Response: Builds bytes from the python object into the stream.


Instruction:
Here you have a function in Python 3, explain what it does
def parse_stream(self, stream: BytesIO, context=None):
        if context is None:
            context = Context()
        if not isinstance(context, Context):
            context = Context(context)
        try:
            return self._parse_stream(stream, context)
        except Error:
            raise
        except Exception as exc:
            raise ParsingError(str(exc))

Response: Parse some python object from the stream.


Instruction:
Can you create a Python 3 function that
returns the size of the construct in bytes.

Response:
def sizeof(self, context=None) -> int:
        """
        Return the size of the construct in bytes.

        :param context: Optional context dictionary.
        """
        if context is None:
            context = Context()
        if not isinstance(context, Context):
            context = Context(context)
        try:
            return self._sizeof(context)
        except Error:
            raise
        except Exception as exc:
            raise SizeofError(str(exc))


Instruction:
Explain what the following Python 3 code does
def poissreg(x0, rho, x, y):

    # objective and gradient
    n = float(x.shape[0])
    f = lambda w: np.mean(np.exp(x.dot(w)) - y * x.dot(w))
    df = lambda w: (x.T.dot(np.exp(x.dot(w))) - x.T.dot(y)) / n

    # minimize via BFGS
    return bfgs(x0, rho, f, df)

Response: Proximal operator for Poisson regression


Instruction:
Can you generate a brief explanation for the following Python 3 code
def smooth(x0, rho, gamma, axis=0):

    # Apply Laplacian smoothing
    n = x0.shape[axis]
    lap_op = spdiags([(2 + rho / gamma) * np.ones(n), -1 * np.ones(n), -1 * np.ones(n)], [0, -1, 1], n, n, format='csc')
    x_out = np.rollaxis(spsolve(gamma * lap_op, rho * np.rollaxis(x0, axis, 0)), axis, 0)

    return x_out

Response: Proximal operator for a smoothing function enforced via the discrete laplacian operator


Instruction:
Can you generate the documentation for the following Python 3 function
def nucnorm(x0, rho, gamma):

    # compute SVD
    u, s, v = np.linalg.svd(x0, full_matrices=False)

    # soft threshold the singular values
    sthr = np.maximum(s - (gamma / float(rho)), 0)

    # reconstruct
    x_out = (u.dot(np.diag(sthr)).dot(v))

    return x_out

Response: Proximal operator for the nuclear norm


Instruction:
Can you generate the documentation for the following Python 3 function
def tvd(x0, rho, gamma):
    try:
        from skimage.restoration import denoise_tv_bregman
    except ImportError:
        print('Error: scikit-image not found. TVD will not work.')
        return x0

    return denoise_tv_bregman(x0, rho / gamma)

Response: Returns the TVD of the total variation of the TVD.


Instruction:
How would you explain what the following Python 3 function does
def sparse(x0, rho, gamma):

    lmbda = float(gamma) / rho

    return (x0 - lmbda) * (x0 >= lmbda) + (x0 + lmbda) * (x0 <= -lmbda)

Response: This function computes the sparse operator for the l1 norm of the current node.


Instruction:
Make a summary of the following Python 3 code
def linsys(x0, rho, P, q):
    return np.linalg.solve(rho * np.eye(q.shape[0]) + P, rho * x0.copy() + q)

Response: Proximal operator for the linear approximation of the function Ax = b.


Instruction:
Make a summary of the following Python 3 code
def headerlist(self):
        if 'Content-Type' not in self.headers:
            self.headers.add_header('Content-Type', self.default_content_type)
        if self._cookies:
            for c in self._cookies.values():
                self.headers.add_header('Set-Cookie', c.OutputString())
        return self.headers.items()

Response: WSGI conform list of ( header value ) tuples.


Instruction:
Here you have a function in Python 3, explain what it does
def assert_redirect(self, response, expected_url=None):
        self.assertIn(
            response.status_code,
            self.redirect_codes,
            self._get_redirect_assertion_message(response),
        )
        if expected_url:
            location_header = response._headers.get('location', None)
            self.assertEqual(
                location_header,
                ('Location', str(expected_url)),
                'Response should redirect to {0}, but it redirects to {1} instead'.format(
                    expected_url,
                    location_header[1],
                )
            )

Response: Assert that the response is redirected to the expected_url.


Instruction:
Can you implement a function in Python 3 that
checks if a model instance was created in the database.

Response:
def assert_instance_created(self, model_class, **kwargs):
        """
        Checks if a model instance was created in the database.

        For example::

        >>> with self.assert_instance_created(Article, slug='lorem-ipsum'):
        ...     Article.objects.create(slug='lorem-ipsum')
        """
        return _InstanceContext(
            self.assert_instance_does_not_exist,
            self.assert_instance_exists,
            model_class,
            **kwargs
        )


Instruction:
Implement a Python 3 function for
checking if the model instance was deleted from the database.

Response:
def assert_instance_deleted(self, model_class, **kwargs):
        """
        Checks if the model instance was deleted from the database.

        For example::

        >>> with self.assert_instance_deleted(Article, slug='lorem-ipsum'):
        ...     Article.objects.get(slug='lorem-ipsum').delete()
        """
        return _InstanceContext(
            self.assert_instance_exists,
            self.assert_instance_does_not_exist,
            model_class,
            **kwargs
        )


Instruction:
Can you tell what is the following Python 3 function doing
def _split_into_mimetype_and_priority(x):
    if ';' in x:
        content_type, priority = x.split(';')
        casted_priority = float(priority.split('=')[1])
    else:
        content_type, casted_priority = x, 1.0

    content_type = content_type.lstrip().rstrip()  # Replace ' text/html' to 'text/html'
    return content_type, casted_priority

Response: Split an accept header item into mimetype and priority.


Instruction:
Can you implement a function in Python 3 that
parses and sort the accept header items.

Response:
def _parse_and_sort_accept_header(accept_header):
    """Parse and sort the accept header items.

    >>> _parse_and_sort_accept_header('application/json;q=0.5, text/*')
    [('text/*', 1.0), ('application/json', 0.5)]
    """
    return sorted([_split_into_mimetype_and_priority(x) for x in accept_header.split(',')],
                  key=lambda x: x[1], reverse=True)


Instruction:
Write a Python 3 script for
returning a mimetype best matched the accept headers.

Response:
def accept_best_match(accept_header, mimetypes):
    """Return a mimetype best matched the accept headers.

    >>> accept_best_match('application/json, text/html', ['application/json', 'text/plain'])
    'application/json'

    >>> accept_best_match('application/json;q=0.5, text/*', ['application/json', 'text/plain'])
    'text/plain'
    """
    for mimetype_pattern, _ in _parse_and_sort_accept_header(accept_header):
        matched_types = fnmatch.filter(mimetypes, mimetype_pattern)
        if matched_types:
            return matched_types[0]
    return mimetypes[0]


Instruction:
Write a Python 3 function for
matching types of url vars.

Response:
def match_url_vars_type(url_vars, type_hints):
    """ Match types of url vars.

    >>> match_url_vars_type({'user_id': '1'}, {'user_id': int})
    (True, {'user_id': 1})
    >>> match_url_vars_type({'user_id': 'foo'}, {'user_id': int})
    (False, {})
    """
    typed_url_vars = {}
    try:
        for k, v in url_vars.items():
            arg_type = type_hints.get(k)
            if arg_type and arg_type != str:
                typed_url_vars[k] = arg_type(v)
            else:
                typed_url_vars[k] = v
    except ValueError:
        return False, {}
    return True, typed_url_vars


Instruction:
Can you generate the documentation for the following Python 3 function
def match_path(rule, path):
    split_rule = split_by_slash(rule)
    split_path = split_by_slash(path)
    url_vars = {}

    if len(split_rule) != len(split_path):
        return False, {}

    for r, p in zip(split_rule, split_path):
        if r.startswith('{') and r.endswith('}'):
            url_vars[r[1:-1]] = p
            continue
        if r != p:
            return False, {}
    return True, url_vars

Response: Match a path to a rule.


Instruction:
Can you tell what is the following Python 3 function doing
def match(self, path, method):
        if path != '/':
            path = path.rstrip('/')
        method = method.upper()

        status = 404
        for p, n, m in self.endpoints:
            matched, url_vars = match_path(p, path)
            if not matched:  # path: not matched
                continue

            if method not in m:  # path: matched, method: not matched
                status = 405
                raise HTTPError(status=status, body=f'Method not found: {path} {method}')  # it has security issue??

            callback, type_hints = m[method]
            type_matched, typed_url_vars = match_url_vars_type(url_vars, type_hints)
            if not type_matched:
                continue  # path: not matched (types are different)
            return callback, typed_url_vars
        raise HTTPError(status=status, body=f'Not found: {path}')

Response: Match the given path and method.


Instruction:
Create a Python 3 function for
adding a new rule or replace an existing rule.

Response:
def add(self, rule, method, name, callback):
        """ Add a new rule or replace the target for an existing rule.

        >>> from kobin import Response
        >>> r = Router()
        >>> def view(user_id: int) -> Response:
        ...     return Response(f'You are {user_id}')
        ...
        >>> r.add('/users/{user_id}', 'GET', 'user-detail', view)
        >>> path, name, methods = r.endpoints[0]
        >>> path
        '/users/{user_id}'
        >>> name
        'user-detail'
        >>> callback, type_hints = methods['GET']
        >>> view == callback
        True
        >>> type_hints['user_id'] == int
        True
        """
        if rule != '/':
            rule = rule.rstrip('/')
        method = method.upper()

        for i, e in enumerate(self.endpoints):
            r, n, callbacks = e
            if r == rule:
                assert name == n and n is not None, (
                    "A same path should set a same name for reverse routing."
                )
                callbacks[method] = (callback, get_type_hints(callback))
                self.endpoints[i] = (r, name, callbacks)
                break
        else:
            e = (rule, name, {method: (callback, get_type_hints(callback))})
            self.endpoints.append(e)


Instruction:
Implement a Python 3 function for
reversing routing. >>> from kobin import Response >>> r = Router() >>> def view(user_id: int) -> Response: ... return Response(f'You are {user_id}') ... >>> r.add('/users/{user_id}', 'GET', 'user-detail', view) >>> r.reverse('user-detail', user_id=1) '/users/1'

Response:
def reverse(self, name, **kwargs):
        """ Reverse routing.

        >>> from kobin import Response
        >>> r = Router()
        >>> def view(user_id: int) -> Response:
        ...     return Response(f'You are {user_id}')
        ...
        >>> r.add('/users/{user_id}', 'GET', 'user-detail', view)
        >>> r.reverse('user-detail', user_id=1)
        '/users/1'
        """
        for p, n, _ in self.endpoints:
            if name == n:
                return p.format(**kwargs)


Instruction:
How would you explain what the following Python 3 function does
def set(self, value):
        '''
        Atomically sets the value to `value`.

        :param value: The value to set.
        '''
        with self._lock.exclusive:
            self._value = value
            return value

Response: Atomically sets the value to value.


Instruction:
Given the following Python 3 function, write the documentation
def get_and_set(self, value):
        '''
        Atomically sets the value to `value` and returns the old value.

        :param value: The value to set.
        '''
        with self._lock.exclusive:
            oldval = self._value
            self._value = value
            return oldval

Response: Atomically sets the value to value and returns the old value.


Instruction:
Can you write a function in Python 3 where it
compares the current value of the current object with the expected value and set the value to update if the current value is equal to the expect value.

Response:
def compare_and_set(self, expect, update):
        '''
        Atomically sets the value to `update` if the current value is equal to
        `expect`.

        :param expect: The expected current value.
        :param update: The value to set if and only if `expect` equals the
            current value.
        '''
        with self._lock.exclusive:
            if self._value == expect:
                self._value = update
                return True

            return False


Instruction:
Can you tell what is the following Python 3 function doing
def add_and_get(self, delta):
        '''
        Atomically adds `delta` to the current value.

        :param delta: The delta to add.
        '''
        with self._lock.exclusive:
            self._value += delta
            return self._value

Response: Atomically adds delta to the current value.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_and_add(self, delta):
        '''
        Atomically adds `delta` to the current value and returns the old value.

        :param delta: The delta to add.
        '''
        with self._lock.exclusive:
            oldval = self._value
            self._value += delta
            return oldval

Response: Atomically adds delta to the current value and returns the old value.


Instruction:
How would you code a function in Python 3 to
subtract delta from the current value and returns the old value.

Response:
def subtract_and_get(self, delta):
        '''
        Atomically subtracts `delta` from the current value.

        :param delta: The delta to subtract.
        '''
        with self._lock.exclusive:
            self._value -= delta
            return self._value


Instruction:
Can you implement a function in Python 3 that
notifies all the watches that a new value has changed.

Response:
def notify_watches(self, oldval, newval):
        '''
        Passes `oldval` and `newval` to each `fn` in the watches dictionary,
        passing along its respective key and the reference to this object.

        :param oldval: The old value which will be passed to the watch.
        :param newval: The new value which will be passed to the watch.
        '''
        watches = self._watches.copy()
        for k in watches:
            fn = watches[k]
            if isinstance(fn, collections.Callable):
                fn(k, self, oldval, newval)


Instruction:
Can you tell what is the following Python 3 function doing
def swap(self, fn, *args, **kwargs):
        '''
        Given a mutator `fn`, calls `fn` with the atom's current state, `args`,
        and `kwargs`. The return value of this invocation becomes the new value
        of the atom. Returns the new value.

        :param fn: A function which will be passed the current state. Should
            return a new state. This absolutely *MUST NOT* mutate the
            reference to the current state! If it does, this function may loop
            indefinitely.
        :param \*args: Arguments to be passed to `fn`.
        :param \*\*kwargs: Keyword arguments to be passed to `fn`.
        '''
        while True:
            oldval = self.deref()
            newval = fn(oldval, *args, **kwargs)
            if self._state.compare_and_set(oldval, newval):
                self.notify_watches(oldval, newval)
                return newval

Response: Given a mutator fn calls the atom s current state with the current state args and kwargs returns the new value.