id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
2,500
oceanprotocol/squid-py
squid_py/ddo/public_key_rsa.py
PublicKeyRSA.set_encode_key_value
def set_encode_key_value(self, value, store_type=PUBLIC_KEY_STORE_TYPE_BASE64): """Set the value based on the type of encoding supported by RSA.""" if store_type == PUBLIC_KEY_STORE_TYPE_PEM: PublicKeyBase.set_encode_key_value(self, value.exportKey('PEM').decode(), store_type) else: PublicKeyBase.set_encode_key_value(self, value.exportKey('DER'), store_type)
python
def set_encode_key_value(self, value, store_type=PUBLIC_KEY_STORE_TYPE_BASE64): """Set the value based on the type of encoding supported by RSA.""" if store_type == PUBLIC_KEY_STORE_TYPE_PEM: PublicKeyBase.set_encode_key_value(self, value.exportKey('PEM').decode(), store_type) else: PublicKeyBase.set_encode_key_value(self, value.exportKey('DER'), store_type)
[ "def", "set_encode_key_value", "(", "self", ",", "value", ",", "store_type", "=", "PUBLIC_KEY_STORE_TYPE_BASE64", ")", ":", "if", "store_type", "==", "PUBLIC_KEY_STORE_TYPE_PEM", ":", "PublicKeyBase", ".", "set_encode_key_value", "(", "self", ",", "value", ".", "exportKey", "(", "'PEM'", ")", ".", "decode", "(", ")", ",", "store_type", ")", "else", ":", "PublicKeyBase", ".", "set_encode_key_value", "(", "self", ",", "value", ".", "exportKey", "(", "'DER'", ")", ",", "store_type", ")" ]
Set the value based on the type of encoding supported by RSA.
[ "Set", "the", "value", "based", "on", "the", "type", "of", "encoding", "supported", "by", "RSA", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/public_key_rsa.py#L27-L32
2,501
oceanprotocol/squid-py
squid_py/did.py
did_parse
def did_parse(did): """ Parse a DID into it's parts. :param did: Asset did, str. :return: Python dictionary with the method and the id. """ if not isinstance(did, str): raise TypeError(f'Expecting DID of string type, got {did} of {type(did)} type') match = re.match('^did:([a-z0-9]+):([a-zA-Z0-9-.]+)(.*)', did) if not match: raise ValueError(f'DID {did} does not seem to be valid.') result = { 'method': match.group(1), 'id': match.group(2), } return result
python
def did_parse(did): """ Parse a DID into it's parts. :param did: Asset did, str. :return: Python dictionary with the method and the id. """ if not isinstance(did, str): raise TypeError(f'Expecting DID of string type, got {did} of {type(did)} type') match = re.match('^did:([a-z0-9]+):([a-zA-Z0-9-.]+)(.*)', did) if not match: raise ValueError(f'DID {did} does not seem to be valid.') result = { 'method': match.group(1), 'id': match.group(2), } return result
[ "def", "did_parse", "(", "did", ")", ":", "if", "not", "isinstance", "(", "did", ",", "str", ")", ":", "raise", "TypeError", "(", "f'Expecting DID of string type, got {did} of {type(did)} type'", ")", "match", "=", "re", ".", "match", "(", "'^did:([a-z0-9]+):([a-zA-Z0-9-.]+)(.*)'", ",", "did", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "f'DID {did} does not seem to be valid.'", ")", "result", "=", "{", "'method'", ":", "match", ".", "group", "(", "1", ")", ",", "'id'", ":", "match", ".", "group", "(", "2", ")", ",", "}", "return", "result" ]
Parse a DID into it's parts. :param did: Asset did, str. :return: Python dictionary with the method and the id.
[ "Parse", "a", "DID", "into", "it", "s", "parts", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/did.py#L31-L50
2,502
oceanprotocol/squid-py
squid_py/did.py
id_to_did
def id_to_did(did_id, method='op'): """Return an Ocean DID from given a hex id.""" if isinstance(did_id, bytes): did_id = Web3.toHex(did_id) # remove leading '0x' of a hex string if isinstance(did_id, str): did_id = remove_0x_prefix(did_id) else: raise TypeError("did id must be a hex string or bytes") # test for zero address if Web3.toBytes(hexstr=did_id) == b'': did_id = '0' return f'did:{method}:{did_id}'
python
def id_to_did(did_id, method='op'): """Return an Ocean DID from given a hex id.""" if isinstance(did_id, bytes): did_id = Web3.toHex(did_id) # remove leading '0x' of a hex string if isinstance(did_id, str): did_id = remove_0x_prefix(did_id) else: raise TypeError("did id must be a hex string or bytes") # test for zero address if Web3.toBytes(hexstr=did_id) == b'': did_id = '0' return f'did:{method}:{did_id}'
[ "def", "id_to_did", "(", "did_id", ",", "method", "=", "'op'", ")", ":", "if", "isinstance", "(", "did_id", ",", "bytes", ")", ":", "did_id", "=", "Web3", ".", "toHex", "(", "did_id", ")", "# remove leading '0x' of a hex string", "if", "isinstance", "(", "did_id", ",", "str", ")", ":", "did_id", "=", "remove_0x_prefix", "(", "did_id", ")", "else", ":", "raise", "TypeError", "(", "\"did id must be a hex string or bytes\"", ")", "# test for zero address", "if", "Web3", ".", "toBytes", "(", "hexstr", "=", "did_id", ")", "==", "b''", ":", "did_id", "=", "'0'", "return", "f'did:{method}:{did_id}'" ]
Return an Ocean DID from given a hex id.
[ "Return", "an", "Ocean", "DID", "from", "given", "a", "hex", "id", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/did.py#L69-L83
2,503
oceanprotocol/squid-py
squid_py/did.py
did_to_id_bytes
def did_to_id_bytes(did): """ Return an Ocean DID to it's correspondng hex id in bytes. So did:op:<hex>, will return <hex> in byte format """ if isinstance(did, str): if re.match('^[0x]?[0-9A-Za-z]+$', did): raise ValueError(f'{did} must be a DID not a hex string') else: did_result = did_parse(did) if not did_result: raise ValueError(f'{did} is not a valid did') if not did_result['id']: raise ValueError(f'{did} is not a valid ocean did') id_bytes = Web3.toBytes(hexstr=did_result['id']) elif isinstance(did, bytes): id_bytes = did else: raise TypeError( f'Unknown did format, expected str or bytes, got {did} of type {type(did)}') return id_bytes
python
def did_to_id_bytes(did): """ Return an Ocean DID to it's correspondng hex id in bytes. So did:op:<hex>, will return <hex> in byte format """ if isinstance(did, str): if re.match('^[0x]?[0-9A-Za-z]+$', did): raise ValueError(f'{did} must be a DID not a hex string') else: did_result = did_parse(did) if not did_result: raise ValueError(f'{did} is not a valid did') if not did_result['id']: raise ValueError(f'{did} is not a valid ocean did') id_bytes = Web3.toBytes(hexstr=did_result['id']) elif isinstance(did, bytes): id_bytes = did else: raise TypeError( f'Unknown did format, expected str or bytes, got {did} of type {type(did)}') return id_bytes
[ "def", "did_to_id_bytes", "(", "did", ")", ":", "if", "isinstance", "(", "did", ",", "str", ")", ":", "if", "re", ".", "match", "(", "'^[0x]?[0-9A-Za-z]+$'", ",", "did", ")", ":", "raise", "ValueError", "(", "f'{did} must be a DID not a hex string'", ")", "else", ":", "did_result", "=", "did_parse", "(", "did", ")", "if", "not", "did_result", ":", "raise", "ValueError", "(", "f'{did} is not a valid did'", ")", "if", "not", "did_result", "[", "'id'", "]", ":", "raise", "ValueError", "(", "f'{did} is not a valid ocean did'", ")", "id_bytes", "=", "Web3", ".", "toBytes", "(", "hexstr", "=", "did_result", "[", "'id'", "]", ")", "elif", "isinstance", "(", "did", ",", "bytes", ")", ":", "id_bytes", "=", "did", "else", ":", "raise", "TypeError", "(", "f'Unknown did format, expected str or bytes, got {did} of type {type(did)}'", ")", "return", "id_bytes" ]
Return an Ocean DID to it's correspondng hex id in bytes. So did:op:<hex>, will return <hex> in byte format
[ "Return", "an", "Ocean", "DID", "to", "it", "s", "correspondng", "hex", "id", "in", "bytes", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/did.py#L94-L115
2,504
oceanprotocol/squid-py
squid_py/keeper/templates/template_manager.py
TemplateStoreManager.get_template
def get_template(self, template_id): """ Get the template for a given template id. :param template_id: id of the template, str :return: """ template = self.contract_concise.getTemplate(template_id) if template and len(template) == 4: return AgreementTemplate(*template) return None
python
def get_template(self, template_id): """ Get the template for a given template id. :param template_id: id of the template, str :return: """ template = self.contract_concise.getTemplate(template_id) if template and len(template) == 4: return AgreementTemplate(*template) return None
[ "def", "get_template", "(", "self", ",", "template_id", ")", ":", "template", "=", "self", ".", "contract_concise", ".", "getTemplate", "(", "template_id", ")", "if", "template", "and", "len", "(", "template", ")", "==", "4", ":", "return", "AgreementTemplate", "(", "*", "template", ")", "return", "None" ]
Get the template for a given template id. :param template_id: id of the template, str :return:
[ "Get", "the", "template", "for", "a", "given", "template", "id", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/templates/template_manager.py#L19-L30
2,505
oceanprotocol/squid-py
squid_py/keeper/templates/template_manager.py
TemplateStoreManager.propose_template
def propose_template(self, template_id, from_account): """Propose a template. :param template_id: id of the template, str :param from_account: Account :return: bool """ tx_hash = self.send_transaction( 'proposeTemplate', (template_id,), transact={'from': from_account.address, 'passphrase': from_account.password}) return self.get_tx_receipt(tx_hash).status == 1
python
def propose_template(self, template_id, from_account): """Propose a template. :param template_id: id of the template, str :param from_account: Account :return: bool """ tx_hash = self.send_transaction( 'proposeTemplate', (template_id,), transact={'from': from_account.address, 'passphrase': from_account.password}) return self.get_tx_receipt(tx_hash).status == 1
[ "def", "propose_template", "(", "self", ",", "template_id", ",", "from_account", ")", ":", "tx_hash", "=", "self", ".", "send_transaction", "(", "'proposeTemplate'", ",", "(", "template_id", ",", ")", ",", "transact", "=", "{", "'from'", ":", "from_account", ".", "address", ",", "'passphrase'", ":", "from_account", ".", "password", "}", ")", "return", "self", ".", "get_tx_receipt", "(", "tx_hash", ")", ".", "status", "==", "1" ]
Propose a template. :param template_id: id of the template, str :param from_account: Account :return: bool
[ "Propose", "a", "template", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/templates/template_manager.py#L32-L44
2,506
oceanprotocol/squid-py
squid_py/agreements/service_factory.py
ServiceDescriptor.access_service_descriptor
def access_service_descriptor(price, consume_endpoint, service_endpoint, timeout, template_id): """ Access service descriptor. :param price: Asset price, int :param consume_endpoint: url of the service provider, str :param service_endpoint: identifier of the service inside the asset DDO, str :param timeout: amount of time in seconds before the agreement expires, int :param template_id: id of the template use to create the service, str :return: Service descriptor. """ return (ServiceTypes.ASSET_ACCESS, {'price': price, 'consumeEndpoint': consume_endpoint, 'serviceEndpoint': service_endpoint, 'timeout': timeout, 'templateId': template_id})
python
def access_service_descriptor(price, consume_endpoint, service_endpoint, timeout, template_id): """ Access service descriptor. :param price: Asset price, int :param consume_endpoint: url of the service provider, str :param service_endpoint: identifier of the service inside the asset DDO, str :param timeout: amount of time in seconds before the agreement expires, int :param template_id: id of the template use to create the service, str :return: Service descriptor. """ return (ServiceTypes.ASSET_ACCESS, {'price': price, 'consumeEndpoint': consume_endpoint, 'serviceEndpoint': service_endpoint, 'timeout': timeout, 'templateId': template_id})
[ "def", "access_service_descriptor", "(", "price", ",", "consume_endpoint", ",", "service_endpoint", ",", "timeout", ",", "template_id", ")", ":", "return", "(", "ServiceTypes", ".", "ASSET_ACCESS", ",", "{", "'price'", ":", "price", ",", "'consumeEndpoint'", ":", "consume_endpoint", ",", "'serviceEndpoint'", ":", "service_endpoint", ",", "'timeout'", ":", "timeout", ",", "'templateId'", ":", "template_id", "}", ")" ]
Access service descriptor. :param price: Asset price, int :param consume_endpoint: url of the service provider, str :param service_endpoint: identifier of the service inside the asset DDO, str :param timeout: amount of time in seconds before the agreement expires, int :param template_id: id of the template use to create the service, str :return: Service descriptor.
[ "Access", "service", "descriptor", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L42-L56
2,507
oceanprotocol/squid-py
squid_py/agreements/service_factory.py
ServiceDescriptor.compute_service_descriptor
def compute_service_descriptor(price, consume_endpoint, service_endpoint, timeout): """ Compute service descriptor. :param price: Asset price, int :param consume_endpoint: url of the service provider, str :param service_endpoint: identifier of the service inside the asset DDO, str :param timeout: amount of time in seconds before the agreement expires, int :return: Service descriptor. """ return (ServiceTypes.CLOUD_COMPUTE, {'price': price, 'consumeEndpoint': consume_endpoint, 'serviceEndpoint': service_endpoint, 'timeout': timeout})
python
def compute_service_descriptor(price, consume_endpoint, service_endpoint, timeout): """ Compute service descriptor. :param price: Asset price, int :param consume_endpoint: url of the service provider, str :param service_endpoint: identifier of the service inside the asset DDO, str :param timeout: amount of time in seconds before the agreement expires, int :return: Service descriptor. """ return (ServiceTypes.CLOUD_COMPUTE, {'price': price, 'consumeEndpoint': consume_endpoint, 'serviceEndpoint': service_endpoint, 'timeout': timeout})
[ "def", "compute_service_descriptor", "(", "price", ",", "consume_endpoint", ",", "service_endpoint", ",", "timeout", ")", ":", "return", "(", "ServiceTypes", ".", "CLOUD_COMPUTE", ",", "{", "'price'", ":", "price", ",", "'consumeEndpoint'", ":", "consume_endpoint", ",", "'serviceEndpoint'", ":", "service_endpoint", ",", "'timeout'", ":", "timeout", "}", ")" ]
Compute service descriptor. :param price: Asset price, int :param consume_endpoint: url of the service provider, str :param service_endpoint: identifier of the service inside the asset DDO, str :param timeout: amount of time in seconds before the agreement expires, int :return: Service descriptor.
[ "Compute", "service", "descriptor", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L59-L72
2,508
oceanprotocol/squid-py
squid_py/agreements/service_factory.py
ServiceFactory.build_services
def build_services(did, service_descriptors): """ Build a list of services. :param did: DID, str :param service_descriptors: List of tuples of length 2. The first item must be one of ServiceTypes and the second item is a dict of parameters and values required by the service :return: List of Services """ services = [] sa_def_key = ServiceAgreement.SERVICE_DEFINITION_ID for i, service_desc in enumerate(service_descriptors): service = ServiceFactory.build_service(service_desc, did) # set serviceDefinitionId for each service service.update_value(sa_def_key, str(i)) services.append(service) return services
python
def build_services(did, service_descriptors): """ Build a list of services. :param did: DID, str :param service_descriptors: List of tuples of length 2. The first item must be one of ServiceTypes and the second item is a dict of parameters and values required by the service :return: List of Services """ services = [] sa_def_key = ServiceAgreement.SERVICE_DEFINITION_ID for i, service_desc in enumerate(service_descriptors): service = ServiceFactory.build_service(service_desc, did) # set serviceDefinitionId for each service service.update_value(sa_def_key, str(i)) services.append(service) return services
[ "def", "build_services", "(", "did", ",", "service_descriptors", ")", ":", "services", "=", "[", "]", "sa_def_key", "=", "ServiceAgreement", ".", "SERVICE_DEFINITION_ID", "for", "i", ",", "service_desc", "in", "enumerate", "(", "service_descriptors", ")", ":", "service", "=", "ServiceFactory", ".", "build_service", "(", "service_desc", ",", "did", ")", "# set serviceDefinitionId for each service", "service", ".", "update_value", "(", "sa_def_key", ",", "str", "(", "i", ")", ")", "services", ".", "append", "(", "service", ")", "return", "services" ]
Build a list of services. :param did: DID, str :param service_descriptors: List of tuples of length 2. The first item must be one of ServiceTypes and the second item is a dict of parameters and values required by the service :return: List of Services
[ "Build", "a", "list", "of", "services", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L79-L97
2,509
oceanprotocol/squid-py
squid_py/agreements/service_factory.py
ServiceFactory.build_service
def build_service(service_descriptor, did): """ Build a service. :param service_descriptor: Tuples of length 2. The first item must be one of ServiceTypes and the second item is a dict of parameters and values required by the service :param did: DID, str :return: Service """ assert isinstance(service_descriptor, tuple) and len( service_descriptor) == 2, 'Unknown service descriptor format.' service_type, kwargs = service_descriptor if service_type == ServiceTypes.METADATA: return ServiceFactory.build_metadata_service( did, kwargs['metadata'], kwargs['serviceEndpoint'] ) elif service_type == ServiceTypes.AUTHORIZATION: return ServiceFactory.build_authorization_service( kwargs['serviceEndpoint'] ) elif service_type == ServiceTypes.ASSET_ACCESS: return ServiceFactory.build_access_service( did, kwargs['price'], kwargs['consumeEndpoint'], kwargs['serviceEndpoint'], kwargs['timeout'], kwargs['templateId'] ) elif service_type == ServiceTypes.CLOUD_COMPUTE: return ServiceFactory.build_compute_service( did, kwargs['price'], kwargs['consumeEndpoint'], kwargs['serviceEndpoint'], kwargs['timeout'] ) raise ValueError(f'Unknown service type {service_type}')
python
def build_service(service_descriptor, did): """ Build a service. :param service_descriptor: Tuples of length 2. The first item must be one of ServiceTypes and the second item is a dict of parameters and values required by the service :param did: DID, str :return: Service """ assert isinstance(service_descriptor, tuple) and len( service_descriptor) == 2, 'Unknown service descriptor format.' service_type, kwargs = service_descriptor if service_type == ServiceTypes.METADATA: return ServiceFactory.build_metadata_service( did, kwargs['metadata'], kwargs['serviceEndpoint'] ) elif service_type == ServiceTypes.AUTHORIZATION: return ServiceFactory.build_authorization_service( kwargs['serviceEndpoint'] ) elif service_type == ServiceTypes.ASSET_ACCESS: return ServiceFactory.build_access_service( did, kwargs['price'], kwargs['consumeEndpoint'], kwargs['serviceEndpoint'], kwargs['timeout'], kwargs['templateId'] ) elif service_type == ServiceTypes.CLOUD_COMPUTE: return ServiceFactory.build_compute_service( did, kwargs['price'], kwargs['consumeEndpoint'], kwargs['serviceEndpoint'], kwargs['timeout'] ) raise ValueError(f'Unknown service type {service_type}')
[ "def", "build_service", "(", "service_descriptor", ",", "did", ")", ":", "assert", "isinstance", "(", "service_descriptor", ",", "tuple", ")", "and", "len", "(", "service_descriptor", ")", "==", "2", ",", "'Unknown service descriptor format.'", "service_type", ",", "kwargs", "=", "service_descriptor", "if", "service_type", "==", "ServiceTypes", ".", "METADATA", ":", "return", "ServiceFactory", ".", "build_metadata_service", "(", "did", ",", "kwargs", "[", "'metadata'", "]", ",", "kwargs", "[", "'serviceEndpoint'", "]", ")", "elif", "service_type", "==", "ServiceTypes", ".", "AUTHORIZATION", ":", "return", "ServiceFactory", ".", "build_authorization_service", "(", "kwargs", "[", "'serviceEndpoint'", "]", ")", "elif", "service_type", "==", "ServiceTypes", ".", "ASSET_ACCESS", ":", "return", "ServiceFactory", ".", "build_access_service", "(", "did", ",", "kwargs", "[", "'price'", "]", ",", "kwargs", "[", "'consumeEndpoint'", "]", ",", "kwargs", "[", "'serviceEndpoint'", "]", ",", "kwargs", "[", "'timeout'", "]", ",", "kwargs", "[", "'templateId'", "]", ")", "elif", "service_type", "==", "ServiceTypes", ".", "CLOUD_COMPUTE", ":", "return", "ServiceFactory", ".", "build_compute_service", "(", "did", ",", "kwargs", "[", "'price'", "]", ",", "kwargs", "[", "'consumeEndpoint'", "]", ",", "kwargs", "[", "'serviceEndpoint'", "]", ",", "kwargs", "[", "'timeout'", "]", ")", "raise", "ValueError", "(", "f'Unknown service type {service_type}'", ")" ]
Build a service. :param service_descriptor: Tuples of length 2. The first item must be one of ServiceTypes and the second item is a dict of parameters and values required by the service :param did: DID, str :return: Service
[ "Build", "a", "service", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L100-L137
2,510
oceanprotocol/squid-py
squid_py/agreements/service_factory.py
ServiceFactory.build_metadata_service
def build_metadata_service(did, metadata, service_endpoint): """ Build a metadata service. :param did: DID, str :param metadata: conforming to the Metadata accepted by Ocean Protocol, dict :param service_endpoint: identifier of the service inside the asset DDO, str :return: Service """ return Service(service_endpoint, ServiceTypes.METADATA, values={'metadata': metadata}, did=did)
python
def build_metadata_service(did, metadata, service_endpoint): """ Build a metadata service. :param did: DID, str :param metadata: conforming to the Metadata accepted by Ocean Protocol, dict :param service_endpoint: identifier of the service inside the asset DDO, str :return: Service """ return Service(service_endpoint, ServiceTypes.METADATA, values={'metadata': metadata}, did=did)
[ "def", "build_metadata_service", "(", "did", ",", "metadata", ",", "service_endpoint", ")", ":", "return", "Service", "(", "service_endpoint", ",", "ServiceTypes", ".", "METADATA", ",", "values", "=", "{", "'metadata'", ":", "metadata", "}", ",", "did", "=", "did", ")" ]
Build a metadata service. :param did: DID, str :param metadata: conforming to the Metadata accepted by Ocean Protocol, dict :param service_endpoint: identifier of the service inside the asset DDO, str :return: Service
[ "Build", "a", "metadata", "service", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L140-L152
2,511
oceanprotocol/squid-py
squid_py/agreements/service_factory.py
ServiceFactory.build_access_service
def build_access_service(did, price, consume_endpoint, service_endpoint, timeout, template_id): """ Build the access service. :param did: DID, str :param price: Asset price, int :param consume_endpoint: url of the service provider, str :param service_endpoint: identifier of the service inside the asset DDO, str :param timeout: amount of time in seconds before the agreement expires, int :param template_id: id of the template use to create the service, str :return: ServiceAgreement """ # TODO fill all the possible mappings param_map = { '_documentId': did_to_id(did), '_amount': price, '_rewardAddress': Keeper.get_instance().escrow_reward_condition.address, } sla_template_path = get_sla_template_path() sla_template = ServiceAgreementTemplate.from_json_file(sla_template_path) sla_template.template_id = template_id conditions = sla_template.conditions[:] for cond in conditions: for param in cond.parameters: param.value = param_map.get(param.name, '') if cond.timeout > 0: cond.timeout = timeout sla_template.set_conditions(conditions) sa = ServiceAgreement( 1, sla_template, consume_endpoint, service_endpoint, ServiceTypes.ASSET_ACCESS ) sa.set_did(did) return sa
python
def build_access_service(did, price, consume_endpoint, service_endpoint, timeout, template_id): """ Build the access service. :param did: DID, str :param price: Asset price, int :param consume_endpoint: url of the service provider, str :param service_endpoint: identifier of the service inside the asset DDO, str :param timeout: amount of time in seconds before the agreement expires, int :param template_id: id of the template use to create the service, str :return: ServiceAgreement """ # TODO fill all the possible mappings param_map = { '_documentId': did_to_id(did), '_amount': price, '_rewardAddress': Keeper.get_instance().escrow_reward_condition.address, } sla_template_path = get_sla_template_path() sla_template = ServiceAgreementTemplate.from_json_file(sla_template_path) sla_template.template_id = template_id conditions = sla_template.conditions[:] for cond in conditions: for param in cond.parameters: param.value = param_map.get(param.name, '') if cond.timeout > 0: cond.timeout = timeout sla_template.set_conditions(conditions) sa = ServiceAgreement( 1, sla_template, consume_endpoint, service_endpoint, ServiceTypes.ASSET_ACCESS ) sa.set_did(did) return sa
[ "def", "build_access_service", "(", "did", ",", "price", ",", "consume_endpoint", ",", "service_endpoint", ",", "timeout", ",", "template_id", ")", ":", "# TODO fill all the possible mappings", "param_map", "=", "{", "'_documentId'", ":", "did_to_id", "(", "did", ")", ",", "'_amount'", ":", "price", ",", "'_rewardAddress'", ":", "Keeper", ".", "get_instance", "(", ")", ".", "escrow_reward_condition", ".", "address", ",", "}", "sla_template_path", "=", "get_sla_template_path", "(", ")", "sla_template", "=", "ServiceAgreementTemplate", ".", "from_json_file", "(", "sla_template_path", ")", "sla_template", ".", "template_id", "=", "template_id", "conditions", "=", "sla_template", ".", "conditions", "[", ":", "]", "for", "cond", "in", "conditions", ":", "for", "param", "in", "cond", ".", "parameters", ":", "param", ".", "value", "=", "param_map", ".", "get", "(", "param", ".", "name", ",", "''", ")", "if", "cond", ".", "timeout", ">", "0", ":", "cond", ".", "timeout", "=", "timeout", "sla_template", ".", "set_conditions", "(", "conditions", ")", "sa", "=", "ServiceAgreement", "(", "1", ",", "sla_template", ",", "consume_endpoint", ",", "service_endpoint", ",", "ServiceTypes", ".", "ASSET_ACCESS", ")", "sa", ".", "set_did", "(", "did", ")", "return", "sa" ]
Build the access service. :param did: DID, str :param price: Asset price, int :param consume_endpoint: url of the service provider, str :param service_endpoint: identifier of the service inside the asset DDO, str :param timeout: amount of time in seconds before the agreement expires, int :param template_id: id of the template use to create the service, str :return: ServiceAgreement
[ "Build", "the", "access", "service", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_factory.py#L166-L204
2,512
oceanprotocol/squid-py
squid_py/agreements/storage.py
record_service_agreement
def record_service_agreement(storage_path, service_agreement_id, did, service_definition_id, price, files, start_time, status='pending'): """ Records the given pending service agreement. :param storage_path: storage path for the internal db, str :param service_agreement_id: :param did: DID, str :param service_definition_id: identifier of the service inside the asset DDO, str :param price: Asset price, int :param files: :param start_time: :param status: :return: """ conn = sqlite3.connect(storage_path) try: cursor = conn.cursor() cursor.execute( '''CREATE TABLE IF NOT EXISTS service_agreements (id VARCHAR PRIMARY KEY, did VARCHAR, service_definition_id INTEGER, price INTEGER, files VARCHAR, start_time INTEGER, status VARCHAR(10));''' ) cursor.execute( 'INSERT OR REPLACE INTO service_agreements VALUES (?,?,?,?,?,?,?)', [service_agreement_id, did, service_definition_id, price, files, start_time, status], ) conn.commit() finally: conn.close()
python
def record_service_agreement(storage_path, service_agreement_id, did, service_definition_id, price, files, start_time, status='pending'): """ Records the given pending service agreement. :param storage_path: storage path for the internal db, str :param service_agreement_id: :param did: DID, str :param service_definition_id: identifier of the service inside the asset DDO, str :param price: Asset price, int :param files: :param start_time: :param status: :return: """ conn = sqlite3.connect(storage_path) try: cursor = conn.cursor() cursor.execute( '''CREATE TABLE IF NOT EXISTS service_agreements (id VARCHAR PRIMARY KEY, did VARCHAR, service_definition_id INTEGER, price INTEGER, files VARCHAR, start_time INTEGER, status VARCHAR(10));''' ) cursor.execute( 'INSERT OR REPLACE INTO service_agreements VALUES (?,?,?,?,?,?,?)', [service_agreement_id, did, service_definition_id, price, files, start_time, status], ) conn.commit() finally: conn.close()
[ "def", "record_service_agreement", "(", "storage_path", ",", "service_agreement_id", ",", "did", ",", "service_definition_id", ",", "price", ",", "files", ",", "start_time", ",", "status", "=", "'pending'", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "storage_path", ")", "try", ":", "cursor", "=", "conn", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "'''CREATE TABLE IF NOT EXISTS service_agreements\n (id VARCHAR PRIMARY KEY, did VARCHAR, service_definition_id INTEGER, \n price INTEGER, files VARCHAR, start_time INTEGER, status VARCHAR(10));'''", ")", "cursor", ".", "execute", "(", "'INSERT OR REPLACE INTO service_agreements VALUES (?,?,?,?,?,?,?)'", ",", "[", "service_agreement_id", ",", "did", ",", "service_definition_id", ",", "price", ",", "files", ",", "start_time", ",", "status", "]", ",", ")", "conn", ".", "commit", "(", ")", "finally", ":", "conn", ".", "close", "(", ")" ]
Records the given pending service agreement. :param storage_path: storage path for the internal db, str :param service_agreement_id: :param did: DID, str :param service_definition_id: identifier of the service inside the asset DDO, str :param price: Asset price, int :param files: :param start_time: :param status: :return:
[ "Records", "the", "given", "pending", "service", "agreement", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/storage.py#L8-L39
2,513
oceanprotocol/squid-py
squid_py/agreements/storage.py
update_service_agreement_status
def update_service_agreement_status(storage_path, service_agreement_id, status='pending'): """ Update the service agreement status. :param storage_path: storage path for the internal db, str :param service_agreement_id: :param status: :return: """ conn = sqlite3.connect(storage_path) try: cursor = conn.cursor() cursor.execute( 'UPDATE service_agreements SET status=? WHERE id=?', (status, service_agreement_id), ) conn.commit() finally: conn.close()
python
def update_service_agreement_status(storage_path, service_agreement_id, status='pending'): """ Update the service agreement status. :param storage_path: storage path for the internal db, str :param service_agreement_id: :param status: :return: """ conn = sqlite3.connect(storage_path) try: cursor = conn.cursor() cursor.execute( 'UPDATE service_agreements SET status=? WHERE id=?', (status, service_agreement_id), ) conn.commit() finally: conn.close()
[ "def", "update_service_agreement_status", "(", "storage_path", ",", "service_agreement_id", ",", "status", "=", "'pending'", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "storage_path", ")", "try", ":", "cursor", "=", "conn", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "'UPDATE service_agreements SET status=? WHERE id=?'", ",", "(", "status", ",", "service_agreement_id", ")", ",", ")", "conn", ".", "commit", "(", ")", "finally", ":", "conn", ".", "close", "(", ")" ]
Update the service agreement status. :param storage_path: storage path for the internal db, str :param service_agreement_id: :param status: :return:
[ "Update", "the", "service", "agreement", "status", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/storage.py#L42-L60
2,514
oceanprotocol/squid-py
squid_py/log.py
setup_logging
def setup_logging(default_path='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'): """Logging setup.""" path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as file: try: config = yaml.safe_load(file.read()) logging.config.dictConfig(config) coloredlogs.install() logging.info(f'Logging configuration loaded from file: {path}') except Exception as ex: print(ex) print('Error in Logging Configuration. Using default configs') logging.basicConfig(level=default_level) coloredlogs.install(level=default_level) else: logging.basicConfig(level=default_level) coloredlogs.install(level=default_level) print('Using default logging settings.')
python
def setup_logging(default_path='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'): """Logging setup.""" path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as file: try: config = yaml.safe_load(file.read()) logging.config.dictConfig(config) coloredlogs.install() logging.info(f'Logging configuration loaded from file: {path}') except Exception as ex: print(ex) print('Error in Logging Configuration. Using default configs') logging.basicConfig(level=default_level) coloredlogs.install(level=default_level) else: logging.basicConfig(level=default_level) coloredlogs.install(level=default_level) print('Using default logging settings.')
[ "def", "setup_logging", "(", "default_path", "=", "'logging.yaml'", ",", "default_level", "=", "logging", ".", "INFO", ",", "env_key", "=", "'LOG_CFG'", ")", ":", "path", "=", "default_path", "value", "=", "os", ".", "getenv", "(", "env_key", ",", "None", ")", "if", "value", ":", "path", "=", "value", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'rt'", ")", "as", "file", ":", "try", ":", "config", "=", "yaml", ".", "safe_load", "(", "file", ".", "read", "(", ")", ")", "logging", ".", "config", ".", "dictConfig", "(", "config", ")", "coloredlogs", ".", "install", "(", ")", "logging", ".", "info", "(", "f'Logging configuration loaded from file: {path}'", ")", "except", "Exception", "as", "ex", ":", "print", "(", "ex", ")", "print", "(", "'Error in Logging Configuration. Using default configs'", ")", "logging", ".", "basicConfig", "(", "level", "=", "default_level", ")", "coloredlogs", ".", "install", "(", "level", "=", "default_level", ")", "else", ":", "logging", ".", "basicConfig", "(", "level", "=", "default_level", ")", "coloredlogs", ".", "install", "(", "level", "=", "default_level", ")", "print", "(", "'Using default logging settings.'", ")" ]
Logging setup.
[ "Logging", "setup", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/log.py#L13-L34
2,515
oceanprotocol/squid-py
squid_py/ocean/ocean_secret_store.py
OceanSecretStore.encrypt
def encrypt(self, document_id, content, account): """ Encrypt string data using the DID as an secret store id, if secret store is enabled then return the result from secret store encryption None for no encryption performed :param document_id: hex str id of document to use for encryption session :param content: str to be encrypted :param account: Account instance encrypting this content :return: hex str encrypted content """ return self._secret_store(account).encrypt_document(document_id, content)
python
def encrypt(self, document_id, content, account): """ Encrypt string data using the DID as an secret store id, if secret store is enabled then return the result from secret store encryption None for no encryption performed :param document_id: hex str id of document to use for encryption session :param content: str to be encrypted :param account: Account instance encrypting this content :return: hex str encrypted content """ return self._secret_store(account).encrypt_document(document_id, content)
[ "def", "encrypt", "(", "self", ",", "document_id", ",", "content", ",", "account", ")", ":", "return", "self", ".", "_secret_store", "(", "account", ")", ".", "encrypt_document", "(", "document_id", ",", "content", ")" ]
Encrypt string data using the DID as an secret store id, if secret store is enabled then return the result from secret store encryption None for no encryption performed :param document_id: hex str id of document to use for encryption session :param content: str to be encrypted :param account: Account instance encrypting this content :return: hex str encrypted content
[ "Encrypt", "string", "data", "using", "the", "DID", "as", "an", "secret", "store", "id", "if", "secret", "store", "is", "enabled", "then", "return", "the", "result", "from", "secret", "store", "encryption" ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_secret_store.py#L34-L46
2,516
oceanprotocol/squid-py
squid_py/did_resolver/did_resolver.py
DIDResolver.get_resolve_url
def get_resolve_url(self, did_bytes): """Return a did value and value type from the block chain event record using 'did'. :param did_bytes: DID, hex-str :return url: Url, str """ data = self._did_registry.get_registered_attribute(did_bytes) if not (data and data.get('value')): return None return data['value']
python
def get_resolve_url(self, did_bytes): """Return a did value and value type from the block chain event record using 'did'. :param did_bytes: DID, hex-str :return url: Url, str """ data = self._did_registry.get_registered_attribute(did_bytes) if not (data and data.get('value')): return None return data['value']
[ "def", "get_resolve_url", "(", "self", ",", "did_bytes", ")", ":", "data", "=", "self", ".", "_did_registry", ".", "get_registered_attribute", "(", "did_bytes", ")", "if", "not", "(", "data", "and", "data", ".", "get", "(", "'value'", ")", ")", ":", "return", "None", "return", "data", "[", "'value'", "]" ]
Return a did value and value type from the block chain event record using 'did'. :param did_bytes: DID, hex-str :return url: Url, str
[ "Return", "a", "did", "value", "and", "value", "type", "from", "the", "block", "chain", "event", "record", "using", "did", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/did_resolver/did_resolver.py#L46-L56
2,517
oceanprotocol/squid-py
squid_py/keeper/contract_base.py
ContractBase.get_instance
def get_instance(cls, dependencies=None): """ Return an instance for a contract name. :param dependencies: :return: Contract base instance """ assert cls is not ContractBase, 'ContractBase is not meant to be used directly.' assert cls.CONTRACT_NAME, 'CONTRACT_NAME must be set to a valid keeper contract name.' return cls(cls.CONTRACT_NAME, dependencies)
python
def get_instance(cls, dependencies=None): """ Return an instance for a contract name. :param dependencies: :return: Contract base instance """ assert cls is not ContractBase, 'ContractBase is not meant to be used directly.' assert cls.CONTRACT_NAME, 'CONTRACT_NAME must be set to a valid keeper contract name.' return cls(cls.CONTRACT_NAME, dependencies)
[ "def", "get_instance", "(", "cls", ",", "dependencies", "=", "None", ")", ":", "assert", "cls", "is", "not", "ContractBase", ",", "'ContractBase is not meant to be used directly.'", "assert", "cls", ".", "CONTRACT_NAME", ",", "'CONTRACT_NAME must be set to a valid keeper contract name.'", "return", "cls", "(", "cls", ".", "CONTRACT_NAME", ",", "dependencies", ")" ]
Return an instance for a contract name. :param dependencies: :return: Contract base instance
[ "Return", "an", "instance", "for", "a", "contract", "name", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/contract_base.py#L38-L47
2,518
oceanprotocol/squid-py
squid_py/keeper/contract_base.py
ContractBase.get_tx_receipt
def get_tx_receipt(tx_hash): """ Get the receipt of a tx. :param tx_hash: hash of the transaction :return: Tx receipt """ try: Web3Provider.get_web3().eth.waitForTransactionReceipt(tx_hash, timeout=20) except Timeout: logger.info('Waiting for transaction receipt timed out.') return return Web3Provider.get_web3().eth.getTransactionReceipt(tx_hash)
python
def get_tx_receipt(tx_hash): """ Get the receipt of a tx. :param tx_hash: hash of the transaction :return: Tx receipt """ try: Web3Provider.get_web3().eth.waitForTransactionReceipt(tx_hash, timeout=20) except Timeout: logger.info('Waiting for transaction receipt timed out.') return return Web3Provider.get_web3().eth.getTransactionReceipt(tx_hash)
[ "def", "get_tx_receipt", "(", "tx_hash", ")", ":", "try", ":", "Web3Provider", ".", "get_web3", "(", ")", ".", "eth", ".", "waitForTransactionReceipt", "(", "tx_hash", ",", "timeout", "=", "20", ")", "except", "Timeout", ":", "logger", ".", "info", "(", "'Waiting for transaction receipt timed out.'", ")", "return", "return", "Web3Provider", ".", "get_web3", "(", ")", ".", "eth", ".", "getTransactionReceipt", "(", "tx_hash", ")" ]
Get the receipt of a tx. :param tx_hash: hash of the transaction :return: Tx receipt
[ "Get", "the", "receipt", "of", "a", "tx", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/contract_base.py#L83-L95
2,519
oceanprotocol/squid-py
squid_py/keeper/contract_base.py
ContractBase.subscribe_to_event
def subscribe_to_event(self, event_name, timeout, event_filter, callback=False, timeout_callback=None, args=None, wait=False): """ Create a listener for the event choose. :param event_name: name of the event to subscribe, str :param timeout: :param event_filter: :param callback: :param timeout_callback: :param args: :param wait: if true block the listener until get the event, bool :return: """ from squid_py.keeper.event_listener import EventListener return EventListener( self.CONTRACT_NAME, event_name, args, filters=event_filter ).listen_once( callback, timeout_callback=timeout_callback, timeout=timeout, blocking=wait )
python
def subscribe_to_event(self, event_name, timeout, event_filter, callback=False, timeout_callback=None, args=None, wait=False): """ Create a listener for the event choose. :param event_name: name of the event to subscribe, str :param timeout: :param event_filter: :param callback: :param timeout_callback: :param args: :param wait: if true block the listener until get the event, bool :return: """ from squid_py.keeper.event_listener import EventListener return EventListener( self.CONTRACT_NAME, event_name, args, filters=event_filter ).listen_once( callback, timeout_callback=timeout_callback, timeout=timeout, blocking=wait )
[ "def", "subscribe_to_event", "(", "self", ",", "event_name", ",", "timeout", ",", "event_filter", ",", "callback", "=", "False", ",", "timeout_callback", "=", "None", ",", "args", "=", "None", ",", "wait", "=", "False", ")", ":", "from", "squid_py", ".", "keeper", ".", "event_listener", "import", "EventListener", "return", "EventListener", "(", "self", ".", "CONTRACT_NAME", ",", "event_name", ",", "args", ",", "filters", "=", "event_filter", ")", ".", "listen_once", "(", "callback", ",", "timeout_callback", "=", "timeout_callback", ",", "timeout", "=", "timeout", ",", "blocking", "=", "wait", ")" ]
Create a listener for the event choose. :param event_name: name of the event to subscribe, str :param timeout: :param event_filter: :param callback: :param timeout_callback: :param args: :param wait: if true block the listener until get the event, bool :return:
[ "Create", "a", "listener", "for", "the", "event", "choose", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/contract_base.py#L97-L122
2,520
oceanprotocol/squid-py
squid_py/agreements/events/escrow_reward_condition.py
refund_reward
def refund_reward(event, agreement_id, did, service_agreement, price, consumer_account, publisher_address, condition_ids): """ Refund the reward to the publisher address. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param price: Asset price, int :param consumer_account: Account instance of the consumer :param publisher_address: ethereum account address of publisher, hex str :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 """ logger.debug(f"trigger refund after event {event}.") access_id, lock_id = condition_ids[:2] name_to_parameter = {param.name: param for param in service_agreement.condition_by_name['escrowReward'].parameters} document_id = add_0x_prefix(name_to_parameter['_documentId'].value) asset_id = add_0x_prefix(did_to_id(did)) assert document_id == asset_id, f'document_id {document_id} <=> asset_id {asset_id} mismatch.' assert price == service_agreement.get_price(), 'price mismatch.' # logger.info(f'About to do grantAccess: account {account.address}, # saId {service_agreement_id}, ' # f'documentKeyId {document_key_id}') try: tx_hash = Keeper.get_instance().escrow_reward_condition.fulfill( agreement_id, price, publisher_address, consumer_account.address, lock_id, access_id, consumer_account ) process_tx_receipt( tx_hash, Keeper.get_instance().escrow_reward_condition.FULFILLED_EVENT, 'EscrowReward.Fulfilled' ) except Exception as e: # logger.error(f'Error when doing escrow_reward_condition.fulfills: {e}') raise e
python
def refund_reward(event, agreement_id, did, service_agreement, price, consumer_account, publisher_address, condition_ids): """ Refund the reward to the publisher address. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param price: Asset price, int :param consumer_account: Account instance of the consumer :param publisher_address: ethereum account address of publisher, hex str :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 """ logger.debug(f"trigger refund after event {event}.") access_id, lock_id = condition_ids[:2] name_to_parameter = {param.name: param for param in service_agreement.condition_by_name['escrowReward'].parameters} document_id = add_0x_prefix(name_to_parameter['_documentId'].value) asset_id = add_0x_prefix(did_to_id(did)) assert document_id == asset_id, f'document_id {document_id} <=> asset_id {asset_id} mismatch.' assert price == service_agreement.get_price(), 'price mismatch.' # logger.info(f'About to do grantAccess: account {account.address}, # saId {service_agreement_id}, ' # f'documentKeyId {document_key_id}') try: tx_hash = Keeper.get_instance().escrow_reward_condition.fulfill( agreement_id, price, publisher_address, consumer_account.address, lock_id, access_id, consumer_account ) process_tx_receipt( tx_hash, Keeper.get_instance().escrow_reward_condition.FULFILLED_EVENT, 'EscrowReward.Fulfilled' ) except Exception as e: # logger.error(f'Error when doing escrow_reward_condition.fulfills: {e}') raise e
[ "def", "refund_reward", "(", "event", ",", "agreement_id", ",", "did", ",", "service_agreement", ",", "price", ",", "consumer_account", ",", "publisher_address", ",", "condition_ids", ")", ":", "logger", ".", "debug", "(", "f\"trigger refund after event {event}.\"", ")", "access_id", ",", "lock_id", "=", "condition_ids", "[", ":", "2", "]", "name_to_parameter", "=", "{", "param", ".", "name", ":", "param", "for", "param", "in", "service_agreement", ".", "condition_by_name", "[", "'escrowReward'", "]", ".", "parameters", "}", "document_id", "=", "add_0x_prefix", "(", "name_to_parameter", "[", "'_documentId'", "]", ".", "value", ")", "asset_id", "=", "add_0x_prefix", "(", "did_to_id", "(", "did", ")", ")", "assert", "document_id", "==", "asset_id", ",", "f'document_id {document_id} <=> asset_id {asset_id} mismatch.'", "assert", "price", "==", "service_agreement", ".", "get_price", "(", ")", ",", "'price mismatch.'", "# logger.info(f'About to do grantAccess: account {account.address},", "# saId {service_agreement_id}, '", "# f'documentKeyId {document_key_id}')", "try", ":", "tx_hash", "=", "Keeper", ".", "get_instance", "(", ")", ".", "escrow_reward_condition", ".", "fulfill", "(", "agreement_id", ",", "price", ",", "publisher_address", ",", "consumer_account", ".", "address", ",", "lock_id", ",", "access_id", ",", "consumer_account", ")", "process_tx_receipt", "(", "tx_hash", ",", "Keeper", ".", "get_instance", "(", ")", ".", "escrow_reward_condition", ".", "FULFILLED_EVENT", ",", "'EscrowReward.Fulfilled'", ")", "except", "Exception", "as", "e", ":", "# logger.error(f'Error when doing escrow_reward_condition.fulfills: {e}')", "raise", "e" ]
Refund the reward to the publisher address. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param price: Asset price, int :param consumer_account: Account instance of the consumer :param publisher_address: ethereum account address of publisher, hex str :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32
[ "Refund", "the", "reward", "to", "the", "publisher", "address", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/events/escrow_reward_condition.py#L56-L98
2,521
oceanprotocol/squid-py
squid_py/agreements/events/escrow_reward_condition.py
consume_asset
def consume_asset(event, agreement_id, did, service_agreement, consumer_account, consume_callback): """ Consumption of an asset after get the event call. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param consumer_account: Account instance of the consumer :param consume_callback: """ logger.debug(f"consuming asset after event {event}.") if consume_callback: config = ConfigProvider.get_config() secret_store = SecretStoreProvider.get_secret_store( config.secret_store_url, config.parity_url, consumer_account ) brizo = BrizoProvider.get_brizo() consume_callback( agreement_id, service_agreement.service_definition_id, DIDResolver(Keeper.get_instance().did_registry).resolve(did), consumer_account, ConfigProvider.get_config().downloads_path, brizo, secret_store )
python
def consume_asset(event, agreement_id, did, service_agreement, consumer_account, consume_callback): """ Consumption of an asset after get the event call. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param consumer_account: Account instance of the consumer :param consume_callback: """ logger.debug(f"consuming asset after event {event}.") if consume_callback: config = ConfigProvider.get_config() secret_store = SecretStoreProvider.get_secret_store( config.secret_store_url, config.parity_url, consumer_account ) brizo = BrizoProvider.get_brizo() consume_callback( agreement_id, service_agreement.service_definition_id, DIDResolver(Keeper.get_instance().did_registry).resolve(did), consumer_account, ConfigProvider.get_config().downloads_path, brizo, secret_store )
[ "def", "consume_asset", "(", "event", ",", "agreement_id", ",", "did", ",", "service_agreement", ",", "consumer_account", ",", "consume_callback", ")", ":", "logger", ".", "debug", "(", "f\"consuming asset after event {event}.\"", ")", "if", "consume_callback", ":", "config", "=", "ConfigProvider", ".", "get_config", "(", ")", "secret_store", "=", "SecretStoreProvider", ".", "get_secret_store", "(", "config", ".", "secret_store_url", ",", "config", ".", "parity_url", ",", "consumer_account", ")", "brizo", "=", "BrizoProvider", ".", "get_brizo", "(", ")", "consume_callback", "(", "agreement_id", ",", "service_agreement", ".", "service_definition_id", ",", "DIDResolver", "(", "Keeper", ".", "get_instance", "(", ")", ".", "did_registry", ")", ".", "resolve", "(", "did", ")", ",", "consumer_account", ",", "ConfigProvider", ".", "get_config", "(", ")", ".", "downloads_path", ",", "brizo", ",", "secret_store", ")" ]
Consumption of an asset after get the event call. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param consumer_account: Account instance of the consumer :param consume_callback:
[ "Consumption", "of", "an", "asset", "after", "get", "the", "event", "call", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/events/escrow_reward_condition.py#L101-L128
2,522
oceanprotocol/squid-py
squid_py/keeper/diagnostics.py
Diagnostics.verify_contracts
def verify_contracts(): """ Verify that the contracts are deployed correctly in the network. :raise Exception: raise exception if the contracts are not deployed correctly. """ artifacts_path = ConfigProvider.get_config().keeper_path logger.info(f'Keeper contract artifacts (JSON abi files) at: {artifacts_path}') if os.environ.get('KEEPER_NETWORK_NAME'): logger.warning(f'The `KEEPER_NETWORK_NAME` env var is set to ' f'{os.environ.get("KEEPER_NETWORK_NAME")}. ' f'This enables the user to override the method of how the network name ' f'is inferred from network id.') # try to find contract with this network name contract_name = Diagnostics.TEST_CONTRACT_NAME network_id = Keeper.get_network_id() network_name = Keeper.get_network_name(network_id) logger.info(f'Using keeper contracts from network {network_name}, ' f'network id is {network_id}') logger.info(f'Looking for keeper contracts ending with ".{network_name}.json", ' f'e.g. "{contract_name}.{network_name}.json".') existing_contract_names = os.listdir(artifacts_path) try: ContractHandler.get(contract_name) except Exception as e: logger.error(e) logger.error(f'Cannot find the keeper contracts. \n' f'Current network id is {network_id} and network name is {network_name}.' f'Expected to find contracts ending with ".{network_name}.json",' f' e.g. "{contract_name}.{network_name}.json"') raise OceanKeeperContractsNotFound( f'Keeper contracts for keeper network {network_name} were not found ' f'in {artifacts_path}. \n' f'Found the following contracts: \n\t{existing_contract_names}' ) keeper = Keeper.get_instance() contracts = [keeper.dispenser, keeper.token, keeper.did_registry, keeper.agreement_manager, keeper.template_manager, keeper.condition_manager, keeper.access_secret_store_condition, keeper.sign_condition, keeper.lock_reward_condition, keeper.escrow_access_secretstore_template, keeper.escrow_reward_condition, keeper.hash_lock_condition ] addresses = '\n'.join([f'\t{c.name}: {c.address}' for c in contracts]) logging.info('Finished loading keeper contracts:\n' '%s', addresses)
python
def verify_contracts(): """ Verify that the contracts are deployed correctly in the network. :raise Exception: raise exception if the contracts are not deployed correctly. """ artifacts_path = ConfigProvider.get_config().keeper_path logger.info(f'Keeper contract artifacts (JSON abi files) at: {artifacts_path}') if os.environ.get('KEEPER_NETWORK_NAME'): logger.warning(f'The `KEEPER_NETWORK_NAME` env var is set to ' f'{os.environ.get("KEEPER_NETWORK_NAME")}. ' f'This enables the user to override the method of how the network name ' f'is inferred from network id.') # try to find contract with this network name contract_name = Diagnostics.TEST_CONTRACT_NAME network_id = Keeper.get_network_id() network_name = Keeper.get_network_name(network_id) logger.info(f'Using keeper contracts from network {network_name}, ' f'network id is {network_id}') logger.info(f'Looking for keeper contracts ending with ".{network_name}.json", ' f'e.g. "{contract_name}.{network_name}.json".') existing_contract_names = os.listdir(artifacts_path) try: ContractHandler.get(contract_name) except Exception as e: logger.error(e) logger.error(f'Cannot find the keeper contracts. \n' f'Current network id is {network_id} and network name is {network_name}.' f'Expected to find contracts ending with ".{network_name}.json",' f' e.g. "{contract_name}.{network_name}.json"') raise OceanKeeperContractsNotFound( f'Keeper contracts for keeper network {network_name} were not found ' f'in {artifacts_path}. \n' f'Found the following contracts: \n\t{existing_contract_names}' ) keeper = Keeper.get_instance() contracts = [keeper.dispenser, keeper.token, keeper.did_registry, keeper.agreement_manager, keeper.template_manager, keeper.condition_manager, keeper.access_secret_store_condition, keeper.sign_condition, keeper.lock_reward_condition, keeper.escrow_access_secretstore_template, keeper.escrow_reward_condition, keeper.hash_lock_condition ] addresses = '\n'.join([f'\t{c.name}: {c.address}' for c in contracts]) logging.info('Finished loading keeper contracts:\n' '%s', addresses)
[ "def", "verify_contracts", "(", ")", ":", "artifacts_path", "=", "ConfigProvider", ".", "get_config", "(", ")", ".", "keeper_path", "logger", ".", "info", "(", "f'Keeper contract artifacts (JSON abi files) at: {artifacts_path}'", ")", "if", "os", ".", "environ", ".", "get", "(", "'KEEPER_NETWORK_NAME'", ")", ":", "logger", ".", "warning", "(", "f'The `KEEPER_NETWORK_NAME` env var is set to '", "f'{os.environ.get(\"KEEPER_NETWORK_NAME\")}. '", "f'This enables the user to override the method of how the network name '", "f'is inferred from network id.'", ")", "# try to find contract with this network name", "contract_name", "=", "Diagnostics", ".", "TEST_CONTRACT_NAME", "network_id", "=", "Keeper", ".", "get_network_id", "(", ")", "network_name", "=", "Keeper", ".", "get_network_name", "(", "network_id", ")", "logger", ".", "info", "(", "f'Using keeper contracts from network {network_name}, '", "f'network id is {network_id}'", ")", "logger", ".", "info", "(", "f'Looking for keeper contracts ending with \".{network_name}.json\", '", "f'e.g. \"{contract_name}.{network_name}.json\".'", ")", "existing_contract_names", "=", "os", ".", "listdir", "(", "artifacts_path", ")", "try", ":", "ContractHandler", ".", "get", "(", "contract_name", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "e", ")", "logger", ".", "error", "(", "f'Cannot find the keeper contracts. \\n'", "f'Current network id is {network_id} and network name is {network_name}.'", "f'Expected to find contracts ending with \".{network_name}.json\",'", "f' e.g. \"{contract_name}.{network_name}.json\"'", ")", "raise", "OceanKeeperContractsNotFound", "(", "f'Keeper contracts for keeper network {network_name} were not found '", "f'in {artifacts_path}. \\n'", "f'Found the following contracts: \\n\\t{existing_contract_names}'", ")", "keeper", "=", "Keeper", ".", "get_instance", "(", ")", "contracts", "=", "[", "keeper", ".", "dispenser", ",", "keeper", ".", "token", ",", "keeper", ".", "did_registry", ",", "keeper", ".", "agreement_manager", ",", "keeper", ".", "template_manager", ",", "keeper", ".", "condition_manager", ",", "keeper", ".", "access_secret_store_condition", ",", "keeper", ".", "sign_condition", ",", "keeper", ".", "lock_reward_condition", ",", "keeper", ".", "escrow_access_secretstore_template", ",", "keeper", ".", "escrow_reward_condition", ",", "keeper", ".", "hash_lock_condition", "]", "addresses", "=", "'\\n'", ".", "join", "(", "[", "f'\\t{c.name}: {c.address}'", "for", "c", "in", "contracts", "]", ")", "logging", ".", "info", "(", "'Finished loading keeper contracts:\\n'", "'%s'", ",", "addresses", ")" ]
Verify that the contracts are deployed correctly in the network. :raise Exception: raise exception if the contracts are not deployed correctly.
[ "Verify", "that", "the", "contracts", "are", "deployed", "correctly", "in", "the", "network", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/diagnostics.py#L19-L66
2,523
oceanprotocol/squid-py
squid_py/ocean/ocean_services.py
OceanServices.create_access_service
def create_access_service(price, service_endpoint, consume_endpoint, timeout=None): """ Publish an asset with an `Access` service according to the supplied attributes. :param price: Asset price, int :param service_endpoint: str URL for initiating service access request :param consume_endpoint: str URL to consume service :param timeout: int amount of time in seconds before the agreement expires :return: Service instance or None """ timeout = timeout or 3600 # default to one hour timeout service = ServiceDescriptor.access_service_descriptor( price, service_endpoint, consume_endpoint, timeout, '' ) return service
python
def create_access_service(price, service_endpoint, consume_endpoint, timeout=None): """ Publish an asset with an `Access` service according to the supplied attributes. :param price: Asset price, int :param service_endpoint: str URL for initiating service access request :param consume_endpoint: str URL to consume service :param timeout: int amount of time in seconds before the agreement expires :return: Service instance or None """ timeout = timeout or 3600 # default to one hour timeout service = ServiceDescriptor.access_service_descriptor( price, service_endpoint, consume_endpoint, timeout, '' ) return service
[ "def", "create_access_service", "(", "price", ",", "service_endpoint", ",", "consume_endpoint", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "or", "3600", "# default to one hour timeout", "service", "=", "ServiceDescriptor", ".", "access_service_descriptor", "(", "price", ",", "service_endpoint", ",", "consume_endpoint", ",", "timeout", ",", "''", ")", "return", "service" ]
Publish an asset with an `Access` service according to the supplied attributes. :param price: Asset price, int :param service_endpoint: str URL for initiating service access request :param consume_endpoint: str URL to consume service :param timeout: int amount of time in seconds before the agreement expires :return: Service instance or None
[ "Publish", "an", "asset", "with", "an", "Access", "service", "according", "to", "the", "supplied", "attributes", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_services.py#L12-L27
2,524
oceanprotocol/squid-py
squid_py/ocean/ocean_conditions.py
OceanConditions.lock_reward
def lock_reward(self, agreement_id, amount, account): """ Lock reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return: bool """ return self._keeper.lock_reward_condition.fulfill( agreement_id, self._keeper.escrow_reward_condition.address, amount, account )
python
def lock_reward(self, agreement_id, amount, account): """ Lock reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return: bool """ return self._keeper.lock_reward_condition.fulfill( agreement_id, self._keeper.escrow_reward_condition.address, amount, account )
[ "def", "lock_reward", "(", "self", ",", "agreement_id", ",", "amount", ",", "account", ")", ":", "return", "self", ".", "_keeper", ".", "lock_reward_condition", ".", "fulfill", "(", "agreement_id", ",", "self", ".", "_keeper", ".", "escrow_reward_condition", ".", "address", ",", "amount", ",", "account", ")" ]
Lock reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return: bool
[ "Lock", "reward", "condition", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_conditions.py#L15-L26
2,525
oceanprotocol/squid-py
squid_py/ocean/ocean_conditions.py
OceanConditions.grant_access
def grant_access(self, agreement_id, did, grantee_address, account): """ Grant access condition. :param agreement_id: id of the agreement, hex str :param did: DID, str :param grantee_address: Address, hex str :param account: Account :return: """ return self._keeper.access_secret_store_condition.fulfill( agreement_id, add_0x_prefix(did_to_id(did)), grantee_address, account )
python
def grant_access(self, agreement_id, did, grantee_address, account): """ Grant access condition. :param agreement_id: id of the agreement, hex str :param did: DID, str :param grantee_address: Address, hex str :param account: Account :return: """ return self._keeper.access_secret_store_condition.fulfill( agreement_id, add_0x_prefix(did_to_id(did)), grantee_address, account )
[ "def", "grant_access", "(", "self", ",", "agreement_id", ",", "did", ",", "grantee_address", ",", "account", ")", ":", "return", "self", ".", "_keeper", ".", "access_secret_store_condition", ".", "fulfill", "(", "agreement_id", ",", "add_0x_prefix", "(", "did_to_id", "(", "did", ")", ")", ",", "grantee_address", ",", "account", ")" ]
Grant access condition. :param agreement_id: id of the agreement, hex str :param did: DID, str :param grantee_address: Address, hex str :param account: Account :return:
[ "Grant", "access", "condition", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_conditions.py#L28-L40
2,526
oceanprotocol/squid-py
squid_py/ocean/ocean_conditions.py
OceanConditions.release_reward
def release_reward(self, agreement_id, amount, account): """ Release reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return: """ agreement_values = self._keeper.agreement_manager.get_agreement(agreement_id) consumer, provider = self._keeper.escrow_access_secretstore_template.get_agreement_data( agreement_id) access_id, lock_id = agreement_values.condition_ids[:2] return self._keeper.escrow_reward_condition.fulfill( agreement_id, amount, provider, consumer, lock_id, access_id, account )
python
def release_reward(self, agreement_id, amount, account): """ Release reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return: """ agreement_values = self._keeper.agreement_manager.get_agreement(agreement_id) consumer, provider = self._keeper.escrow_access_secretstore_template.get_agreement_data( agreement_id) access_id, lock_id = agreement_values.condition_ids[:2] return self._keeper.escrow_reward_condition.fulfill( agreement_id, amount, provider, consumer, lock_id, access_id, account )
[ "def", "release_reward", "(", "self", ",", "agreement_id", ",", "amount", ",", "account", ")", ":", "agreement_values", "=", "self", ".", "_keeper", ".", "agreement_manager", ".", "get_agreement", "(", "agreement_id", ")", "consumer", ",", "provider", "=", "self", ".", "_keeper", ".", "escrow_access_secretstore_template", ".", "get_agreement_data", "(", "agreement_id", ")", "access_id", ",", "lock_id", "=", "agreement_values", ".", "condition_ids", "[", ":", "2", "]", "return", "self", ".", "_keeper", ".", "escrow_reward_condition", ".", "fulfill", "(", "agreement_id", ",", "amount", ",", "provider", ",", "consumer", ",", "lock_id", ",", "access_id", ",", "account", ")" ]
Release reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return:
[ "Release", "reward", "condition", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_conditions.py#L42-L63
2,527
oceanprotocol/squid-py
squid_py/ocean/ocean_conditions.py
OceanConditions.refund_reward
def refund_reward(self, agreement_id, amount, account): """ Refund reaward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return: """ return self.release_reward(agreement_id, amount, account)
python
def refund_reward(self, agreement_id, amount, account): """ Refund reaward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return: """ return self.release_reward(agreement_id, amount, account)
[ "def", "refund_reward", "(", "self", ",", "agreement_id", ",", "amount", ",", "account", ")", ":", "return", "self", ".", "release_reward", "(", "agreement_id", ",", "amount", ",", "account", ")" ]
Refund reaward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return:
[ "Refund", "reaward", "condition", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_conditions.py#L65-L74
2,528
oceanprotocol/squid-py
squid_py/agreements/service_agreement_template.py
ServiceAgreementTemplate.from_json_file
def from_json_file(cls, path): """ Return a template from a json allocated in a path. :param path: string :return: ServiceAgreementTemplate """ with open(path) as jsf: template_json = json.load(jsf) return cls(template_json=template_json)
python
def from_json_file(cls, path): """ Return a template from a json allocated in a path. :param path: string :return: ServiceAgreementTemplate """ with open(path) as jsf: template_json = json.load(jsf) return cls(template_json=template_json)
[ "def", "from_json_file", "(", "cls", ",", "path", ")", ":", "with", "open", "(", "path", ")", "as", "jsf", ":", "template_json", "=", "json", ".", "load", "(", "jsf", ")", "return", "cls", "(", "template_json", "=", "template_json", ")" ]
Return a template from a json allocated in a path. :param path: string :return: ServiceAgreementTemplate
[ "Return", "a", "template", "from", "a", "json", "allocated", "in", "a", "path", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement_template.py#L24-L33
2,529
oceanprotocol/squid-py
squid_py/agreements/service_agreement_template.py
ServiceAgreementTemplate.parse_template_json
def parse_template_json(self, template_json): """ Parse a template from a json. :param template_json: json dict """ assert template_json['type'] == self.DOCUMENT_TYPE, '' self.template_id = template_json['templateId'] self.name = template_json.get('name') self.creator = template_json.get('creator') self.template = template_json['serviceAgreementTemplate']
python
def parse_template_json(self, template_json): """ Parse a template from a json. :param template_json: json dict """ assert template_json['type'] == self.DOCUMENT_TYPE, '' self.template_id = template_json['templateId'] self.name = template_json.get('name') self.creator = template_json.get('creator') self.template = template_json['serviceAgreementTemplate']
[ "def", "parse_template_json", "(", "self", ",", "template_json", ")", ":", "assert", "template_json", "[", "'type'", "]", "==", "self", ".", "DOCUMENT_TYPE", ",", "''", "self", ".", "template_id", "=", "template_json", "[", "'templateId'", "]", "self", ".", "name", "=", "template_json", ".", "get", "(", "'name'", ")", "self", ".", "creator", "=", "template_json", ".", "get", "(", "'creator'", ")", "self", ".", "template", "=", "template_json", "[", "'serviceAgreementTemplate'", "]" ]
Parse a template from a json. :param template_json: json dict
[ "Parse", "a", "template", "from", "a", "json", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement_template.py#L35-L45
2,530
oceanprotocol/squid-py
squid_py/agreements/service_agreement_template.py
ServiceAgreementTemplate.as_dictionary
def as_dictionary(self): """ Return the service agreement template as a dictionary. :return: dict """ template = { 'contractName': self.contract_name, 'events': [e.as_dictionary() for e in self.agreement_events], 'fulfillmentOrder': self.fulfillment_order, 'conditionDependency': self.condition_dependency, 'conditions': [cond.as_dictionary() for cond in self.conditions] } return { # 'type': self.DOCUMENT_TYPE, 'name': self.name, 'creator': self.creator, 'serviceAgreementTemplate': template }
python
def as_dictionary(self): """ Return the service agreement template as a dictionary. :return: dict """ template = { 'contractName': self.contract_name, 'events': [e.as_dictionary() for e in self.agreement_events], 'fulfillmentOrder': self.fulfillment_order, 'conditionDependency': self.condition_dependency, 'conditions': [cond.as_dictionary() for cond in self.conditions] } return { # 'type': self.DOCUMENT_TYPE, 'name': self.name, 'creator': self.creator, 'serviceAgreementTemplate': template }
[ "def", "as_dictionary", "(", "self", ")", ":", "template", "=", "{", "'contractName'", ":", "self", ".", "contract_name", ",", "'events'", ":", "[", "e", ".", "as_dictionary", "(", ")", "for", "e", "in", "self", ".", "agreement_events", "]", ",", "'fulfillmentOrder'", ":", "self", ".", "fulfillment_order", ",", "'conditionDependency'", ":", "self", ".", "condition_dependency", ",", "'conditions'", ":", "[", "cond", ".", "as_dictionary", "(", ")", "for", "cond", "in", "self", ".", "conditions", "]", "}", "return", "{", "# 'type': self.DOCUMENT_TYPE,", "'name'", ":", "self", ".", "name", ",", "'creator'", ":", "self", ".", "creator", ",", "'serviceAgreementTemplate'", ":", "template", "}" ]
Return the service agreement template as a dictionary. :return: dict
[ "Return", "the", "service", "agreement", "template", "as", "a", "dictionary", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement_template.py#L110-L128
2,531
oceanprotocol/squid-py
squid_py/ocean/ocean_tokens.py
OceanTokens.request
def request(self, account, amount): """ Request a number of tokens to be minted and transfered to `account` :param account: Account instance requesting the tokens :param amount: int number of tokens to request :return: bool """ return self._keeper.dispenser.request_tokens(amount, account)
python
def request(self, account, amount): """ Request a number of tokens to be minted and transfered to `account` :param account: Account instance requesting the tokens :param amount: int number of tokens to request :return: bool """ return self._keeper.dispenser.request_tokens(amount, account)
[ "def", "request", "(", "self", ",", "account", ",", "amount", ")", ":", "return", "self", ".", "_keeper", ".", "dispenser", ".", "request_tokens", "(", "amount", ",", "account", ")" ]
Request a number of tokens to be minted and transfered to `account` :param account: Account instance requesting the tokens :param amount: int number of tokens to request :return: bool
[ "Request", "a", "number", "of", "tokens", "to", "be", "minted", "and", "transfered", "to", "account" ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_tokens.py#L11-L19
2,532
oceanprotocol/squid-py
squid_py/ocean/ocean_tokens.py
OceanTokens.transfer
def transfer(self, receiver_address, amount, sender_account): """ Transfer a number of tokens from `sender_account` to `receiver_address` :param receiver_address: hex str ethereum address to receive this transfer of tokens :param amount: int number of tokens to transfer :param sender_account: Account instance to take the tokens from :return: bool """ self._keeper.token.token_approve(receiver_address, amount, sender_account) self._keeper.token.transfer(receiver_address, amount, sender_account)
python
def transfer(self, receiver_address, amount, sender_account): """ Transfer a number of tokens from `sender_account` to `receiver_address` :param receiver_address: hex str ethereum address to receive this transfer of tokens :param amount: int number of tokens to transfer :param sender_account: Account instance to take the tokens from :return: bool """ self._keeper.token.token_approve(receiver_address, amount, sender_account) self._keeper.token.transfer(receiver_address, amount, sender_account)
[ "def", "transfer", "(", "self", ",", "receiver_address", ",", "amount", ",", "sender_account", ")", ":", "self", ".", "_keeper", ".", "token", ".", "token_approve", "(", "receiver_address", ",", "amount", ",", "sender_account", ")", "self", ".", "_keeper", ".", "token", ".", "transfer", "(", "receiver_address", ",", "amount", ",", "sender_account", ")" ]
Transfer a number of tokens from `sender_account` to `receiver_address` :param receiver_address: hex str ethereum address to receive this transfer of tokens :param amount: int number of tokens to transfer :param sender_account: Account instance to take the tokens from :return: bool
[ "Transfer", "a", "number", "of", "tokens", "from", "sender_account", "to", "receiver_address" ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_tokens.py#L21-L32
2,533
oceanprotocol/squid-py
squid_py/aquarius/aquarius.py
Aquarius.list_assets
def list_assets(self): """ List all the assets registered in the aquarius instance. :return: List of DID string """ response = self.requests_session.get(self._base_url).content if not response: return {} try: asset_list = json.loads(response) except TypeError: asset_list = None except ValueError: raise ValueError(response.decode('UTF-8')) if not asset_list: return [] if 'ids' in asset_list: return asset_list['ids'] return []
python
def list_assets(self): """ List all the assets registered in the aquarius instance. :return: List of DID string """ response = self.requests_session.get(self._base_url).content if not response: return {} try: asset_list = json.loads(response) except TypeError: asset_list = None except ValueError: raise ValueError(response.decode('UTF-8')) if not asset_list: return [] if 'ids' in asset_list: return asset_list['ids'] return []
[ "def", "list_assets", "(", "self", ")", ":", "response", "=", "self", ".", "requests_session", ".", "get", "(", "self", ".", "_base_url", ")", ".", "content", "if", "not", "response", ":", "return", "{", "}", "try", ":", "asset_list", "=", "json", ".", "loads", "(", "response", ")", "except", "TypeError", ":", "asset_list", "=", "None", "except", "ValueError", ":", "raise", "ValueError", "(", "response", ".", "decode", "(", "'UTF-8'", ")", ")", "if", "not", "asset_list", ":", "return", "[", "]", "if", "'ids'", "in", "asset_list", ":", "return", "asset_list", "[", "'ids'", "]", "return", "[", "]" ]
List all the assets registered in the aquarius instance. :return: List of DID string
[ "List", "all", "the", "assets", "registered", "in", "the", "aquarius", "instance", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L55-L77
2,534
oceanprotocol/squid-py
squid_py/aquarius/aquarius.py
Aquarius.get_asset_ddo
def get_asset_ddo(self, did): """ Retrieve asset ddo for a given did. :param did: Asset DID string :return: DDO instance """ response = self.requests_session.get(f'{self.url}/{did}').content if not response: return {} try: parsed_response = json.loads(response) except TypeError: parsed_response = None except ValueError: raise ValueError(response.decode('UTF-8')) if parsed_response is None: return {} return Asset(dictionary=parsed_response)
python
def get_asset_ddo(self, did): """ Retrieve asset ddo for a given did. :param did: Asset DID string :return: DDO instance """ response = self.requests_session.get(f'{self.url}/{did}').content if not response: return {} try: parsed_response = json.loads(response) except TypeError: parsed_response = None except ValueError: raise ValueError(response.decode('UTF-8')) if parsed_response is None: return {} return Asset(dictionary=parsed_response)
[ "def", "get_asset_ddo", "(", "self", ",", "did", ")", ":", "response", "=", "self", ".", "requests_session", ".", "get", "(", "f'{self.url}/{did}'", ")", ".", "content", "if", "not", "response", ":", "return", "{", "}", "try", ":", "parsed_response", "=", "json", ".", "loads", "(", "response", ")", "except", "TypeError", ":", "parsed_response", "=", "None", "except", "ValueError", ":", "raise", "ValueError", "(", "response", ".", "decode", "(", "'UTF-8'", ")", ")", "if", "parsed_response", "is", "None", ":", "return", "{", "}", "return", "Asset", "(", "dictionary", "=", "parsed_response", ")" ]
Retrieve asset ddo for a given did. :param did: Asset DID string :return: DDO instance
[ "Retrieve", "asset", "ddo", "for", "a", "given", "did", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L79-L97
2,535
oceanprotocol/squid-py
squid_py/aquarius/aquarius.py
Aquarius.get_asset_metadata
def get_asset_metadata(self, did): """ Retrieve asset metadata for a given did. :param did: Asset DID string :return: metadata key of the DDO instance """ response = self.requests_session.get(f'{self._base_url}/metadata/{did}').content if not response: return {} try: parsed_response = json.loads(response) except TypeError: parsed_response = None except ValueError: raise ValueError(response.decode('UTF-8')) if parsed_response is None: return {} return parsed_response['metadata']
python
def get_asset_metadata(self, did): """ Retrieve asset metadata for a given did. :param did: Asset DID string :return: metadata key of the DDO instance """ response = self.requests_session.get(f'{self._base_url}/metadata/{did}').content if not response: return {} try: parsed_response = json.loads(response) except TypeError: parsed_response = None except ValueError: raise ValueError(response.decode('UTF-8')) if parsed_response is None: return {} return parsed_response['metadata']
[ "def", "get_asset_metadata", "(", "self", ",", "did", ")", ":", "response", "=", "self", ".", "requests_session", ".", "get", "(", "f'{self._base_url}/metadata/{did}'", ")", ".", "content", "if", "not", "response", ":", "return", "{", "}", "try", ":", "parsed_response", "=", "json", ".", "loads", "(", "response", ")", "except", "TypeError", ":", "parsed_response", "=", "None", "except", "ValueError", ":", "raise", "ValueError", "(", "response", ".", "decode", "(", "'UTF-8'", ")", ")", "if", "parsed_response", "is", "None", ":", "return", "{", "}", "return", "parsed_response", "[", "'metadata'", "]" ]
Retrieve asset metadata for a given did. :param did: Asset DID string :return: metadata key of the DDO instance
[ "Retrieve", "asset", "metadata", "for", "a", "given", "did", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L99-L117
2,536
oceanprotocol/squid-py
squid_py/aquarius/aquarius.py
Aquarius.list_assets_ddo
def list_assets_ddo(self): """ List all the ddos registered in the aquarius instance. :return: List of DDO instance """ return json.loads(self.requests_session.get(self.url).content)
python
def list_assets_ddo(self): """ List all the ddos registered in the aquarius instance. :return: List of DDO instance """ return json.loads(self.requests_session.get(self.url).content)
[ "def", "list_assets_ddo", "(", "self", ")", ":", "return", "json", ".", "loads", "(", "self", ".", "requests_session", ".", "get", "(", "self", ".", "url", ")", ".", "content", ")" ]
List all the ddos registered in the aquarius instance. :return: List of DDO instance
[ "List", "all", "the", "ddos", "registered", "in", "the", "aquarius", "instance", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L119-L125
2,537
oceanprotocol/squid-py
squid_py/aquarius/aquarius.py
Aquarius.publish_asset_ddo
def publish_asset_ddo(self, ddo): """ Register asset ddo in aquarius. :param ddo: DDO instance :return: API response (depends on implementation) """ try: asset_did = ddo.did response = self.requests_session.post(self.url, data=ddo.as_text(), headers=self._headers) except AttributeError: raise AttributeError('DDO invalid. Review that all the required parameters are filled.') if response.status_code == 500: raise ValueError( f'This Asset ID already exists! \n\tHTTP Error message: \n\t\t{response.text}') elif response.status_code != 201: raise Exception(f'{response.status_code} ERROR Full error: \n{response.text}') elif response.status_code == 201: response = json.loads(response.content) logger.debug(f'Published asset DID {asset_did}') return response else: raise Exception(f'Unhandled ERROR: status-code {response.status_code}, ' f'error message {response.text}')
python
def publish_asset_ddo(self, ddo): """ Register asset ddo in aquarius. :param ddo: DDO instance :return: API response (depends on implementation) """ try: asset_did = ddo.did response = self.requests_session.post(self.url, data=ddo.as_text(), headers=self._headers) except AttributeError: raise AttributeError('DDO invalid. Review that all the required parameters are filled.') if response.status_code == 500: raise ValueError( f'This Asset ID already exists! \n\tHTTP Error message: \n\t\t{response.text}') elif response.status_code != 201: raise Exception(f'{response.status_code} ERROR Full error: \n{response.text}') elif response.status_code == 201: response = json.loads(response.content) logger.debug(f'Published asset DID {asset_did}') return response else: raise Exception(f'Unhandled ERROR: status-code {response.status_code}, ' f'error message {response.text}')
[ "def", "publish_asset_ddo", "(", "self", ",", "ddo", ")", ":", "try", ":", "asset_did", "=", "ddo", ".", "did", "response", "=", "self", ".", "requests_session", ".", "post", "(", "self", ".", "url", ",", "data", "=", "ddo", ".", "as_text", "(", ")", ",", "headers", "=", "self", ".", "_headers", ")", "except", "AttributeError", ":", "raise", "AttributeError", "(", "'DDO invalid. Review that all the required parameters are filled.'", ")", "if", "response", ".", "status_code", "==", "500", ":", "raise", "ValueError", "(", "f'This Asset ID already exists! \\n\\tHTTP Error message: \\n\\t\\t{response.text}'", ")", "elif", "response", ".", "status_code", "!=", "201", ":", "raise", "Exception", "(", "f'{response.status_code} ERROR Full error: \\n{response.text}'", ")", "elif", "response", ".", "status_code", "==", "201", ":", "response", "=", "json", ".", "loads", "(", "response", ".", "content", ")", "logger", ".", "debug", "(", "f'Published asset DID {asset_did}'", ")", "return", "response", "else", ":", "raise", "Exception", "(", "f'Unhandled ERROR: status-code {response.status_code}, '", "f'error message {response.text}'", ")" ]
Register asset ddo in aquarius. :param ddo: DDO instance :return: API response (depends on implementation)
[ "Register", "asset", "ddo", "in", "aquarius", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L127-L151
2,538
oceanprotocol/squid-py
squid_py/aquarius/aquarius.py
Aquarius.update_asset_ddo
def update_asset_ddo(self, did, ddo): """ Update the ddo of a did already registered. :param did: Asset DID string :param ddo: DDO instance :return: API response (depends on implementation) """ response = self.requests_session.put(f'{self.url}/{did}', data=ddo.as_text(), headers=self._headers) if response.status_code == 200 or response.status_code == 201: return json.loads(response.content) else: raise Exception(f'Unable to update DDO: {response.content}')
python
def update_asset_ddo(self, did, ddo): """ Update the ddo of a did already registered. :param did: Asset DID string :param ddo: DDO instance :return: API response (depends on implementation) """ response = self.requests_session.put(f'{self.url}/{did}', data=ddo.as_text(), headers=self._headers) if response.status_code == 200 or response.status_code == 201: return json.loads(response.content) else: raise Exception(f'Unable to update DDO: {response.content}')
[ "def", "update_asset_ddo", "(", "self", ",", "did", ",", "ddo", ")", ":", "response", "=", "self", ".", "requests_session", ".", "put", "(", "f'{self.url}/{did}'", ",", "data", "=", "ddo", ".", "as_text", "(", ")", ",", "headers", "=", "self", ".", "_headers", ")", "if", "response", ".", "status_code", "==", "200", "or", "response", ".", "status_code", "==", "201", ":", "return", "json", ".", "loads", "(", "response", ".", "content", ")", "else", ":", "raise", "Exception", "(", "f'Unable to update DDO: {response.content}'", ")" ]
Update the ddo of a did already registered. :param did: Asset DID string :param ddo: DDO instance :return: API response (depends on implementation)
[ "Update", "the", "ddo", "of", "a", "did", "already", "registered", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L153-L166
2,539
oceanprotocol/squid-py
squid_py/aquarius/aquarius.py
Aquarius.text_search
def text_search(self, text, sort=None, offset=100, page=1): """ Search in aquarius using text query. Given the string aquarius will do a full-text query to search in all documents. Currently implemented are the MongoDB and Elastic Search drivers. For a detailed guide on how to search, see the MongoDB driver documentation: mongodb driverCurrently implemented in: https://docs.mongodb.com/manual/reference/operator/query/text/ And the Elastic Search documentation: https://www.elastic.co/guide/en/elasticsearch/guide/current/full-text-search.html Other drivers are possible according to each implementation. :param text: String to be search. :param sort: 1/-1 to sort ascending or descending. :param offset: Integer with the number of elements displayed per page. :param page: Integer with the number of page. :return: List of DDO instance """ assert page >= 1, f'Invalid page value {page}. Required page >= 1.' payload = {"text": text, "sort": sort, "offset": offset, "page": page} response = self.requests_session.get( f'{self.url}/query', params=payload, headers=self._headers ) if response.status_code == 200: return self._parse_search_response(response.content) else: raise Exception(f'Unable to search for DDO: {response.content}')
python
def text_search(self, text, sort=None, offset=100, page=1): """ Search in aquarius using text query. Given the string aquarius will do a full-text query to search in all documents. Currently implemented are the MongoDB and Elastic Search drivers. For a detailed guide on how to search, see the MongoDB driver documentation: mongodb driverCurrently implemented in: https://docs.mongodb.com/manual/reference/operator/query/text/ And the Elastic Search documentation: https://www.elastic.co/guide/en/elasticsearch/guide/current/full-text-search.html Other drivers are possible according to each implementation. :param text: String to be search. :param sort: 1/-1 to sort ascending or descending. :param offset: Integer with the number of elements displayed per page. :param page: Integer with the number of page. :return: List of DDO instance """ assert page >= 1, f'Invalid page value {page}. Required page >= 1.' payload = {"text": text, "sort": sort, "offset": offset, "page": page} response = self.requests_session.get( f'{self.url}/query', params=payload, headers=self._headers ) if response.status_code == 200: return self._parse_search_response(response.content) else: raise Exception(f'Unable to search for DDO: {response.content}')
[ "def", "text_search", "(", "self", ",", "text", ",", "sort", "=", "None", ",", "offset", "=", "100", ",", "page", "=", "1", ")", ":", "assert", "page", ">=", "1", ",", "f'Invalid page value {page}. Required page >= 1.'", "payload", "=", "{", "\"text\"", ":", "text", ",", "\"sort\"", ":", "sort", ",", "\"offset\"", ":", "offset", ",", "\"page\"", ":", "page", "}", "response", "=", "self", ".", "requests_session", ".", "get", "(", "f'{self.url}/query'", ",", "params", "=", "payload", ",", "headers", "=", "self", ".", "_headers", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "self", ".", "_parse_search_response", "(", "response", ".", "content", ")", "else", ":", "raise", "Exception", "(", "f'Unable to search for DDO: {response.content}'", ")" ]
Search in aquarius using text query. Given the string aquarius will do a full-text query to search in all documents. Currently implemented are the MongoDB and Elastic Search drivers. For a detailed guide on how to search, see the MongoDB driver documentation: mongodb driverCurrently implemented in: https://docs.mongodb.com/manual/reference/operator/query/text/ And the Elastic Search documentation: https://www.elastic.co/guide/en/elasticsearch/guide/current/full-text-search.html Other drivers are possible according to each implementation. :param text: String to be search. :param sort: 1/-1 to sort ascending or descending. :param offset: Integer with the number of elements displayed per page. :param page: Integer with the number of page. :return: List of DDO instance
[ "Search", "in", "aquarius", "using", "text", "query", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L168-L200
2,540
oceanprotocol/squid-py
squid_py/aquarius/aquarius.py
Aquarius.query_search
def query_search(self, search_query, sort=None, offset=100, page=1): """ Search using a query. Currently implemented is the MongoDB query model to search for documents according to: https://docs.mongodb.com/manual/tutorial/query-documents/ And an Elastic Search driver, which implements a basic parser to convert the query into elastic search format. Example: query_search({"price":[0,10]}) :param search_query: Python dictionary, query following mongodb syntax :param sort: 1/-1 to sort ascending or descending. :param offset: Integer with the number of elements displayed per page. :param page: Integer with the number of page. :return: List of DDO instance """ assert page >= 1, f'Invalid page value {page}. Required page >= 1.' search_query['sort'] = sort search_query['offset'] = offset search_query['page'] = page response = self.requests_session.post( f'{self.url}/query', data=json.dumps(search_query), headers=self._headers ) if response.status_code == 200: return self._parse_search_response(response.content) else: raise Exception(f'Unable to search for DDO: {response.content}')
python
def query_search(self, search_query, sort=None, offset=100, page=1): """ Search using a query. Currently implemented is the MongoDB query model to search for documents according to: https://docs.mongodb.com/manual/tutorial/query-documents/ And an Elastic Search driver, which implements a basic parser to convert the query into elastic search format. Example: query_search({"price":[0,10]}) :param search_query: Python dictionary, query following mongodb syntax :param sort: 1/-1 to sort ascending or descending. :param offset: Integer with the number of elements displayed per page. :param page: Integer with the number of page. :return: List of DDO instance """ assert page >= 1, f'Invalid page value {page}. Required page >= 1.' search_query['sort'] = sort search_query['offset'] = offset search_query['page'] = page response = self.requests_session.post( f'{self.url}/query', data=json.dumps(search_query), headers=self._headers ) if response.status_code == 200: return self._parse_search_response(response.content) else: raise Exception(f'Unable to search for DDO: {response.content}')
[ "def", "query_search", "(", "self", ",", "search_query", ",", "sort", "=", "None", ",", "offset", "=", "100", ",", "page", "=", "1", ")", ":", "assert", "page", ">=", "1", ",", "f'Invalid page value {page}. Required page >= 1.'", "search_query", "[", "'sort'", "]", "=", "sort", "search_query", "[", "'offset'", "]", "=", "offset", "search_query", "[", "'page'", "]", "=", "page", "response", "=", "self", ".", "requests_session", ".", "post", "(", "f'{self.url}/query'", ",", "data", "=", "json", ".", "dumps", "(", "search_query", ")", ",", "headers", "=", "self", ".", "_headers", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "self", ".", "_parse_search_response", "(", "response", ".", "content", ")", "else", ":", "raise", "Exception", "(", "f'Unable to search for DDO: {response.content}'", ")" ]
Search using a query. Currently implemented is the MongoDB query model to search for documents according to: https://docs.mongodb.com/manual/tutorial/query-documents/ And an Elastic Search driver, which implements a basic parser to convert the query into elastic search format. Example: query_search({"price":[0,10]}) :param search_query: Python dictionary, query following mongodb syntax :param sort: 1/-1 to sort ascending or descending. :param offset: Integer with the number of elements displayed per page. :param page: Integer with the number of page. :return: List of DDO instance
[ "Search", "using", "a", "query", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L202-L232
2,541
oceanprotocol/squid-py
squid_py/aquarius/aquarius.py
Aquarius.retire_asset_ddo
def retire_asset_ddo(self, did): """ Retire asset ddo of Aquarius. :param did: Asset DID string :return: API response (depends on implementation) """ response = self.requests_session.delete(f'{self.url}/{did}', headers=self._headers) if response.status_code == 200: logging.debug(f'Removed asset DID: {did} from metadata store') return response raise AquariusGenericError(f'Unable to remove DID: {response}')
python
def retire_asset_ddo(self, did): """ Retire asset ddo of Aquarius. :param did: Asset DID string :return: API response (depends on implementation) """ response = self.requests_session.delete(f'{self.url}/{did}', headers=self._headers) if response.status_code == 200: logging.debug(f'Removed asset DID: {did} from metadata store') return response raise AquariusGenericError(f'Unable to remove DID: {response}')
[ "def", "retire_asset_ddo", "(", "self", ",", "did", ")", ":", "response", "=", "self", ".", "requests_session", ".", "delete", "(", "f'{self.url}/{did}'", ",", "headers", "=", "self", ".", "_headers", ")", "if", "response", ".", "status_code", "==", "200", ":", "logging", ".", "debug", "(", "f'Removed asset DID: {did} from metadata store'", ")", "return", "response", "raise", "AquariusGenericError", "(", "f'Unable to remove DID: {response}'", ")" ]
Retire asset ddo of Aquarius. :param did: Asset DID string :return: API response (depends on implementation)
[ "Retire", "asset", "ddo", "of", "Aquarius", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L234-L246
2,542
oceanprotocol/squid-py
squid_py/aquarius/aquarius.py
Aquarius.validate_metadata
def validate_metadata(self, metadata): """ Validate that the metadata of your ddo is valid. :param metadata: conforming to the Metadata accepted by Ocean Protocol, dict :return: bool """ response = self.requests_session.post( f'{self.url}/validate', data=json.dumps(metadata), headers=self._headers ) if response.content == b'true\n': return True else: logger.info(self._parse_search_response(response.content)) return False
python
def validate_metadata(self, metadata): """ Validate that the metadata of your ddo is valid. :param metadata: conforming to the Metadata accepted by Ocean Protocol, dict :return: bool """ response = self.requests_session.post( f'{self.url}/validate', data=json.dumps(metadata), headers=self._headers ) if response.content == b'true\n': return True else: logger.info(self._parse_search_response(response.content)) return False
[ "def", "validate_metadata", "(", "self", ",", "metadata", ")", ":", "response", "=", "self", ".", "requests_session", ".", "post", "(", "f'{self.url}/validate'", ",", "data", "=", "json", ".", "dumps", "(", "metadata", ")", ",", "headers", "=", "self", ".", "_headers", ")", "if", "response", ".", "content", "==", "b'true\\n'", ":", "return", "True", "else", ":", "logger", ".", "info", "(", "self", ".", "_parse_search_response", "(", "response", ".", "content", ")", ")", "return", "False" ]
Validate that the metadata of your ddo is valid. :param metadata: conforming to the Metadata accepted by Ocean Protocol, dict :return: bool
[ "Validate", "that", "the", "metadata", "of", "your", "ddo", "is", "valid", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/aquarius/aquarius.py#L248-L264
2,543
oceanprotocol/squid-py
squid_py/agreements/utils.py
get_sla_template_path
def get_sla_template_path(service_type=ServiceTypes.ASSET_ACCESS): """ Get the template for a ServiceType. :param service_type: ServiceTypes :return: Path of the template, str """ if service_type == ServiceTypes.ASSET_ACCESS: name = 'access_sla_template.json' elif service_type == ServiceTypes.CLOUD_COMPUTE: name = 'compute_sla_template.json' elif service_type == ServiceTypes.FITCHAIN_COMPUTE: name = 'fitchain_sla_template.json' else: raise ValueError(f'Invalid/unsupported service agreement type {service_type}') return os.path.join(os.path.sep, *os.path.realpath(__file__).split(os.path.sep)[1:-1], name)
python
def get_sla_template_path(service_type=ServiceTypes.ASSET_ACCESS): """ Get the template for a ServiceType. :param service_type: ServiceTypes :return: Path of the template, str """ if service_type == ServiceTypes.ASSET_ACCESS: name = 'access_sla_template.json' elif service_type == ServiceTypes.CLOUD_COMPUTE: name = 'compute_sla_template.json' elif service_type == ServiceTypes.FITCHAIN_COMPUTE: name = 'fitchain_sla_template.json' else: raise ValueError(f'Invalid/unsupported service agreement type {service_type}') return os.path.join(os.path.sep, *os.path.realpath(__file__).split(os.path.sep)[1:-1], name)
[ "def", "get_sla_template_path", "(", "service_type", "=", "ServiceTypes", ".", "ASSET_ACCESS", ")", ":", "if", "service_type", "==", "ServiceTypes", ".", "ASSET_ACCESS", ":", "name", "=", "'access_sla_template.json'", "elif", "service_type", "==", "ServiceTypes", ".", "CLOUD_COMPUTE", ":", "name", "=", "'compute_sla_template.json'", "elif", "service_type", "==", "ServiceTypes", ".", "FITCHAIN_COMPUTE", ":", "name", "=", "'fitchain_sla_template.json'", "else", ":", "raise", "ValueError", "(", "f'Invalid/unsupported service agreement type {service_type}'", ")", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "sep", ",", "*", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "[", "1", ":", "-", "1", "]", ",", "name", ")" ]
Get the template for a ServiceType. :param service_type: ServiceTypes :return: Path of the template, str
[ "Get", "the", "template", "for", "a", "ServiceType", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/utils.py#L11-L27
2,544
oceanprotocol/squid-py
squid_py/ocean/ocean_accounts.py
OceanAccounts.balance
def balance(self, account): """ Return the balance, a tuple with the eth and ocn balance. :param account: Account instance to return the balance of :return: Balance tuple of (eth, ocn) """ return Balance(self._keeper.get_ether_balance(account.address), self._keeper.token.get_token_balance(account.address))
python
def balance(self, account): """ Return the balance, a tuple with the eth and ocn balance. :param account: Account instance to return the balance of :return: Balance tuple of (eth, ocn) """ return Balance(self._keeper.get_ether_balance(account.address), self._keeper.token.get_token_balance(account.address))
[ "def", "balance", "(", "self", ",", "account", ")", ":", "return", "Balance", "(", "self", ".", "_keeper", ".", "get_ether_balance", "(", "account", ".", "address", ")", ",", "self", ".", "_keeper", ".", "token", ".", "get_token_balance", "(", "account", ".", "address", ")", ")" ]
Return the balance, a tuple with the eth and ocn balance. :param account: Account instance to return the balance of :return: Balance tuple of (eth, ocn)
[ "Return", "the", "balance", "a", "tuple", "with", "the", "eth", "and", "ocn", "balance", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_accounts.py#L44-L52
2,545
oceanprotocol/squid-py
squid_py/agreements/register_service_agreement.py
process_agreement_events_consumer
def process_agreement_events_consumer(publisher_address, agreement_id, did, service_agreement, price, consumer_account, condition_ids, consume_callback): """ Process the agreement events during the register of the service agreement for the consumer side. :param publisher_address: ethereum account address of publisher, hex str :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param price: Asset price, int :param consumer_account: Account instance of the consumer :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 :param consume_callback: :return: """ conditions_dict = service_agreement.condition_by_name events_manager = EventsManager.get_instance(Keeper.get_instance()) events_manager.watch_agreement_created_event( agreement_id, lock_reward_condition.fulfillLockRewardCondition, None, (agreement_id, price, consumer_account), EVENT_WAIT_TIMEOUT, ) if consume_callback: def _refund_callback(_price, _publisher_address, _condition_ids): def do_refund(_event, _agreement_id, _did, _service_agreement, _consumer_account, *_): escrow_reward_condition.refund_reward( _event, _agreement_id, _did, _service_agreement, _price, _consumer_account, _publisher_address, _condition_ids ) return do_refund events_manager.watch_access_event( agreement_id, escrow_reward_condition.consume_asset, _refund_callback(price, publisher_address, condition_ids), (agreement_id, did, service_agreement, consumer_account, consume_callback), conditions_dict['accessSecretStore'].timeout )
python
def process_agreement_events_consumer(publisher_address, agreement_id, did, service_agreement, price, consumer_account, condition_ids, consume_callback): """ Process the agreement events during the register of the service agreement for the consumer side. :param publisher_address: ethereum account address of publisher, hex str :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param price: Asset price, int :param consumer_account: Account instance of the consumer :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 :param consume_callback: :return: """ conditions_dict = service_agreement.condition_by_name events_manager = EventsManager.get_instance(Keeper.get_instance()) events_manager.watch_agreement_created_event( agreement_id, lock_reward_condition.fulfillLockRewardCondition, None, (agreement_id, price, consumer_account), EVENT_WAIT_TIMEOUT, ) if consume_callback: def _refund_callback(_price, _publisher_address, _condition_ids): def do_refund(_event, _agreement_id, _did, _service_agreement, _consumer_account, *_): escrow_reward_condition.refund_reward( _event, _agreement_id, _did, _service_agreement, _price, _consumer_account, _publisher_address, _condition_ids ) return do_refund events_manager.watch_access_event( agreement_id, escrow_reward_condition.consume_asset, _refund_callback(price, publisher_address, condition_ids), (agreement_id, did, service_agreement, consumer_account, consume_callback), conditions_dict['accessSecretStore'].timeout )
[ "def", "process_agreement_events_consumer", "(", "publisher_address", ",", "agreement_id", ",", "did", ",", "service_agreement", ",", "price", ",", "consumer_account", ",", "condition_ids", ",", "consume_callback", ")", ":", "conditions_dict", "=", "service_agreement", ".", "condition_by_name", "events_manager", "=", "EventsManager", ".", "get_instance", "(", "Keeper", ".", "get_instance", "(", ")", ")", "events_manager", ".", "watch_agreement_created_event", "(", "agreement_id", ",", "lock_reward_condition", ".", "fulfillLockRewardCondition", ",", "None", ",", "(", "agreement_id", ",", "price", ",", "consumer_account", ")", ",", "EVENT_WAIT_TIMEOUT", ",", ")", "if", "consume_callback", ":", "def", "_refund_callback", "(", "_price", ",", "_publisher_address", ",", "_condition_ids", ")", ":", "def", "do_refund", "(", "_event", ",", "_agreement_id", ",", "_did", ",", "_service_agreement", ",", "_consumer_account", ",", "*", "_", ")", ":", "escrow_reward_condition", ".", "refund_reward", "(", "_event", ",", "_agreement_id", ",", "_did", ",", "_service_agreement", ",", "_price", ",", "_consumer_account", ",", "_publisher_address", ",", "_condition_ids", ")", "return", "do_refund", "events_manager", ".", "watch_access_event", "(", "agreement_id", ",", "escrow_reward_condition", ".", "consume_asset", ",", "_refund_callback", "(", "price", ",", "publisher_address", ",", "condition_ids", ")", ",", "(", "agreement_id", ",", "did", ",", "service_agreement", ",", "consumer_account", ",", "consume_callback", ")", ",", "conditions_dict", "[", "'accessSecretStore'", "]", ".", "timeout", ")" ]
Process the agreement events during the register of the service agreement for the consumer side. :param publisher_address: ethereum account address of publisher, hex str :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param price: Asset price, int :param consumer_account: Account instance of the consumer :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 :param consume_callback: :return:
[ "Process", "the", "agreement", "events", "during", "the", "register", "of", "the", "service", "agreement", "for", "the", "consumer", "side", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/register_service_agreement.py#L54-L96
2,546
oceanprotocol/squid-py
squid_py/agreements/register_service_agreement.py
process_agreement_events_publisher
def process_agreement_events_publisher(publisher_account, agreement_id, did, service_agreement, price, consumer_address, condition_ids): """ Process the agreement events during the register of the service agreement for the publisher side :param publisher_account: Account instance of the publisher :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param price: Asset price, int :param consumer_address: ethereum account address of consumer, hex str :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 :return: """ conditions_dict = service_agreement.condition_by_name events_manager = EventsManager.get_instance(Keeper.get_instance()) events_manager.watch_lock_reward_event( agreement_id, access_secret_store_condition.fulfillAccessSecretStoreCondition, None, (agreement_id, did, service_agreement, consumer_address, publisher_account), conditions_dict['lockReward'].timeout ) events_manager.watch_access_event( agreement_id, escrow_reward_condition.fulfillEscrowRewardCondition, None, (agreement_id, service_agreement, price, consumer_address, publisher_account, condition_ids), conditions_dict['accessSecretStore'].timeout ) events_manager.watch_reward_event( agreement_id, verify_reward_condition.verifyRewardTokens, None, (agreement_id, did, service_agreement, price, consumer_address, publisher_account), conditions_dict['escrowReward'].timeout )
python
def process_agreement_events_publisher(publisher_account, agreement_id, did, service_agreement, price, consumer_address, condition_ids): """ Process the agreement events during the register of the service agreement for the publisher side :param publisher_account: Account instance of the publisher :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param price: Asset price, int :param consumer_address: ethereum account address of consumer, hex str :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 :return: """ conditions_dict = service_agreement.condition_by_name events_manager = EventsManager.get_instance(Keeper.get_instance()) events_manager.watch_lock_reward_event( agreement_id, access_secret_store_condition.fulfillAccessSecretStoreCondition, None, (agreement_id, did, service_agreement, consumer_address, publisher_account), conditions_dict['lockReward'].timeout ) events_manager.watch_access_event( agreement_id, escrow_reward_condition.fulfillEscrowRewardCondition, None, (agreement_id, service_agreement, price, consumer_address, publisher_account, condition_ids), conditions_dict['accessSecretStore'].timeout ) events_manager.watch_reward_event( agreement_id, verify_reward_condition.verifyRewardTokens, None, (agreement_id, did, service_agreement, price, consumer_address, publisher_account), conditions_dict['escrowReward'].timeout )
[ "def", "process_agreement_events_publisher", "(", "publisher_account", ",", "agreement_id", ",", "did", ",", "service_agreement", ",", "price", ",", "consumer_address", ",", "condition_ids", ")", ":", "conditions_dict", "=", "service_agreement", ".", "condition_by_name", "events_manager", "=", "EventsManager", ".", "get_instance", "(", "Keeper", ".", "get_instance", "(", ")", ")", "events_manager", ".", "watch_lock_reward_event", "(", "agreement_id", ",", "access_secret_store_condition", ".", "fulfillAccessSecretStoreCondition", ",", "None", ",", "(", "agreement_id", ",", "did", ",", "service_agreement", ",", "consumer_address", ",", "publisher_account", ")", ",", "conditions_dict", "[", "'lockReward'", "]", ".", "timeout", ")", "events_manager", ".", "watch_access_event", "(", "agreement_id", ",", "escrow_reward_condition", ".", "fulfillEscrowRewardCondition", ",", "None", ",", "(", "agreement_id", ",", "service_agreement", ",", "price", ",", "consumer_address", ",", "publisher_account", ",", "condition_ids", ")", ",", "conditions_dict", "[", "'accessSecretStore'", "]", ".", "timeout", ")", "events_manager", ".", "watch_reward_event", "(", "agreement_id", ",", "verify_reward_condition", ".", "verifyRewardTokens", ",", "None", ",", "(", "agreement_id", ",", "did", ",", "service_agreement", ",", "price", ",", "consumer_address", ",", "publisher_account", ")", ",", "conditions_dict", "[", "'escrowReward'", "]", ".", "timeout", ")" ]
Process the agreement events during the register of the service agreement for the publisher side :param publisher_account: Account instance of the publisher :param agreement_id: id of the agreement, hex str :param did: DID, str :param service_agreement: ServiceAgreement instance :param price: Asset price, int :param consumer_address: ethereum account address of consumer, hex str :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 :return:
[ "Process", "the", "agreement", "events", "during", "the", "register", "of", "the", "service", "agreement", "for", "the", "publisher", "side" ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/register_service_agreement.py#L130-L171
2,547
oceanprotocol/squid-py
squid_py/agreements/register_service_agreement.py
execute_pending_service_agreements
def execute_pending_service_agreements(storage_path, account, actor_type, did_resolver_fn): """ Iterates over pending service agreements recorded in the local storage, fetches their service definitions, and subscribes to service agreement events. :param storage_path: storage path for the internal db, str :param account: :param actor_type: :param did_resolver_fn: :return: """ keeper = Keeper.get_instance() # service_agreement_id, did, service_definition_id, price, files, start_time, status for (agreement_id, did, _, price, files, start_time, _) in get_service_agreements(storage_path): ddo = did_resolver_fn(did) for service in ddo.services: if service.type != 'Access': continue consumer_provider_tuple = keeper.escrow_access_secretstore_template.get_agreement_data( agreement_id) if not consumer_provider_tuple: continue consumer, provider = consumer_provider_tuple did = ddo.did service_agreement = ServiceAgreement.from_service_dict(service.as_dictionary()) condition_ids = service_agreement.generate_agreement_condition_ids( agreement_id, did, consumer, provider, keeper) if actor_type == 'consumer': assert account.address == consumer process_agreement_events_consumer( provider, agreement_id, did, service_agreement, price, account, condition_ids, None) else: assert account.address == provider process_agreement_events_publisher( account, agreement_id, did, service_agreement, price, consumer, condition_ids)
python
def execute_pending_service_agreements(storage_path, account, actor_type, did_resolver_fn): """ Iterates over pending service agreements recorded in the local storage, fetches their service definitions, and subscribes to service agreement events. :param storage_path: storage path for the internal db, str :param account: :param actor_type: :param did_resolver_fn: :return: """ keeper = Keeper.get_instance() # service_agreement_id, did, service_definition_id, price, files, start_time, status for (agreement_id, did, _, price, files, start_time, _) in get_service_agreements(storage_path): ddo = did_resolver_fn(did) for service in ddo.services: if service.type != 'Access': continue consumer_provider_tuple = keeper.escrow_access_secretstore_template.get_agreement_data( agreement_id) if not consumer_provider_tuple: continue consumer, provider = consumer_provider_tuple did = ddo.did service_agreement = ServiceAgreement.from_service_dict(service.as_dictionary()) condition_ids = service_agreement.generate_agreement_condition_ids( agreement_id, did, consumer, provider, keeper) if actor_type == 'consumer': assert account.address == consumer process_agreement_events_consumer( provider, agreement_id, did, service_agreement, price, account, condition_ids, None) else: assert account.address == provider process_agreement_events_publisher( account, agreement_id, did, service_agreement, price, consumer, condition_ids)
[ "def", "execute_pending_service_agreements", "(", "storage_path", ",", "account", ",", "actor_type", ",", "did_resolver_fn", ")", ":", "keeper", "=", "Keeper", ".", "get_instance", "(", ")", "# service_agreement_id, did, service_definition_id, price, files, start_time, status", "for", "(", "agreement_id", ",", "did", ",", "_", ",", "price", ",", "files", ",", "start_time", ",", "_", ")", "in", "get_service_agreements", "(", "storage_path", ")", ":", "ddo", "=", "did_resolver_fn", "(", "did", ")", "for", "service", "in", "ddo", ".", "services", ":", "if", "service", ".", "type", "!=", "'Access'", ":", "continue", "consumer_provider_tuple", "=", "keeper", ".", "escrow_access_secretstore_template", ".", "get_agreement_data", "(", "agreement_id", ")", "if", "not", "consumer_provider_tuple", ":", "continue", "consumer", ",", "provider", "=", "consumer_provider_tuple", "did", "=", "ddo", ".", "did", "service_agreement", "=", "ServiceAgreement", ".", "from_service_dict", "(", "service", ".", "as_dictionary", "(", ")", ")", "condition_ids", "=", "service_agreement", ".", "generate_agreement_condition_ids", "(", "agreement_id", ",", "did", ",", "consumer", ",", "provider", ",", "keeper", ")", "if", "actor_type", "==", "'consumer'", ":", "assert", "account", ".", "address", "==", "consumer", "process_agreement_events_consumer", "(", "provider", ",", "agreement_id", ",", "did", ",", "service_agreement", ",", "price", ",", "account", ",", "condition_ids", ",", "None", ")", "else", ":", "assert", "account", ".", "address", "==", "provider", "process_agreement_events_publisher", "(", "account", ",", "agreement_id", ",", "did", ",", "service_agreement", ",", "price", ",", "consumer", ",", "condition_ids", ")" ]
Iterates over pending service agreements recorded in the local storage, fetches their service definitions, and subscribes to service agreement events. :param storage_path: storage path for the internal db, str :param account: :param actor_type: :param did_resolver_fn: :return:
[ "Iterates", "over", "pending", "service", "agreements", "recorded", "in", "the", "local", "storage", "fetches", "their", "service", "definitions", "and", "subscribes", "to", "service", "agreement", "events", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/register_service_agreement.py#L174-L215
2,548
oceanprotocol/squid-py
squid_py/keeper/utils.py
generate_multi_value_hash
def generate_multi_value_hash(types, values): """ Return the hash of the given list of values. This is equivalent to packing and hashing values in a solidity smart contract hence the use of `soliditySha3`. :param types: list of solidity types expressed as strings :param values: list of values matching the `types` list :return: bytes """ assert len(types) == len(values) return Web3Provider.get_web3().soliditySha3( types, values )
python
def generate_multi_value_hash(types, values): """ Return the hash of the given list of values. This is equivalent to packing and hashing values in a solidity smart contract hence the use of `soliditySha3`. :param types: list of solidity types expressed as strings :param values: list of values matching the `types` list :return: bytes """ assert len(types) == len(values) return Web3Provider.get_web3().soliditySha3( types, values )
[ "def", "generate_multi_value_hash", "(", "types", ",", "values", ")", ":", "assert", "len", "(", "types", ")", "==", "len", "(", "values", ")", "return", "Web3Provider", ".", "get_web3", "(", ")", ".", "soliditySha3", "(", "types", ",", "values", ")" ]
Return the hash of the given list of values. This is equivalent to packing and hashing values in a solidity smart contract hence the use of `soliditySha3`. :param types: list of solidity types expressed as strings :param values: list of values matching the `types` list :return: bytes
[ "Return", "the", "hash", "of", "the", "given", "list", "of", "values", ".", "This", "is", "equivalent", "to", "packing", "and", "hashing", "values", "in", "a", "solidity", "smart", "contract", "hence", "the", "use", "of", "soliditySha3", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/utils.py#L14-L28
2,549
oceanprotocol/squid-py
squid_py/keeper/utils.py
process_tx_receipt
def process_tx_receipt(tx_hash, event, event_name): """ Wait until the tx receipt is processed. :param tx_hash: hash of the transaction :param event: AttributeDict with the event data. :param event_name: name of the event to subscribe, str :return: """ web3 = Web3Provider.get_web3() try: web3.eth.waitForTransactionReceipt(tx_hash, timeout=20) except Timeout: logger.info('Waiting for transaction receipt timed out. Cannot verify receipt and event.') return receipt = web3.eth.getTransactionReceipt(tx_hash) event = event().processReceipt(receipt) if event: logger.info(f'Success: got {event_name} event after fulfilling condition.') logger.debug( f'Success: got {event_name} event after fulfilling condition. {receipt}, ::: {event}') else: logger.debug(f'Something is not right, cannot find the {event_name} event after calling the' f' fulfillment condition. This is the transaction receipt {receipt}') if receipt and receipt.status == 0: logger.warning( f'Transaction failed: tx_hash {tx_hash}, tx event {event_name}, receipt {receipt}')
python
def process_tx_receipt(tx_hash, event, event_name): """ Wait until the tx receipt is processed. :param tx_hash: hash of the transaction :param event: AttributeDict with the event data. :param event_name: name of the event to subscribe, str :return: """ web3 = Web3Provider.get_web3() try: web3.eth.waitForTransactionReceipt(tx_hash, timeout=20) except Timeout: logger.info('Waiting for transaction receipt timed out. Cannot verify receipt and event.') return receipt = web3.eth.getTransactionReceipt(tx_hash) event = event().processReceipt(receipt) if event: logger.info(f'Success: got {event_name} event after fulfilling condition.') logger.debug( f'Success: got {event_name} event after fulfilling condition. {receipt}, ::: {event}') else: logger.debug(f'Something is not right, cannot find the {event_name} event after calling the' f' fulfillment condition. This is the transaction receipt {receipt}') if receipt and receipt.status == 0: logger.warning( f'Transaction failed: tx_hash {tx_hash}, tx event {event_name}, receipt {receipt}')
[ "def", "process_tx_receipt", "(", "tx_hash", ",", "event", ",", "event_name", ")", ":", "web3", "=", "Web3Provider", ".", "get_web3", "(", ")", "try", ":", "web3", ".", "eth", ".", "waitForTransactionReceipt", "(", "tx_hash", ",", "timeout", "=", "20", ")", "except", "Timeout", ":", "logger", ".", "info", "(", "'Waiting for transaction receipt timed out. Cannot verify receipt and event.'", ")", "return", "receipt", "=", "web3", ".", "eth", ".", "getTransactionReceipt", "(", "tx_hash", ")", "event", "=", "event", "(", ")", ".", "processReceipt", "(", "receipt", ")", "if", "event", ":", "logger", ".", "info", "(", "f'Success: got {event_name} event after fulfilling condition.'", ")", "logger", ".", "debug", "(", "f'Success: got {event_name} event after fulfilling condition. {receipt}, ::: {event}'", ")", "else", ":", "logger", ".", "debug", "(", "f'Something is not right, cannot find the {event_name} event after calling the'", "f' fulfillment condition. This is the transaction receipt {receipt}'", ")", "if", "receipt", "and", "receipt", ".", "status", "==", "0", ":", "logger", ".", "warning", "(", "f'Transaction failed: tx_hash {tx_hash}, tx event {event_name}, receipt {receipt}'", ")" ]
Wait until the tx receipt is processed. :param tx_hash: hash of the transaction :param event: AttributeDict with the event data. :param event_name: name of the event to subscribe, str :return:
[ "Wait", "until", "the", "tx", "receipt", "is", "processed", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/utils.py#L31-L59
2,550
oceanprotocol/squid-py
squid_py/keeper/conditions/condition_manager.py
ConditionStoreManager.get_condition
def get_condition(self, condition_id): """Retrieve the condition for a condition_id. :param condition_id: id of the condition, str :return: """ condition = self.contract_concise.getCondition(condition_id) if condition and len(condition) == 7: return ConditionValues(*condition) return None
python
def get_condition(self, condition_id): """Retrieve the condition for a condition_id. :param condition_id: id of the condition, str :return: """ condition = self.contract_concise.getCondition(condition_id) if condition and len(condition) == 7: return ConditionValues(*condition) return None
[ "def", "get_condition", "(", "self", ",", "condition_id", ")", ":", "condition", "=", "self", ".", "contract_concise", ".", "getCondition", "(", "condition_id", ")", "if", "condition", "and", "len", "(", "condition", ")", "==", "7", ":", "return", "ConditionValues", "(", "*", "condition", ")", "return", "None" ]
Retrieve the condition for a condition_id. :param condition_id: id of the condition, str :return:
[ "Retrieve", "the", "condition", "for", "a", "condition_id", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/condition_manager.py#L19-L29
2,551
oceanprotocol/squid-py
squid_py/keeper/conditions/sign.py
SignCondition.fulfill
def fulfill(self, agreement_id, message, account_address, signature, from_account): """ Fulfill the sign conditon. :param agreement_id: id of the agreement, hex str :param message: :param account_address: ethereum account address, hex str :param signature: signed agreement hash, hex str :param from_account: Account doing the transaction :return: """ return self._fulfill( agreement_id, message, account_address, signature, transact={'from': from_account.address, 'passphrase': from_account.password} )
python
def fulfill(self, agreement_id, message, account_address, signature, from_account): """ Fulfill the sign conditon. :param agreement_id: id of the agreement, hex str :param message: :param account_address: ethereum account address, hex str :param signature: signed agreement hash, hex str :param from_account: Account doing the transaction :return: """ return self._fulfill( agreement_id, message, account_address, signature, transact={'from': from_account.address, 'passphrase': from_account.password} )
[ "def", "fulfill", "(", "self", ",", "agreement_id", ",", "message", ",", "account_address", ",", "signature", ",", "from_account", ")", ":", "return", "self", ".", "_fulfill", "(", "agreement_id", ",", "message", ",", "account_address", ",", "signature", ",", "transact", "=", "{", "'from'", ":", "from_account", ".", "address", ",", "'passphrase'", ":", "from_account", ".", "password", "}", ")" ]
Fulfill the sign conditon. :param agreement_id: id of the agreement, hex str :param message: :param account_address: ethereum account address, hex str :param signature: signed agreement hash, hex str :param from_account: Account doing the transaction :return:
[ "Fulfill", "the", "sign", "conditon", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/sign.py#L11-L29
2,552
oceanprotocol/squid-py
squid_py/ocean/ocean_agreements.py
OceanAgreements.create
def create(self, did, service_definition_id, agreement_id, service_agreement_signature, consumer_address, account): """ Execute the service agreement on-chain using keeper's ServiceAgreement contract. The on-chain executeAgreement method requires the following arguments: templateId, signature, consumer, hashes, timeouts, serviceAgreementId, did. `agreement_message_hash` is necessary to verify the signature. The consumer `signature` includes the conditions timeouts and parameters values which is usedon-chain to verify that the values actually match the signed hashes. :param did: str representation fo the asset DID. Use this to retrieve the asset DDO. :param service_definition_id: str identifies the specific service in the ddo to use in this agreement. :param agreement_id: 32 bytes identifier created by the consumer and will be used on-chain for the executed agreement. :param service_agreement_signature: str the signed agreement message hash which includes conditions and their parameters values and other details of the agreement. :param consumer_address: ethereum account address of consumer, hex str :param account: Account instance creating the agreement. Can be either the consumer, publisher or provider :return: dict the `executeAgreement` transaction receipt """ assert consumer_address and Web3Provider.get_web3().isChecksumAddress( consumer_address), f'Invalid consumer address {consumer_address}' assert account.address in self._keeper.accounts, \ f'Unrecognized account address {account.address}' agreement_template_approved = self._keeper.template_manager.is_template_approved( self._keeper.escrow_access_secretstore_template.address) if not agreement_template_approved: msg = (f'The EscrowAccessSecretStoreTemplate contract at address ' f'{self._keeper.escrow_access_secretstore_template.address} is not ' f'approved and cannot be used for creating service agreements.') logger.warning(msg) raise OceanInvalidAgreementTemplate(msg) asset = self._asset_resolver.resolve(did) asset_id = asset.asset_id service_agreement = ServiceAgreement.from_ddo(service_definition_id, asset) agreement_template = self._keeper.escrow_access_secretstore_template if agreement_template.get_agreement_consumer(agreement_id) is not None: raise OceanServiceAgreementExists( f'Service agreement {agreement_id} already exists, cannot reuse ' f'the same agreement id.') if consumer_address != account.address: if not self._verify_service_agreement_signature( did, agreement_id, service_definition_id, consumer_address, service_agreement_signature, ddo=asset ): raise OceanInvalidServiceAgreementSignature( f'Verifying consumer signature failed: ' f'signature {service_agreement_signature}, ' f'consumerAddress {consumer_address}' ) publisher_address = Web3Provider.get_web3().toChecksumAddress(asset.publisher) condition_ids = service_agreement.generate_agreement_condition_ids( agreement_id, asset_id, consumer_address, publisher_address, self._keeper) time_locks = service_agreement.conditions_timelocks time_outs = service_agreement.conditions_timeouts success = agreement_template.create_agreement( agreement_id, asset_id, condition_ids, time_locks, time_outs, consumer_address, account ) if not success: # success is based on tx receipt which is not reliable. # So we check on-chain directly to see if agreement_id is there consumer = self._keeper.escrow_access_secretstore_template.get_agreement_consumer(agreement_id) if consumer: success = True else: event_log = self._keeper.escrow_access_secretstore_template.subscribe_agreement_created( agreement_id, 30, None, (), wait=True ) success = event_log is not None if success: logger.info(f'Service agreement {agreement_id} created successfully.') else: logger.info(f'Create agreement "{agreement_id}" failed.') self._log_agreement_info( asset, service_agreement, agreement_id, service_agreement_signature, consumer_address, account, condition_ids ) if success: # subscribe to events related to this agreement_id if consumer_address == account.address: register_service_agreement_consumer( self._config.storage_path, publisher_address, agreement_id, did, service_agreement, service_definition_id, service_agreement.get_price(), asset.encrypted_files, account, condition_ids, None ) else: register_service_agreement_publisher( self._config.storage_path, consumer_address, agreement_id, did, service_agreement, service_definition_id, service_agreement.get_price(), account, condition_ids ) return success
python
def create(self, did, service_definition_id, agreement_id, service_agreement_signature, consumer_address, account): """ Execute the service agreement on-chain using keeper's ServiceAgreement contract. The on-chain executeAgreement method requires the following arguments: templateId, signature, consumer, hashes, timeouts, serviceAgreementId, did. `agreement_message_hash` is necessary to verify the signature. The consumer `signature` includes the conditions timeouts and parameters values which is usedon-chain to verify that the values actually match the signed hashes. :param did: str representation fo the asset DID. Use this to retrieve the asset DDO. :param service_definition_id: str identifies the specific service in the ddo to use in this agreement. :param agreement_id: 32 bytes identifier created by the consumer and will be used on-chain for the executed agreement. :param service_agreement_signature: str the signed agreement message hash which includes conditions and their parameters values and other details of the agreement. :param consumer_address: ethereum account address of consumer, hex str :param account: Account instance creating the agreement. Can be either the consumer, publisher or provider :return: dict the `executeAgreement` transaction receipt """ assert consumer_address and Web3Provider.get_web3().isChecksumAddress( consumer_address), f'Invalid consumer address {consumer_address}' assert account.address in self._keeper.accounts, \ f'Unrecognized account address {account.address}' agreement_template_approved = self._keeper.template_manager.is_template_approved( self._keeper.escrow_access_secretstore_template.address) if not agreement_template_approved: msg = (f'The EscrowAccessSecretStoreTemplate contract at address ' f'{self._keeper.escrow_access_secretstore_template.address} is not ' f'approved and cannot be used for creating service agreements.') logger.warning(msg) raise OceanInvalidAgreementTemplate(msg) asset = self._asset_resolver.resolve(did) asset_id = asset.asset_id service_agreement = ServiceAgreement.from_ddo(service_definition_id, asset) agreement_template = self._keeper.escrow_access_secretstore_template if agreement_template.get_agreement_consumer(agreement_id) is not None: raise OceanServiceAgreementExists( f'Service agreement {agreement_id} already exists, cannot reuse ' f'the same agreement id.') if consumer_address != account.address: if not self._verify_service_agreement_signature( did, agreement_id, service_definition_id, consumer_address, service_agreement_signature, ddo=asset ): raise OceanInvalidServiceAgreementSignature( f'Verifying consumer signature failed: ' f'signature {service_agreement_signature}, ' f'consumerAddress {consumer_address}' ) publisher_address = Web3Provider.get_web3().toChecksumAddress(asset.publisher) condition_ids = service_agreement.generate_agreement_condition_ids( agreement_id, asset_id, consumer_address, publisher_address, self._keeper) time_locks = service_agreement.conditions_timelocks time_outs = service_agreement.conditions_timeouts success = agreement_template.create_agreement( agreement_id, asset_id, condition_ids, time_locks, time_outs, consumer_address, account ) if not success: # success is based on tx receipt which is not reliable. # So we check on-chain directly to see if agreement_id is there consumer = self._keeper.escrow_access_secretstore_template.get_agreement_consumer(agreement_id) if consumer: success = True else: event_log = self._keeper.escrow_access_secretstore_template.subscribe_agreement_created( agreement_id, 30, None, (), wait=True ) success = event_log is not None if success: logger.info(f'Service agreement {agreement_id} created successfully.') else: logger.info(f'Create agreement "{agreement_id}" failed.') self._log_agreement_info( asset, service_agreement, agreement_id, service_agreement_signature, consumer_address, account, condition_ids ) if success: # subscribe to events related to this agreement_id if consumer_address == account.address: register_service_agreement_consumer( self._config.storage_path, publisher_address, agreement_id, did, service_agreement, service_definition_id, service_agreement.get_price(), asset.encrypted_files, account, condition_ids, None ) else: register_service_agreement_publisher( self._config.storage_path, consumer_address, agreement_id, did, service_agreement, service_definition_id, service_agreement.get_price(), account, condition_ids ) return success
[ "def", "create", "(", "self", ",", "did", ",", "service_definition_id", ",", "agreement_id", ",", "service_agreement_signature", ",", "consumer_address", ",", "account", ")", ":", "assert", "consumer_address", "and", "Web3Provider", ".", "get_web3", "(", ")", ".", "isChecksumAddress", "(", "consumer_address", ")", ",", "f'Invalid consumer address {consumer_address}'", "assert", "account", ".", "address", "in", "self", ".", "_keeper", ".", "accounts", ",", "f'Unrecognized account address {account.address}'", "agreement_template_approved", "=", "self", ".", "_keeper", ".", "template_manager", ".", "is_template_approved", "(", "self", ".", "_keeper", ".", "escrow_access_secretstore_template", ".", "address", ")", "if", "not", "agreement_template_approved", ":", "msg", "=", "(", "f'The EscrowAccessSecretStoreTemplate contract at address '", "f'{self._keeper.escrow_access_secretstore_template.address} is not '", "f'approved and cannot be used for creating service agreements.'", ")", "logger", ".", "warning", "(", "msg", ")", "raise", "OceanInvalidAgreementTemplate", "(", "msg", ")", "asset", "=", "self", ".", "_asset_resolver", ".", "resolve", "(", "did", ")", "asset_id", "=", "asset", ".", "asset_id", "service_agreement", "=", "ServiceAgreement", ".", "from_ddo", "(", "service_definition_id", ",", "asset", ")", "agreement_template", "=", "self", ".", "_keeper", ".", "escrow_access_secretstore_template", "if", "agreement_template", ".", "get_agreement_consumer", "(", "agreement_id", ")", "is", "not", "None", ":", "raise", "OceanServiceAgreementExists", "(", "f'Service agreement {agreement_id} already exists, cannot reuse '", "f'the same agreement id.'", ")", "if", "consumer_address", "!=", "account", ".", "address", ":", "if", "not", "self", ".", "_verify_service_agreement_signature", "(", "did", ",", "agreement_id", ",", "service_definition_id", ",", "consumer_address", ",", "service_agreement_signature", ",", "ddo", "=", "asset", ")", ":", "raise", "OceanInvalidServiceAgreementSignature", "(", "f'Verifying consumer signature failed: '", "f'signature {service_agreement_signature}, '", "f'consumerAddress {consumer_address}'", ")", "publisher_address", "=", "Web3Provider", ".", "get_web3", "(", ")", ".", "toChecksumAddress", "(", "asset", ".", "publisher", ")", "condition_ids", "=", "service_agreement", ".", "generate_agreement_condition_ids", "(", "agreement_id", ",", "asset_id", ",", "consumer_address", ",", "publisher_address", ",", "self", ".", "_keeper", ")", "time_locks", "=", "service_agreement", ".", "conditions_timelocks", "time_outs", "=", "service_agreement", ".", "conditions_timeouts", "success", "=", "agreement_template", ".", "create_agreement", "(", "agreement_id", ",", "asset_id", ",", "condition_ids", ",", "time_locks", ",", "time_outs", ",", "consumer_address", ",", "account", ")", "if", "not", "success", ":", "# success is based on tx receipt which is not reliable.", "# So we check on-chain directly to see if agreement_id is there", "consumer", "=", "self", ".", "_keeper", ".", "escrow_access_secretstore_template", ".", "get_agreement_consumer", "(", "agreement_id", ")", "if", "consumer", ":", "success", "=", "True", "else", ":", "event_log", "=", "self", ".", "_keeper", ".", "escrow_access_secretstore_template", ".", "subscribe_agreement_created", "(", "agreement_id", ",", "30", ",", "None", ",", "(", ")", ",", "wait", "=", "True", ")", "success", "=", "event_log", "is", "not", "None", "if", "success", ":", "logger", ".", "info", "(", "f'Service agreement {agreement_id} created successfully.'", ")", "else", ":", "logger", ".", "info", "(", "f'Create agreement \"{agreement_id}\" failed.'", ")", "self", ".", "_log_agreement_info", "(", "asset", ",", "service_agreement", ",", "agreement_id", ",", "service_agreement_signature", ",", "consumer_address", ",", "account", ",", "condition_ids", ")", "if", "success", ":", "# subscribe to events related to this agreement_id", "if", "consumer_address", "==", "account", ".", "address", ":", "register_service_agreement_consumer", "(", "self", ".", "_config", ".", "storage_path", ",", "publisher_address", ",", "agreement_id", ",", "did", ",", "service_agreement", ",", "service_definition_id", ",", "service_agreement", ".", "get_price", "(", ")", ",", "asset", ".", "encrypted_files", ",", "account", ",", "condition_ids", ",", "None", ")", "else", ":", "register_service_agreement_publisher", "(", "self", ".", "_config", ".", "storage_path", ",", "consumer_address", ",", "agreement_id", ",", "did", ",", "service_agreement", ",", "service_definition_id", ",", "service_agreement", ".", "get_price", "(", ")", ",", "account", ",", "condition_ids", ")", "return", "success" ]
Execute the service agreement on-chain using keeper's ServiceAgreement contract. The on-chain executeAgreement method requires the following arguments: templateId, signature, consumer, hashes, timeouts, serviceAgreementId, did. `agreement_message_hash` is necessary to verify the signature. The consumer `signature` includes the conditions timeouts and parameters values which is usedon-chain to verify that the values actually match the signed hashes. :param did: str representation fo the asset DID. Use this to retrieve the asset DDO. :param service_definition_id: str identifies the specific service in the ddo to use in this agreement. :param agreement_id: 32 bytes identifier created by the consumer and will be used on-chain for the executed agreement. :param service_agreement_signature: str the signed agreement message hash which includes conditions and their parameters values and other details of the agreement. :param consumer_address: ethereum account address of consumer, hex str :param account: Account instance creating the agreement. Can be either the consumer, publisher or provider :return: dict the `executeAgreement` transaction receipt
[ "Execute", "the", "service", "agreement", "on", "-", "chain", "using", "keeper", "s", "ServiceAgreement", "contract", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_agreements.py#L126-L252
2,553
oceanprotocol/squid-py
squid_py/ocean/ocean_agreements.py
OceanAgreements.is_access_granted
def is_access_granted(self, agreement_id, did, consumer_address): """ Check permission for the agreement. Verify on-chain that the `consumer_address` has permission to access the given asset `did` according to the `agreement_id`. :param agreement_id: id of the agreement, hex str :param did: DID, str :param consumer_address: ethereum account address of consumer, hex str :return: bool True if user has permission """ agreement_consumer = self._keeper.escrow_access_secretstore_template.get_agreement_consumer( agreement_id) if agreement_consumer != consumer_address: logger.warning(f'Invalid consumer address {consumer_address} and/or ' f'service agreement id {agreement_id} (did {did})' f', agreement consumer is {agreement_consumer}') return False document_id = did_to_id(did) return self._keeper.access_secret_store_condition.check_permissions( document_id, consumer_address )
python
def is_access_granted(self, agreement_id, did, consumer_address): """ Check permission for the agreement. Verify on-chain that the `consumer_address` has permission to access the given asset `did` according to the `agreement_id`. :param agreement_id: id of the agreement, hex str :param did: DID, str :param consumer_address: ethereum account address of consumer, hex str :return: bool True if user has permission """ agreement_consumer = self._keeper.escrow_access_secretstore_template.get_agreement_consumer( agreement_id) if agreement_consumer != consumer_address: logger.warning(f'Invalid consumer address {consumer_address} and/or ' f'service agreement id {agreement_id} (did {did})' f', agreement consumer is {agreement_consumer}') return False document_id = did_to_id(did) return self._keeper.access_secret_store_condition.check_permissions( document_id, consumer_address )
[ "def", "is_access_granted", "(", "self", ",", "agreement_id", ",", "did", ",", "consumer_address", ")", ":", "agreement_consumer", "=", "self", ".", "_keeper", ".", "escrow_access_secretstore_template", ".", "get_agreement_consumer", "(", "agreement_id", ")", "if", "agreement_consumer", "!=", "consumer_address", ":", "logger", ".", "warning", "(", "f'Invalid consumer address {consumer_address} and/or '", "f'service agreement id {agreement_id} (did {did})'", "f', agreement consumer is {agreement_consumer}'", ")", "return", "False", "document_id", "=", "did_to_id", "(", "did", ")", "return", "self", ".", "_keeper", ".", "access_secret_store_condition", ".", "check_permissions", "(", "document_id", ",", "consumer_address", ")" ]
Check permission for the agreement. Verify on-chain that the `consumer_address` has permission to access the given asset `did` according to the `agreement_id`. :param agreement_id: id of the agreement, hex str :param did: DID, str :param consumer_address: ethereum account address of consumer, hex str :return: bool True if user has permission
[ "Check", "permission", "for", "the", "agreement", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_agreements.py#L273-L296
2,554
oceanprotocol/squid-py
squid_py/ocean/ocean_agreements.py
OceanAgreements._verify_service_agreement_signature
def _verify_service_agreement_signature(self, did, agreement_id, service_definition_id, consumer_address, signature, ddo=None): """ Verify service agreement signature. Verify that the given signature is truly signed by the `consumer_address` and represents this did's service agreement.. :param did: DID, str :param agreement_id: id of the agreement, hex str :param service_definition_id: identifier of the service inside the asset DDO, str :param consumer_address: ethereum account address of consumer, hex str :param signature: Signature, str :param ddo: DDO instance :return: True if signature is legitimate, False otherwise :raises: ValueError if service is not found in the ddo :raises: AssertionError if conditions keys do not match the on-chain conditions keys """ if not ddo: ddo = self._asset_resolver.resolve(did) service_agreement = ServiceAgreement.from_ddo(service_definition_id, ddo) agreement_hash = service_agreement.get_service_agreement_hash( agreement_id, ddo.asset_id, consumer_address, Web3Provider.get_web3().toChecksumAddress(ddo.proof['creator']), self._keeper) prefixed_hash = prepare_prefixed_hash(agreement_hash) recovered_address = Web3Provider.get_web3().eth.account.recoverHash( prefixed_hash, signature=signature ) is_valid = (recovered_address == consumer_address) if not is_valid: logger.warning(f'Agreement signature failed: agreement hash is {agreement_hash.hex()}') return is_valid
python
def _verify_service_agreement_signature(self, did, agreement_id, service_definition_id, consumer_address, signature, ddo=None): """ Verify service agreement signature. Verify that the given signature is truly signed by the `consumer_address` and represents this did's service agreement.. :param did: DID, str :param agreement_id: id of the agreement, hex str :param service_definition_id: identifier of the service inside the asset DDO, str :param consumer_address: ethereum account address of consumer, hex str :param signature: Signature, str :param ddo: DDO instance :return: True if signature is legitimate, False otherwise :raises: ValueError if service is not found in the ddo :raises: AssertionError if conditions keys do not match the on-chain conditions keys """ if not ddo: ddo = self._asset_resolver.resolve(did) service_agreement = ServiceAgreement.from_ddo(service_definition_id, ddo) agreement_hash = service_agreement.get_service_agreement_hash( agreement_id, ddo.asset_id, consumer_address, Web3Provider.get_web3().toChecksumAddress(ddo.proof['creator']), self._keeper) prefixed_hash = prepare_prefixed_hash(agreement_hash) recovered_address = Web3Provider.get_web3().eth.account.recoverHash( prefixed_hash, signature=signature ) is_valid = (recovered_address == consumer_address) if not is_valid: logger.warning(f'Agreement signature failed: agreement hash is {agreement_hash.hex()}') return is_valid
[ "def", "_verify_service_agreement_signature", "(", "self", ",", "did", ",", "agreement_id", ",", "service_definition_id", ",", "consumer_address", ",", "signature", ",", "ddo", "=", "None", ")", ":", "if", "not", "ddo", ":", "ddo", "=", "self", ".", "_asset_resolver", ".", "resolve", "(", "did", ")", "service_agreement", "=", "ServiceAgreement", ".", "from_ddo", "(", "service_definition_id", ",", "ddo", ")", "agreement_hash", "=", "service_agreement", ".", "get_service_agreement_hash", "(", "agreement_id", ",", "ddo", ".", "asset_id", ",", "consumer_address", ",", "Web3Provider", ".", "get_web3", "(", ")", ".", "toChecksumAddress", "(", "ddo", ".", "proof", "[", "'creator'", "]", ")", ",", "self", ".", "_keeper", ")", "prefixed_hash", "=", "prepare_prefixed_hash", "(", "agreement_hash", ")", "recovered_address", "=", "Web3Provider", ".", "get_web3", "(", ")", ".", "eth", ".", "account", ".", "recoverHash", "(", "prefixed_hash", ",", "signature", "=", "signature", ")", "is_valid", "=", "(", "recovered_address", "==", "consumer_address", ")", "if", "not", "is_valid", ":", "logger", ".", "warning", "(", "f'Agreement signature failed: agreement hash is {agreement_hash.hex()}'", ")", "return", "is_valid" ]
Verify service agreement signature. Verify that the given signature is truly signed by the `consumer_address` and represents this did's service agreement.. :param did: DID, str :param agreement_id: id of the agreement, hex str :param service_definition_id: identifier of the service inside the asset DDO, str :param consumer_address: ethereum account address of consumer, hex str :param signature: Signature, str :param ddo: DDO instance :return: True if signature is legitimate, False otherwise :raises: ValueError if service is not found in the ddo :raises: AssertionError if conditions keys do not match the on-chain conditions keys
[ "Verify", "service", "agreement", "signature", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_agreements.py#L298-L332
2,555
oceanprotocol/squid-py
squid_py/ocean/ocean_agreements.py
OceanAgreements.status
def status(self, agreement_id): """ Get the status of a service agreement. :param agreement_id: id of the agreement, hex str :return: dict with condition status of each of the agreement's conditions or None if the agreement is invalid. """ condition_ids = self._keeper.agreement_manager.get_agreement(agreement_id).condition_ids result = {"agreementId": agreement_id} conditions = dict() for i in condition_ids: conditions[self._keeper.get_condition_name_by_address( self._keeper.condition_manager.get_condition( i).type_ref)] = self._keeper.condition_manager.get_condition_state(i) result["conditions"] = conditions return result
python
def status(self, agreement_id): """ Get the status of a service agreement. :param agreement_id: id of the agreement, hex str :return: dict with condition status of each of the agreement's conditions or None if the agreement is invalid. """ condition_ids = self._keeper.agreement_manager.get_agreement(agreement_id).condition_ids result = {"agreementId": agreement_id} conditions = dict() for i in condition_ids: conditions[self._keeper.get_condition_name_by_address( self._keeper.condition_manager.get_condition( i).type_ref)] = self._keeper.condition_manager.get_condition_state(i) result["conditions"] = conditions return result
[ "def", "status", "(", "self", ",", "agreement_id", ")", ":", "condition_ids", "=", "self", ".", "_keeper", ".", "agreement_manager", ".", "get_agreement", "(", "agreement_id", ")", ".", "condition_ids", "result", "=", "{", "\"agreementId\"", ":", "agreement_id", "}", "conditions", "=", "dict", "(", ")", "for", "i", "in", "condition_ids", ":", "conditions", "[", "self", ".", "_keeper", ".", "get_condition_name_by_address", "(", "self", ".", "_keeper", ".", "condition_manager", ".", "get_condition", "(", "i", ")", ".", "type_ref", ")", "]", "=", "self", ".", "_keeper", ".", "condition_manager", ".", "get_condition_state", "(", "i", ")", "result", "[", "\"conditions\"", "]", "=", "conditions", "return", "result" ]
Get the status of a service agreement. :param agreement_id: id of the agreement, hex str :return: dict with condition status of each of the agreement's conditions or None if the agreement is invalid.
[ "Get", "the", "status", "of", "a", "service", "agreement", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_agreements.py#L343-L359
2,556
oceanprotocol/squid-py
squid_py/keeper/templates/access_secret_store_template.py
EscrowAccessSecretStoreTemplate.create_agreement
def create_agreement(self, agreement_id, did, condition_ids, time_locks, time_outs, consumer_address, account): """ Create the service agreement. Return true if it is created successfully. :param agreement_id: id of the agreement, hex str :param did: DID, str :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 :param time_locks: is a list of uint time lock values associated to each Condition, int :param time_outs: is a list of uint time out values associated to each Condition, int :param consumer_address: ethereum account address of consumer, hex str :param account: Account instance creating the agreement :return: bool """ logger.info( f'Creating agreement {agreement_id} with did={did}, consumer={consumer_address}.') tx_hash = self.send_transaction( 'createAgreement', (agreement_id, did, condition_ids, time_locks, time_outs, consumer_address), transact={'from': account.address, 'passphrase': account.password} ) receipt = self.get_tx_receipt(tx_hash) return receipt and receipt.status == 1
python
def create_agreement(self, agreement_id, did, condition_ids, time_locks, time_outs, consumer_address, account): """ Create the service agreement. Return true if it is created successfully. :param agreement_id: id of the agreement, hex str :param did: DID, str :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 :param time_locks: is a list of uint time lock values associated to each Condition, int :param time_outs: is a list of uint time out values associated to each Condition, int :param consumer_address: ethereum account address of consumer, hex str :param account: Account instance creating the agreement :return: bool """ logger.info( f'Creating agreement {agreement_id} with did={did}, consumer={consumer_address}.') tx_hash = self.send_transaction( 'createAgreement', (agreement_id, did, condition_ids, time_locks, time_outs, consumer_address), transact={'from': account.address, 'passphrase': account.password} ) receipt = self.get_tx_receipt(tx_hash) return receipt and receipt.status == 1
[ "def", "create_agreement", "(", "self", ",", "agreement_id", ",", "did", ",", "condition_ids", ",", "time_locks", ",", "time_outs", ",", "consumer_address", ",", "account", ")", ":", "logger", ".", "info", "(", "f'Creating agreement {agreement_id} with did={did}, consumer={consumer_address}.'", ")", "tx_hash", "=", "self", ".", "send_transaction", "(", "'createAgreement'", ",", "(", "agreement_id", ",", "did", ",", "condition_ids", ",", "time_locks", ",", "time_outs", ",", "consumer_address", ")", ",", "transact", "=", "{", "'from'", ":", "account", ".", "address", ",", "'passphrase'", ":", "account", ".", "password", "}", ")", "receipt", "=", "self", ".", "get_tx_receipt", "(", "tx_hash", ")", "return", "receipt", "and", "receipt", ".", "status", "==", "1" ]
Create the service agreement. Return true if it is created successfully. :param agreement_id: id of the agreement, hex str :param did: DID, str :param condition_ids: is a list of bytes32 content-addressed Condition IDs, bytes32 :param time_locks: is a list of uint time lock values associated to each Condition, int :param time_outs: is a list of uint time out values associated to each Condition, int :param consumer_address: ethereum account address of consumer, hex str :param account: Account instance creating the agreement :return: bool
[ "Create", "the", "service", "agreement", ".", "Return", "true", "if", "it", "is", "created", "successfully", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/templates/access_secret_store_template.py#L17-L45
2,557
oceanprotocol/squid-py
squid_py/keeper/templates/access_secret_store_template.py
EscrowAccessSecretStoreTemplate.subscribe_agreement_created
def subscribe_agreement_created(self, agreement_id, timeout, callback, args, wait=False): """ Subscribe to an agreement created. :param agreement_id: id of the agreement, hex str :param timeout: :param callback: :param args: :param wait: if true block the listener until get the event, bool :return: """ logger.info( f'Subscribing {self.AGREEMENT_CREATED_EVENT} event with agreement id {agreement_id}.') return self.subscribe_to_event( self.AGREEMENT_CREATED_EVENT, timeout, {'_agreementId': Web3Provider.get_web3().toBytes(hexstr=agreement_id)}, callback=callback, args=args, wait=wait )
python
def subscribe_agreement_created(self, agreement_id, timeout, callback, args, wait=False): """ Subscribe to an agreement created. :param agreement_id: id of the agreement, hex str :param timeout: :param callback: :param args: :param wait: if true block the listener until get the event, bool :return: """ logger.info( f'Subscribing {self.AGREEMENT_CREATED_EVENT} event with agreement id {agreement_id}.') return self.subscribe_to_event( self.AGREEMENT_CREATED_EVENT, timeout, {'_agreementId': Web3Provider.get_web3().toBytes(hexstr=agreement_id)}, callback=callback, args=args, wait=wait )
[ "def", "subscribe_agreement_created", "(", "self", ",", "agreement_id", ",", "timeout", ",", "callback", ",", "args", ",", "wait", "=", "False", ")", ":", "logger", ".", "info", "(", "f'Subscribing {self.AGREEMENT_CREATED_EVENT} event with agreement id {agreement_id}.'", ")", "return", "self", ".", "subscribe_to_event", "(", "self", ".", "AGREEMENT_CREATED_EVENT", ",", "timeout", ",", "{", "'_agreementId'", ":", "Web3Provider", ".", "get_web3", "(", ")", ".", "toBytes", "(", "hexstr", "=", "agreement_id", ")", "}", ",", "callback", "=", "callback", ",", "args", "=", "args", ",", "wait", "=", "wait", ")" ]
Subscribe to an agreement created. :param agreement_id: id of the agreement, hex str :param timeout: :param callback: :param args: :param wait: if true block the listener until get the event, bool :return:
[ "Subscribe", "to", "an", "agreement", "created", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/templates/access_secret_store_template.py#L72-L92
2,558
oceanprotocol/squid-py
squid_py/keeper/conditions/condition_base.py
ConditionBase.generate_id
def generate_id(self, agreement_id, types, values): """ Generate id for the condition. :param agreement_id: id of the agreement, hex str :param types: list of types :param values: list of values :return: id, str """ values_hash = utils.generate_multi_value_hash(types, values) return utils.generate_multi_value_hash( ['bytes32', 'address', 'bytes32'], [agreement_id, self.address, values_hash] )
python
def generate_id(self, agreement_id, types, values): """ Generate id for the condition. :param agreement_id: id of the agreement, hex str :param types: list of types :param values: list of values :return: id, str """ values_hash = utils.generate_multi_value_hash(types, values) return utils.generate_multi_value_hash( ['bytes32', 'address', 'bytes32'], [agreement_id, self.address, values_hash] )
[ "def", "generate_id", "(", "self", ",", "agreement_id", ",", "types", ",", "values", ")", ":", "values_hash", "=", "utils", ".", "generate_multi_value_hash", "(", "types", ",", "values", ")", "return", "utils", ".", "generate_multi_value_hash", "(", "[", "'bytes32'", ",", "'address'", ",", "'bytes32'", "]", ",", "[", "agreement_id", ",", "self", ".", "address", ",", "values_hash", "]", ")" ]
Generate id for the condition. :param agreement_id: id of the agreement, hex str :param types: list of types :param values: list of values :return: id, str
[ "Generate", "id", "for", "the", "condition", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/condition_base.py#L16-L29
2,559
oceanprotocol/squid-py
squid_py/keeper/conditions/condition_base.py
ConditionBase._fulfill
def _fulfill(self, *args, **kwargs): """ Fulfill the condition. :param args: :param kwargs: :return: true if the condition was successfully fulfilled, bool """ tx_hash = self.send_transaction('fulfill', args, **kwargs) receipt = self.get_tx_receipt(tx_hash) return receipt.status == 1
python
def _fulfill(self, *args, **kwargs): """ Fulfill the condition. :param args: :param kwargs: :return: true if the condition was successfully fulfilled, bool """ tx_hash = self.send_transaction('fulfill', args, **kwargs) receipt = self.get_tx_receipt(tx_hash) return receipt.status == 1
[ "def", "_fulfill", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "tx_hash", "=", "self", ".", "send_transaction", "(", "'fulfill'", ",", "args", ",", "*", "*", "kwargs", ")", "receipt", "=", "self", ".", "get_tx_receipt", "(", "tx_hash", ")", "return", "receipt", ".", "status", "==", "1" ]
Fulfill the condition. :param args: :param kwargs: :return: true if the condition was successfully fulfilled, bool
[ "Fulfill", "the", "condition", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/condition_base.py#L31-L41
2,560
oceanprotocol/squid-py
squid_py/keeper/conditions/condition_base.py
ConditionBase.subscribe_condition_fulfilled
def subscribe_condition_fulfilled(self, agreement_id, timeout, callback, args, timeout_callback=None, wait=False): """ Subscribe to the condition fullfilled event. :param agreement_id: id of the agreement, hex str :param timeout: :param callback: :param args: :param timeout_callback: :param wait: if true block the listener until get the event, bool :return: """ logger.info( f'Subscribing {self.FULFILLED_EVENT} event with agreement id {agreement_id}.') return self.subscribe_to_event( self.FULFILLED_EVENT, timeout, {'_agreementId': Web3Provider.get_web3().toBytes(hexstr=agreement_id)}, callback=callback, timeout_callback=timeout_callback, args=args, wait=wait )
python
def subscribe_condition_fulfilled(self, agreement_id, timeout, callback, args, timeout_callback=None, wait=False): """ Subscribe to the condition fullfilled event. :param agreement_id: id of the agreement, hex str :param timeout: :param callback: :param args: :param timeout_callback: :param wait: if true block the listener until get the event, bool :return: """ logger.info( f'Subscribing {self.FULFILLED_EVENT} event with agreement id {agreement_id}.') return self.subscribe_to_event( self.FULFILLED_EVENT, timeout, {'_agreementId': Web3Provider.get_web3().toBytes(hexstr=agreement_id)}, callback=callback, timeout_callback=timeout_callback, args=args, wait=wait )
[ "def", "subscribe_condition_fulfilled", "(", "self", ",", "agreement_id", ",", "timeout", ",", "callback", ",", "args", ",", "timeout_callback", "=", "None", ",", "wait", "=", "False", ")", ":", "logger", ".", "info", "(", "f'Subscribing {self.FULFILLED_EVENT} event with agreement id {agreement_id}.'", ")", "return", "self", ".", "subscribe_to_event", "(", "self", ".", "FULFILLED_EVENT", ",", "timeout", ",", "{", "'_agreementId'", ":", "Web3Provider", ".", "get_web3", "(", ")", ".", "toBytes", "(", "hexstr", "=", "agreement_id", ")", "}", ",", "callback", "=", "callback", ",", "timeout_callback", "=", "timeout_callback", ",", "args", "=", "args", ",", "wait", "=", "wait", ")" ]
Subscribe to the condition fullfilled event. :param agreement_id: id of the agreement, hex str :param timeout: :param callback: :param args: :param timeout_callback: :param wait: if true block the listener until get the event, bool :return:
[ "Subscribe", "to", "the", "condition", "fullfilled", "event", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/condition_base.py#L62-L85
2,561
oceanprotocol/squid-py
squid_py/keeper/web3/contract.py
transact_with_contract_function
def transact_with_contract_function( address, web3, function_name=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """ Helper function for interacting with a contract function by sending a transaction. This is copied from web3 `transact_with_contract_function` so we can use `personal_sendTransaction` when possible. """ transact_transaction = prepare_transaction( address, web3, fn_identifier=function_name, contract_abi=contract_abi, transaction=transaction, fn_abi=fn_abi, fn_args=args, fn_kwargs=kwargs, ) passphrase = None if transaction and 'passphrase' in transaction: passphrase = transaction['passphrase'] transact_transaction.pop('passphrase') if passphrase: txn_hash = web3.personal.sendTransaction(transact_transaction, passphrase) else: txn_hash = web3.eth.sendTransaction(transact_transaction) return txn_hash
python
def transact_with_contract_function( address, web3, function_name=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """ Helper function for interacting with a contract function by sending a transaction. This is copied from web3 `transact_with_contract_function` so we can use `personal_sendTransaction` when possible. """ transact_transaction = prepare_transaction( address, web3, fn_identifier=function_name, contract_abi=contract_abi, transaction=transaction, fn_abi=fn_abi, fn_args=args, fn_kwargs=kwargs, ) passphrase = None if transaction and 'passphrase' in transaction: passphrase = transaction['passphrase'] transact_transaction.pop('passphrase') if passphrase: txn_hash = web3.personal.sendTransaction(transact_transaction, passphrase) else: txn_hash = web3.eth.sendTransaction(transact_transaction) return txn_hash
[ "def", "transact_with_contract_function", "(", "address", ",", "web3", ",", "function_name", "=", "None", ",", "transaction", "=", "None", ",", "contract_abi", "=", "None", ",", "fn_abi", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "transact_transaction", "=", "prepare_transaction", "(", "address", ",", "web3", ",", "fn_identifier", "=", "function_name", ",", "contract_abi", "=", "contract_abi", ",", "transaction", "=", "transaction", ",", "fn_abi", "=", "fn_abi", ",", "fn_args", "=", "args", ",", "fn_kwargs", "=", "kwargs", ",", ")", "passphrase", "=", "None", "if", "transaction", "and", "'passphrase'", "in", "transaction", ":", "passphrase", "=", "transaction", "[", "'passphrase'", "]", "transact_transaction", ".", "pop", "(", "'passphrase'", ")", "if", "passphrase", ":", "txn_hash", "=", "web3", ".", "personal", ".", "sendTransaction", "(", "transact_transaction", ",", "passphrase", ")", "else", ":", "txn_hash", "=", "web3", ".", "eth", ".", "sendTransaction", "(", "transact_transaction", ")", "return", "txn_hash" ]
Helper function for interacting with a contract function by sending a transaction. This is copied from web3 `transact_with_contract_function` so we can use `personal_sendTransaction` when possible.
[ "Helper", "function", "for", "interacting", "with", "a", "contract", "function", "by", "sending", "a", "transaction", ".", "This", "is", "copied", "from", "web3", "transact_with_contract_function", "so", "we", "can", "use", "personal_sendTransaction", "when", "possible", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/web3/contract.py#L67-L102
2,562
oceanprotocol/squid-py
squid_py/keeper/web3/contract.py
SquidContractFunction.transact
def transact(self, transaction=None): """ Customize calling smart contract transaction functions to use `personal_sendTransaction` instead of `eth_sendTransaction` and to estimate gas limit. This function is largely copied from web3 ContractFunction with important addition. Note: will fallback to `eth_sendTransaction` if `passphrase` is not provided in the `transaction` dict. :param transaction: dict which has the required transaction arguments per `personal_sendTransaction` requirements. :return: hex str transaction hash """ if transaction is None: transact_transaction = {} else: transact_transaction = dict(**transaction) if 'data' in transact_transaction: raise ValueError("Cannot set data in transact transaction") cf = self._contract_function if cf.address is not None: transact_transaction.setdefault('to', cf.address) if cf.web3.eth.defaultAccount is not empty: transact_transaction.setdefault('from', cf.web3.eth.defaultAccount) if 'to' not in transact_transaction: if isinstance(self, type): raise ValueError( "When using `Contract.transact` from a contract factory you " "must provide a `to` address with the transaction" ) else: raise ValueError( "Please ensure that this contract instance has an address." ) if 'gas' not in transact_transaction: tx = transaction.copy() if 'passphrase' in tx: tx.pop('passphrase') gas = cf.estimateGas(tx) transact_transaction['gas'] = gas return transact_with_contract_function( cf.address, cf.web3, cf.function_identifier, transact_transaction, cf.contract_abi, cf.abi, *cf.args, **cf.kwargs )
python
def transact(self, transaction=None): """ Customize calling smart contract transaction functions to use `personal_sendTransaction` instead of `eth_sendTransaction` and to estimate gas limit. This function is largely copied from web3 ContractFunction with important addition. Note: will fallback to `eth_sendTransaction` if `passphrase` is not provided in the `transaction` dict. :param transaction: dict which has the required transaction arguments per `personal_sendTransaction` requirements. :return: hex str transaction hash """ if transaction is None: transact_transaction = {} else: transact_transaction = dict(**transaction) if 'data' in transact_transaction: raise ValueError("Cannot set data in transact transaction") cf = self._contract_function if cf.address is not None: transact_transaction.setdefault('to', cf.address) if cf.web3.eth.defaultAccount is not empty: transact_transaction.setdefault('from', cf.web3.eth.defaultAccount) if 'to' not in transact_transaction: if isinstance(self, type): raise ValueError( "When using `Contract.transact` from a contract factory you " "must provide a `to` address with the transaction" ) else: raise ValueError( "Please ensure that this contract instance has an address." ) if 'gas' not in transact_transaction: tx = transaction.copy() if 'passphrase' in tx: tx.pop('passphrase') gas = cf.estimateGas(tx) transact_transaction['gas'] = gas return transact_with_contract_function( cf.address, cf.web3, cf.function_identifier, transact_transaction, cf.contract_abi, cf.abi, *cf.args, **cf.kwargs )
[ "def", "transact", "(", "self", ",", "transaction", "=", "None", ")", ":", "if", "transaction", "is", "None", ":", "transact_transaction", "=", "{", "}", "else", ":", "transact_transaction", "=", "dict", "(", "*", "*", "transaction", ")", "if", "'data'", "in", "transact_transaction", ":", "raise", "ValueError", "(", "\"Cannot set data in transact transaction\"", ")", "cf", "=", "self", ".", "_contract_function", "if", "cf", ".", "address", "is", "not", "None", ":", "transact_transaction", ".", "setdefault", "(", "'to'", ",", "cf", ".", "address", ")", "if", "cf", ".", "web3", ".", "eth", ".", "defaultAccount", "is", "not", "empty", ":", "transact_transaction", ".", "setdefault", "(", "'from'", ",", "cf", ".", "web3", ".", "eth", ".", "defaultAccount", ")", "if", "'to'", "not", "in", "transact_transaction", ":", "if", "isinstance", "(", "self", ",", "type", ")", ":", "raise", "ValueError", "(", "\"When using `Contract.transact` from a contract factory you \"", "\"must provide a `to` address with the transaction\"", ")", "else", ":", "raise", "ValueError", "(", "\"Please ensure that this contract instance has an address.\"", ")", "if", "'gas'", "not", "in", "transact_transaction", ":", "tx", "=", "transaction", ".", "copy", "(", ")", "if", "'passphrase'", "in", "tx", ":", "tx", ".", "pop", "(", "'passphrase'", ")", "gas", "=", "cf", ".", "estimateGas", "(", "tx", ")", "transact_transaction", "[", "'gas'", "]", "=", "gas", "return", "transact_with_contract_function", "(", "cf", ".", "address", ",", "cf", ".", "web3", ",", "cf", ".", "function_identifier", ",", "transact_transaction", ",", "cf", ".", "contract_abi", ",", "cf", ".", "abi", ",", "*", "cf", ".", "args", ",", "*", "*", "cf", ".", "kwargs", ")" ]
Customize calling smart contract transaction functions to use `personal_sendTransaction` instead of `eth_sendTransaction` and to estimate gas limit. This function is largely copied from web3 ContractFunction with important addition. Note: will fallback to `eth_sendTransaction` if `passphrase` is not provided in the `transaction` dict. :param transaction: dict which has the required transaction arguments per `personal_sendTransaction` requirements. :return: hex str transaction hash
[ "Customize", "calling", "smart", "contract", "transaction", "functions", "to", "use", "personal_sendTransaction", "instead", "of", "eth_sendTransaction", "and", "to", "estimate", "gas", "limit", ".", "This", "function", "is", "largely", "copied", "from", "web3", "ContractFunction", "with", "important", "addition", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/web3/contract.py#L10-L64
2,563
oceanprotocol/squid-py
squid_py/keeper/conditions/escrow_reward.py
EscrowRewardCondition.fulfill
def fulfill(self, agreement_id, amount, receiver_address, sender_address, lock_condition_id, release_condition_id, account): """ Fulfill the escrow reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param receiver_address: ethereum address of the receiver, hex str :param sender_address: ethereum address of the sender, hex str :param lock_condition_id: id of the condition, str :param release_condition_id: id of the condition, str :param account: Account instance :return: """ return self._fulfill( agreement_id, amount, receiver_address, sender_address, lock_condition_id, release_condition_id, transact={'from': account.address, 'passphrase': account.password} )
python
def fulfill(self, agreement_id, amount, receiver_address, sender_address, lock_condition_id, release_condition_id, account): """ Fulfill the escrow reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param receiver_address: ethereum address of the receiver, hex str :param sender_address: ethereum address of the sender, hex str :param lock_condition_id: id of the condition, str :param release_condition_id: id of the condition, str :param account: Account instance :return: """ return self._fulfill( agreement_id, amount, receiver_address, sender_address, lock_condition_id, release_condition_id, transact={'from': account.address, 'passphrase': account.password} )
[ "def", "fulfill", "(", "self", ",", "agreement_id", ",", "amount", ",", "receiver_address", ",", "sender_address", ",", "lock_condition_id", ",", "release_condition_id", ",", "account", ")", ":", "return", "self", ".", "_fulfill", "(", "agreement_id", ",", "amount", ",", "receiver_address", ",", "sender_address", ",", "lock_condition_id", ",", "release_condition_id", ",", "transact", "=", "{", "'from'", ":", "account", ".", "address", ",", "'passphrase'", ":", "account", ".", "password", "}", ")" ]
Fulfill the escrow reward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param receiver_address: ethereum address of the receiver, hex str :param sender_address: ethereum address of the sender, hex str :param lock_condition_id: id of the condition, str :param release_condition_id: id of the condition, str :param account: Account instance :return:
[ "Fulfill", "the", "escrow", "reward", "condition", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/escrow_reward.py#L11-L40
2,564
oceanprotocol/squid-py
squid_py/keeper/conditions/escrow_reward.py
EscrowRewardCondition.hash_values
def hash_values(self, amount, receiver_address, sender_address, lock_condition_id, release_condition_id): """ Hash the values of the escrow reward condition. :param amount: Amount of tokens, int :param receiver_address: ethereum address of the receiver, hex str :param sender_address: ethereum address of the sender, hex str :param lock_condition_id: id of the condition, str :param release_condition_id: id of the condition, str :return: hex str """ return self._hash_values( amount, receiver_address, sender_address, lock_condition_id, release_condition_id )
python
def hash_values(self, amount, receiver_address, sender_address, lock_condition_id, release_condition_id): """ Hash the values of the escrow reward condition. :param amount: Amount of tokens, int :param receiver_address: ethereum address of the receiver, hex str :param sender_address: ethereum address of the sender, hex str :param lock_condition_id: id of the condition, str :param release_condition_id: id of the condition, str :return: hex str """ return self._hash_values( amount, receiver_address, sender_address, lock_condition_id, release_condition_id )
[ "def", "hash_values", "(", "self", ",", "amount", ",", "receiver_address", ",", "sender_address", ",", "lock_condition_id", ",", "release_condition_id", ")", ":", "return", "self", ".", "_hash_values", "(", "amount", ",", "receiver_address", ",", "sender_address", ",", "lock_condition_id", ",", "release_condition_id", ")" ]
Hash the values of the escrow reward condition. :param amount: Amount of tokens, int :param receiver_address: ethereum address of the receiver, hex str :param sender_address: ethereum address of the sender, hex str :param lock_condition_id: id of the condition, str :param release_condition_id: id of the condition, str :return: hex str
[ "Hash", "the", "values", "of", "the", "escrow", "reward", "condition", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/escrow_reward.py#L42-L60
2,565
oceanprotocol/squid-py
squid_py/agreements/service_agreement_condition.py
Parameter.as_dictionary
def as_dictionary(self): """ Return the parameter as a dictionary. :return: dict """ return { "name": self.name, "type": self.type, "value": remove_0x_prefix(self.value) if self.type == 'bytes32' else self.value }
python
def as_dictionary(self): """ Return the parameter as a dictionary. :return: dict """ return { "name": self.name, "type": self.type, "value": remove_0x_prefix(self.value) if self.type == 'bytes32' else self.value }
[ "def", "as_dictionary", "(", "self", ")", ":", "return", "{", "\"name\"", ":", "self", ".", "name", ",", "\"type\"", ":", "self", ".", "type", ",", "\"value\"", ":", "remove_0x_prefix", "(", "self", ".", "value", ")", "if", "self", ".", "type", "==", "'bytes32'", "else", "self", ".", "value", "}" ]
Return the parameter as a dictionary. :return: dict
[ "Return", "the", "parameter", "as", "a", "dictionary", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement_condition.py#L21-L31
2,566
oceanprotocol/squid-py
squid_py/agreements/service_agreement_condition.py
ServiceAgreementCondition.init_from_condition_json
def init_from_condition_json(self, condition_json): """ Init the condition values from a condition json. :param condition_json: dict """ self.name = condition_json['name'] self.timelock = condition_json['timelock'] self.timeout = condition_json['timeout'] self.contract_name = condition_json['contractName'] self.function_name = condition_json['functionName'] self.parameters = [Parameter(p) for p in condition_json['parameters']] self.events = [Event(e) for e in condition_json['events']]
python
def init_from_condition_json(self, condition_json): """ Init the condition values from a condition json. :param condition_json: dict """ self.name = condition_json['name'] self.timelock = condition_json['timelock'] self.timeout = condition_json['timeout'] self.contract_name = condition_json['contractName'] self.function_name = condition_json['functionName'] self.parameters = [Parameter(p) for p in condition_json['parameters']] self.events = [Event(e) for e in condition_json['events']]
[ "def", "init_from_condition_json", "(", "self", ",", "condition_json", ")", ":", "self", ".", "name", "=", "condition_json", "[", "'name'", "]", "self", ".", "timelock", "=", "condition_json", "[", "'timelock'", "]", "self", ".", "timeout", "=", "condition_json", "[", "'timeout'", "]", "self", ".", "contract_name", "=", "condition_json", "[", "'contractName'", "]", "self", ".", "function_name", "=", "condition_json", "[", "'functionName'", "]", "self", ".", "parameters", "=", "[", "Parameter", "(", "p", ")", "for", "p", "in", "condition_json", "[", "'parameters'", "]", "]", "self", ".", "events", "=", "[", "Event", "(", "e", ")", "for", "e", "in", "condition_json", "[", "'events'", "]", "]" ]
Init the condition values from a condition json. :param condition_json: dict
[ "Init", "the", "condition", "values", "from", "a", "condition", "json", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement_condition.py#L93-L105
2,567
oceanprotocol/squid-py
squid_py/agreements/service_agreement_condition.py
ServiceAgreementCondition.as_dictionary
def as_dictionary(self): """ Return the condition as a dictionary. :return: dict """ condition_dict = { "name": self.name, "timelock": self.timelock, "timeout": self.timeout, "contractName": self.contract_name, "functionName": self.function_name, "events": [e.as_dictionary() for e in self.events], "parameters": [p.as_dictionary() for p in self.parameters], } return condition_dict
python
def as_dictionary(self): """ Return the condition as a dictionary. :return: dict """ condition_dict = { "name": self.name, "timelock": self.timelock, "timeout": self.timeout, "contractName": self.contract_name, "functionName": self.function_name, "events": [e.as_dictionary() for e in self.events], "parameters": [p.as_dictionary() for p in self.parameters], } return condition_dict
[ "def", "as_dictionary", "(", "self", ")", ":", "condition_dict", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"timelock\"", ":", "self", ".", "timelock", ",", "\"timeout\"", ":", "self", ".", "timeout", ",", "\"contractName\"", ":", "self", ".", "contract_name", ",", "\"functionName\"", ":", "self", ".", "function_name", ",", "\"events\"", ":", "[", "e", ".", "as_dictionary", "(", ")", "for", "e", "in", "self", ".", "events", "]", ",", "\"parameters\"", ":", "[", "p", ".", "as_dictionary", "(", ")", "for", "p", "in", "self", ".", "parameters", "]", ",", "}", "return", "condition_dict" ]
Return the condition as a dictionary. :return: dict
[ "Return", "the", "condition", "as", "a", "dictionary", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement_condition.py#L107-L123
2,568
oceanprotocol/squid-py
squid_py/ddo/service.py
Service.update_value
def update_value(self, name, value): """ Update value in the array of values. :param name: Key of the value, str :param value: New value, str :return: None """ if name not in {'id', self.SERVICE_ENDPOINT, self.CONSUME_ENDPOINT, 'type'}: self._values[name] = value
python
def update_value(self, name, value): """ Update value in the array of values. :param name: Key of the value, str :param value: New value, str :return: None """ if name not in {'id', self.SERVICE_ENDPOINT, self.CONSUME_ENDPOINT, 'type'}: self._values[name] = value
[ "def", "update_value", "(", "self", ",", "name", ",", "value", ")", ":", "if", "name", "not", "in", "{", "'id'", ",", "self", ".", "SERVICE_ENDPOINT", ",", "self", ".", "CONSUME_ENDPOINT", ",", "'type'", "}", ":", "self", ".", "_values", "[", "name", "]", "=", "value" ]
Update value in the array of values. :param name: Key of the value, str :param value: New value, str :return: None
[ "Update", "value", "in", "the", "array", "of", "values", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/service.py#L92-L101
2,569
oceanprotocol/squid-py
squid_py/ddo/service.py
Service.as_text
def as_text(self, is_pretty=False): """Return the service as a JSON string.""" values = { 'type': self._type, self.SERVICE_ENDPOINT: self._service_endpoint, } if self._consume_endpoint is not None: values[self.CONSUME_ENDPOINT] = self._consume_endpoint if self._values: # add extra service values to the dictionary for name, value in self._values.items(): values[name] = value if is_pretty: return json.dumps(values, indent=4, separators=(',', ': ')) return json.dumps(values)
python
def as_text(self, is_pretty=False): """Return the service as a JSON string.""" values = { 'type': self._type, self.SERVICE_ENDPOINT: self._service_endpoint, } if self._consume_endpoint is not None: values[self.CONSUME_ENDPOINT] = self._consume_endpoint if self._values: # add extra service values to the dictionary for name, value in self._values.items(): values[name] = value if is_pretty: return json.dumps(values, indent=4, separators=(',', ': ')) return json.dumps(values)
[ "def", "as_text", "(", "self", ",", "is_pretty", "=", "False", ")", ":", "values", "=", "{", "'type'", ":", "self", ".", "_type", ",", "self", ".", "SERVICE_ENDPOINT", ":", "self", ".", "_service_endpoint", ",", "}", "if", "self", ".", "_consume_endpoint", "is", "not", "None", ":", "values", "[", "self", ".", "CONSUME_ENDPOINT", "]", "=", "self", ".", "_consume_endpoint", "if", "self", ".", "_values", ":", "# add extra service values to the dictionary", "for", "name", ",", "value", "in", "self", ".", "_values", ".", "items", "(", ")", ":", "values", "[", "name", "]", "=", "value", "if", "is_pretty", ":", "return", "json", ".", "dumps", "(", "values", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", "return", "json", ".", "dumps", "(", "values", ")" ]
Return the service as a JSON string.
[ "Return", "the", "service", "as", "a", "JSON", "string", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/service.py#L116-L132
2,570
oceanprotocol/squid-py
squid_py/ddo/service.py
Service.as_dictionary
def as_dictionary(self): """Return the service as a python dictionary.""" values = { 'type': self._type, self.SERVICE_ENDPOINT: self._service_endpoint, } if self._consume_endpoint is not None: values[self.CONSUME_ENDPOINT] = self._consume_endpoint if self._values: # add extra service values to the dictionary for name, value in self._values.items(): if isinstance(value, object) and hasattr(value, 'as_dictionary'): value = value.as_dictionary() elif isinstance(value, list): value = [v.as_dictionary() if hasattr(v, 'as_dictionary') else v for v in value] values[name] = value return values
python
def as_dictionary(self): """Return the service as a python dictionary.""" values = { 'type': self._type, self.SERVICE_ENDPOINT: self._service_endpoint, } if self._consume_endpoint is not None: values[self.CONSUME_ENDPOINT] = self._consume_endpoint if self._values: # add extra service values to the dictionary for name, value in self._values.items(): if isinstance(value, object) and hasattr(value, 'as_dictionary'): value = value.as_dictionary() elif isinstance(value, list): value = [v.as_dictionary() if hasattr(v, 'as_dictionary') else v for v in value] values[name] = value return values
[ "def", "as_dictionary", "(", "self", ")", ":", "values", "=", "{", "'type'", ":", "self", ".", "_type", ",", "self", ".", "SERVICE_ENDPOINT", ":", "self", ".", "_service_endpoint", ",", "}", "if", "self", ".", "_consume_endpoint", "is", "not", "None", ":", "values", "[", "self", ".", "CONSUME_ENDPOINT", "]", "=", "self", ".", "_consume_endpoint", "if", "self", ".", "_values", ":", "# add extra service values to the dictionary", "for", "name", ",", "value", "in", "self", ".", "_values", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "object", ")", "and", "hasattr", "(", "value", ",", "'as_dictionary'", ")", ":", "value", "=", "value", ".", "as_dictionary", "(", ")", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "v", ".", "as_dictionary", "(", ")", "if", "hasattr", "(", "v", ",", "'as_dictionary'", ")", "else", "v", "for", "v", "in", "value", "]", "values", "[", "name", "]", "=", "value", "return", "values" ]
Return the service as a python dictionary.
[ "Return", "the", "service", "as", "a", "python", "dictionary", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/service.py#L134-L151
2,571
oceanprotocol/squid-py
squid_py/ddo/service.py
Service.from_json
def from_json(cls, service_dict): """Create a service object from a JSON string.""" sd = service_dict.copy() service_endpoint = sd.get(cls.SERVICE_ENDPOINT) if not service_endpoint: logger.error( 'Service definition in DDO document is missing the "serviceEndpoint" key/value.') raise IndexError _type = sd.get('type') if not _type: logger.error('Service definition in DDO document is missing the "type" key/value.') raise IndexError sd.pop(cls.SERVICE_ENDPOINT) sd.pop('type') return cls( service_endpoint, _type, sd )
python
def from_json(cls, service_dict): """Create a service object from a JSON string.""" sd = service_dict.copy() service_endpoint = sd.get(cls.SERVICE_ENDPOINT) if not service_endpoint: logger.error( 'Service definition in DDO document is missing the "serviceEndpoint" key/value.') raise IndexError _type = sd.get('type') if not _type: logger.error('Service definition in DDO document is missing the "type" key/value.') raise IndexError sd.pop(cls.SERVICE_ENDPOINT) sd.pop('type') return cls( service_endpoint, _type, sd )
[ "def", "from_json", "(", "cls", ",", "service_dict", ")", ":", "sd", "=", "service_dict", ".", "copy", "(", ")", "service_endpoint", "=", "sd", ".", "get", "(", "cls", ".", "SERVICE_ENDPOINT", ")", "if", "not", "service_endpoint", ":", "logger", ".", "error", "(", "'Service definition in DDO document is missing the \"serviceEndpoint\" key/value.'", ")", "raise", "IndexError", "_type", "=", "sd", ".", "get", "(", "'type'", ")", "if", "not", "_type", ":", "logger", ".", "error", "(", "'Service definition in DDO document is missing the \"type\" key/value.'", ")", "raise", "IndexError", "sd", ".", "pop", "(", "cls", ".", "SERVICE_ENDPOINT", ")", "sd", ".", "pop", "(", "'type'", ")", "return", "cls", "(", "service_endpoint", ",", "_type", ",", "sd", ")" ]
Create a service object from a JSON string.
[ "Create", "a", "service", "object", "from", "a", "JSON", "string", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/service.py#L154-L174
2,572
oceanprotocol/squid-py
squid_py/keeper/conditions/access.py
AccessSecretStoreCondition.fulfill
def fulfill(self, agreement_id, document_id, grantee_address, account): """ Fulfill the access secret store condition. :param agreement_id: id of the agreement, hex str :param document_id: refers to the DID in which secret store will issue the decryption keys, DID :param grantee_address: is the address of the granted user, str :param account: Account instance :return: true if the condition was successfully fulfilled, bool """ return self._fulfill( agreement_id, document_id, grantee_address, transact={'from': account.address, 'passphrase': account.password} )
python
def fulfill(self, agreement_id, document_id, grantee_address, account): """ Fulfill the access secret store condition. :param agreement_id: id of the agreement, hex str :param document_id: refers to the DID in which secret store will issue the decryption keys, DID :param grantee_address: is the address of the granted user, str :param account: Account instance :return: true if the condition was successfully fulfilled, bool """ return self._fulfill( agreement_id, document_id, grantee_address, transact={'from': account.address, 'passphrase': account.password} )
[ "def", "fulfill", "(", "self", ",", "agreement_id", ",", "document_id", ",", "grantee_address", ",", "account", ")", ":", "return", "self", ".", "_fulfill", "(", "agreement_id", ",", "document_id", ",", "grantee_address", ",", "transact", "=", "{", "'from'", ":", "account", ".", "address", ",", "'passphrase'", ":", "account", ".", "password", "}", ")" ]
Fulfill the access secret store condition. :param agreement_id: id of the agreement, hex str :param document_id: refers to the DID in which secret store will issue the decryption keys, DID :param grantee_address: is the address of the granted user, str :param account: Account instance :return: true if the condition was successfully fulfilled, bool
[ "Fulfill", "the", "access", "secret", "store", "condition", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/access.py#L13-L30
2,573
oceanprotocol/squid-py
squid_py/keeper/conditions/access.py
AccessSecretStoreCondition.get_purchased_assets_by_address
def get_purchased_assets_by_address(self, address, from_block=0, to_block='latest'): """ Get the list of the assets dids consumed for an address. :param address: is the address of the granted user, hex-str :param from_block: block to start to listen :param to_block: block to stop to listen :return: list of dids """ block_filter = EventFilter( ConditionBase.FULFILLED_EVENT, getattr(self.events, ConditionBase.FULFILLED_EVENT), from_block=from_block, to_block=to_block, argument_filters={'_grantee': address} ) log_items = block_filter.get_all_entries(max_tries=5) did_list = [] for log_i in log_items: did_list.append(id_to_did(log_i.args['_documentId'])) return did_list
python
def get_purchased_assets_by_address(self, address, from_block=0, to_block='latest'): """ Get the list of the assets dids consumed for an address. :param address: is the address of the granted user, hex-str :param from_block: block to start to listen :param to_block: block to stop to listen :return: list of dids """ block_filter = EventFilter( ConditionBase.FULFILLED_EVENT, getattr(self.events, ConditionBase.FULFILLED_EVENT), from_block=from_block, to_block=to_block, argument_filters={'_grantee': address} ) log_items = block_filter.get_all_entries(max_tries=5) did_list = [] for log_i in log_items: did_list.append(id_to_did(log_i.args['_documentId'])) return did_list
[ "def", "get_purchased_assets_by_address", "(", "self", ",", "address", ",", "from_block", "=", "0", ",", "to_block", "=", "'latest'", ")", ":", "block_filter", "=", "EventFilter", "(", "ConditionBase", ".", "FULFILLED_EVENT", ",", "getattr", "(", "self", ".", "events", ",", "ConditionBase", ".", "FULFILLED_EVENT", ")", ",", "from_block", "=", "from_block", ",", "to_block", "=", "to_block", ",", "argument_filters", "=", "{", "'_grantee'", ":", "address", "}", ")", "log_items", "=", "block_filter", ".", "get_all_entries", "(", "max_tries", "=", "5", ")", "did_list", "=", "[", "]", "for", "log_i", "in", "log_items", ":", "did_list", ".", "append", "(", "id_to_did", "(", "log_i", ".", "args", "[", "'_documentId'", "]", ")", ")", "return", "did_list" ]
Get the list of the assets dids consumed for an address. :param address: is the address of the granted user, hex-str :param from_block: block to start to listen :param to_block: block to stop to listen :return: list of dids
[ "Get", "the", "list", "of", "the", "assets", "dids", "consumed", "for", "an", "address", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/conditions/access.py#L55-L76
2,574
oceanprotocol/squid-py
squid_py/keeper/web3_provider.py
Web3Provider.get_web3
def get_web3(): """Return the web3 instance to interact with the ethereum client.""" if Web3Provider._web3 is None: config = ConfigProvider.get_config() provider = ( config.web3_provider if config.web3_provider else CustomHTTPProvider( config.keeper_url ) ) Web3Provider._web3 = Web3(provider) # Reset attributes to avoid lint issue about no attribute Web3Provider._web3.eth = getattr(Web3Provider._web3, 'eth') Web3Provider._web3.net = getattr(Web3Provider._web3, 'net') Web3Provider._web3.personal = getattr(Web3Provider._web3, 'personal') Web3Provider._web3.version = getattr(Web3Provider._web3, 'version') Web3Provider._web3.txpool = getattr(Web3Provider._web3, 'txpool') Web3Provider._web3.miner = getattr(Web3Provider._web3, 'miner') Web3Provider._web3.admin = getattr(Web3Provider._web3, 'admin') Web3Provider._web3.parity = getattr(Web3Provider._web3, 'parity') Web3Provider._web3.testing = getattr(Web3Provider._web3, 'testing') return Web3Provider._web3
python
def get_web3(): """Return the web3 instance to interact with the ethereum client.""" if Web3Provider._web3 is None: config = ConfigProvider.get_config() provider = ( config.web3_provider if config.web3_provider else CustomHTTPProvider( config.keeper_url ) ) Web3Provider._web3 = Web3(provider) # Reset attributes to avoid lint issue about no attribute Web3Provider._web3.eth = getattr(Web3Provider._web3, 'eth') Web3Provider._web3.net = getattr(Web3Provider._web3, 'net') Web3Provider._web3.personal = getattr(Web3Provider._web3, 'personal') Web3Provider._web3.version = getattr(Web3Provider._web3, 'version') Web3Provider._web3.txpool = getattr(Web3Provider._web3, 'txpool') Web3Provider._web3.miner = getattr(Web3Provider._web3, 'miner') Web3Provider._web3.admin = getattr(Web3Provider._web3, 'admin') Web3Provider._web3.parity = getattr(Web3Provider._web3, 'parity') Web3Provider._web3.testing = getattr(Web3Provider._web3, 'testing') return Web3Provider._web3
[ "def", "get_web3", "(", ")", ":", "if", "Web3Provider", ".", "_web3", "is", "None", ":", "config", "=", "ConfigProvider", ".", "get_config", "(", ")", "provider", "=", "(", "config", ".", "web3_provider", "if", "config", ".", "web3_provider", "else", "CustomHTTPProvider", "(", "config", ".", "keeper_url", ")", ")", "Web3Provider", ".", "_web3", "=", "Web3", "(", "provider", ")", "# Reset attributes to avoid lint issue about no attribute", "Web3Provider", ".", "_web3", ".", "eth", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'eth'", ")", "Web3Provider", ".", "_web3", ".", "net", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'net'", ")", "Web3Provider", ".", "_web3", ".", "personal", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'personal'", ")", "Web3Provider", ".", "_web3", ".", "version", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'version'", ")", "Web3Provider", ".", "_web3", ".", "txpool", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'txpool'", ")", "Web3Provider", ".", "_web3", ".", "miner", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'miner'", ")", "Web3Provider", ".", "_web3", ".", "admin", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'admin'", ")", "Web3Provider", ".", "_web3", ".", "parity", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'parity'", ")", "Web3Provider", ".", "_web3", ".", "testing", "=", "getattr", "(", "Web3Provider", ".", "_web3", ",", "'testing'", ")", "return", "Web3Provider", ".", "_web3" ]
Return the web3 instance to interact with the ethereum client.
[ "Return", "the", "web3", "instance", "to", "interact", "with", "the", "ethereum", "client", "." ]
43a5b7431627e4c9ab7382ed9eb8153e96ed4483
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/web3_provider.py#L15-L38
2,575
BlueBrain/NeuroM
neurom/core/_soma.py
_get_type
def _get_type(points, soma_class): '''get the type of the soma Args: points: Soma points soma_class(str): one of 'contour' or 'cylinder' to specify the type ''' assert soma_class in (SOMA_CONTOUR, SOMA_CYLINDER) npoints = len(points) if soma_class == SOMA_CONTOUR: return {0: None, 1: SomaSinglePoint, 2: None}.get(npoints, SomaSimpleContour) if(npoints == 3 and points[0][COLS.P] == -1 and points[1][COLS.P] == 1 and points[2][COLS.P] == 1): L.warning('Using neuromorpho 3-Point soma') # NeuroMorpho is the main provider of morphologies, but they # with SWC as their default file format: they convert all # uploads to SWC. In the process of conversion, they turn all # somas into their custom 'Three-point soma representation': # http://neuromorpho.org/SomaFormat.html return SomaNeuromorphoThreePointCylinders return {0: None, 1: SomaSinglePoint}.get(npoints, SomaCylinders)
python
def _get_type(points, soma_class): '''get the type of the soma Args: points: Soma points soma_class(str): one of 'contour' or 'cylinder' to specify the type ''' assert soma_class in (SOMA_CONTOUR, SOMA_CYLINDER) npoints = len(points) if soma_class == SOMA_CONTOUR: return {0: None, 1: SomaSinglePoint, 2: None}.get(npoints, SomaSimpleContour) if(npoints == 3 and points[0][COLS.P] == -1 and points[1][COLS.P] == 1 and points[2][COLS.P] == 1): L.warning('Using neuromorpho 3-Point soma') # NeuroMorpho is the main provider of morphologies, but they # with SWC as their default file format: they convert all # uploads to SWC. In the process of conversion, they turn all # somas into their custom 'Three-point soma representation': # http://neuromorpho.org/SomaFormat.html return SomaNeuromorphoThreePointCylinders return {0: None, 1: SomaSinglePoint}.get(npoints, SomaCylinders)
[ "def", "_get_type", "(", "points", ",", "soma_class", ")", ":", "assert", "soma_class", "in", "(", "SOMA_CONTOUR", ",", "SOMA_CYLINDER", ")", "npoints", "=", "len", "(", "points", ")", "if", "soma_class", "==", "SOMA_CONTOUR", ":", "return", "{", "0", ":", "None", ",", "1", ":", "SomaSinglePoint", ",", "2", ":", "None", "}", ".", "get", "(", "npoints", ",", "SomaSimpleContour", ")", "if", "(", "npoints", "==", "3", "and", "points", "[", "0", "]", "[", "COLS", ".", "P", "]", "==", "-", "1", "and", "points", "[", "1", "]", "[", "COLS", ".", "P", "]", "==", "1", "and", "points", "[", "2", "]", "[", "COLS", ".", "P", "]", "==", "1", ")", ":", "L", ".", "warning", "(", "'Using neuromorpho 3-Point soma'", ")", "# NeuroMorpho is the main provider of morphologies, but they", "# with SWC as their default file format: they convert all", "# uploads to SWC. In the process of conversion, they turn all", "# somas into their custom 'Three-point soma representation':", "# http://neuromorpho.org/SomaFormat.html", "return", "SomaNeuromorphoThreePointCylinders", "return", "{", "0", ":", "None", ",", "1", ":", "SomaSinglePoint", "}", ".", "get", "(", "npoints", ",", "SomaCylinders", ")" ]
get the type of the soma Args: points: Soma points soma_class(str): one of 'contour' or 'cylinder' to specify the type
[ "get", "the", "type", "of", "the", "soma" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_soma.py#L203-L232
2,576
BlueBrain/NeuroM
neurom/core/_soma.py
make_soma
def make_soma(points, soma_check=None, soma_class=SOMA_CONTOUR): '''Make a soma object from a set of points Infers the soma type (SomaSinglePoint, SomaSimpleContour) from the points and the 'soma_class' Parameters: points: collection of points forming a soma. soma_check: optional validation function applied to points. Should raise a SomaError if points not valid. soma_class(str): one of 'contour' or 'cylinder' to specify the type Raises: SomaError if no soma points found, points incompatible with soma, or if soma_check(points) fails. ''' if soma_check: soma_check(points) stype = _get_type(points, soma_class) if stype is None: raise SomaError('Invalid soma points') return stype(points)
python
def make_soma(points, soma_check=None, soma_class=SOMA_CONTOUR): '''Make a soma object from a set of points Infers the soma type (SomaSinglePoint, SomaSimpleContour) from the points and the 'soma_class' Parameters: points: collection of points forming a soma. soma_check: optional validation function applied to points. Should raise a SomaError if points not valid. soma_class(str): one of 'contour' or 'cylinder' to specify the type Raises: SomaError if no soma points found, points incompatible with soma, or if soma_check(points) fails. ''' if soma_check: soma_check(points) stype = _get_type(points, soma_class) if stype is None: raise SomaError('Invalid soma points') return stype(points)
[ "def", "make_soma", "(", "points", ",", "soma_check", "=", "None", ",", "soma_class", "=", "SOMA_CONTOUR", ")", ":", "if", "soma_check", ":", "soma_check", "(", "points", ")", "stype", "=", "_get_type", "(", "points", ",", "soma_class", ")", "if", "stype", "is", "None", ":", "raise", "SomaError", "(", "'Invalid soma points'", ")", "return", "stype", "(", "points", ")" ]
Make a soma object from a set of points Infers the soma type (SomaSinglePoint, SomaSimpleContour) from the points and the 'soma_class' Parameters: points: collection of points forming a soma. soma_check: optional validation function applied to points. Should raise a SomaError if points not valid. soma_class(str): one of 'contour' or 'cylinder' to specify the type Raises: SomaError if no soma points found, points incompatible with soma, or if soma_check(points) fails.
[ "Make", "a", "soma", "object", "from", "a", "set", "of", "points" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_soma.py#L235-L260
2,577
BlueBrain/NeuroM
neurom/core/_soma.py
SomaSimpleContour.center
def center(self): '''Obtain the center from the average of all points''' points = np.array(self._points) return np.mean(points[:, COLS.XYZ], axis=0)
python
def center(self): '''Obtain the center from the average of all points''' points = np.array(self._points) return np.mean(points[:, COLS.XYZ], axis=0)
[ "def", "center", "(", "self", ")", ":", "points", "=", "np", ".", "array", "(", "self", ".", "_points", ")", "return", "np", ".", "mean", "(", "points", "[", ":", ",", "COLS", ".", "XYZ", "]", ",", "axis", "=", "0", ")" ]
Obtain the center from the average of all points
[ "Obtain", "the", "center", "from", "the", "average", "of", "all", "points" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/core/_soma.py#L188-L191
2,578
BlueBrain/NeuroM
neurom/fst/sectionfunc.py
section_tortuosity
def section_tortuosity(section): '''Tortuosity of a section The tortuosity is defined as the ratio of the path length of a section and the euclidian distnce between its end points. The path length is the sum of distances between consecutive points. If the section contains less than 2 points, the value 1 is returned. ''' pts = section.points return 1 if len(pts) < 2 else mm.section_length(pts) / mm.point_dist(pts[-1], pts[0])
python
def section_tortuosity(section): '''Tortuosity of a section The tortuosity is defined as the ratio of the path length of a section and the euclidian distnce between its end points. The path length is the sum of distances between consecutive points. If the section contains less than 2 points, the value 1 is returned. ''' pts = section.points return 1 if len(pts) < 2 else mm.section_length(pts) / mm.point_dist(pts[-1], pts[0])
[ "def", "section_tortuosity", "(", "section", ")", ":", "pts", "=", "section", ".", "points", "return", "1", "if", "len", "(", "pts", ")", "<", "2", "else", "mm", ".", "section_length", "(", "pts", ")", "/", "mm", ".", "point_dist", "(", "pts", "[", "-", "1", "]", ",", "pts", "[", "0", "]", ")" ]
Tortuosity of a section The tortuosity is defined as the ratio of the path length of a section and the euclidian distnce between its end points. The path length is the sum of distances between consecutive points. If the section contains less than 2 points, the value 1 is returned.
[ "Tortuosity", "of", "a", "section" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/sectionfunc.py#L50-L61
2,579
BlueBrain/NeuroM
neurom/fst/sectionfunc.py
section_end_distance
def section_end_distance(section): '''End to end distance of a section The end to end distance of a section is defined as the euclidian distnce between its end points. If the section contains less than 2 points, the value 0 is returned. ''' pts = section.points return 0 if len(pts) < 2 else mm.point_dist(pts[-1], pts[0])
python
def section_end_distance(section): '''End to end distance of a section The end to end distance of a section is defined as the euclidian distnce between its end points. If the section contains less than 2 points, the value 0 is returned. ''' pts = section.points return 0 if len(pts) < 2 else mm.point_dist(pts[-1], pts[0])
[ "def", "section_end_distance", "(", "section", ")", ":", "pts", "=", "section", ".", "points", "return", "0", "if", "len", "(", "pts", ")", "<", "2", "else", "mm", ".", "point_dist", "(", "pts", "[", "-", "1", "]", ",", "pts", "[", "0", "]", ")" ]
End to end distance of a section The end to end distance of a section is defined as the euclidian distnce between its end points. If the section contains less than 2 points, the value 0 is returned.
[ "End", "to", "end", "distance", "of", "a", "section" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/sectionfunc.py#L64-L73
2,580
BlueBrain/NeuroM
neurom/fst/sectionfunc.py
strahler_order
def strahler_order(section): '''Branching order of a tree section The strahler order is the inverse of the branch order, since this is computed from the tips of the tree towards the root. This implementation is a translation of the three steps described in Wikipedia (https://en.wikipedia.org/wiki/Strahler_number): - If the node is a leaf (has no children), its Strahler number is one. - If the node has one child with Strahler number i, and all other children have Strahler numbers less than i, then the Strahler number of the node is i again. - If the node has two or more children with Strahler number i, and no children with greater number, then the Strahler number of the node is i + 1. No efforts have been invested in making it computationnaly efficient, but it computes acceptably fast on tested morphologies (i.e., no waiting time). ''' if section.children: child_orders = [strahler_order(child) for child in section.children] max_so_children = max(child_orders) it = iter(co == max_so_children for co in child_orders) # check if there are *two* or more children w/ the max_so_children any(it) if any(it): return max_so_children + 1 return max_so_children return 1
python
def strahler_order(section): '''Branching order of a tree section The strahler order is the inverse of the branch order, since this is computed from the tips of the tree towards the root. This implementation is a translation of the three steps described in Wikipedia (https://en.wikipedia.org/wiki/Strahler_number): - If the node is a leaf (has no children), its Strahler number is one. - If the node has one child with Strahler number i, and all other children have Strahler numbers less than i, then the Strahler number of the node is i again. - If the node has two or more children with Strahler number i, and no children with greater number, then the Strahler number of the node is i + 1. No efforts have been invested in making it computationnaly efficient, but it computes acceptably fast on tested morphologies (i.e., no waiting time). ''' if section.children: child_orders = [strahler_order(child) for child in section.children] max_so_children = max(child_orders) it = iter(co == max_so_children for co in child_orders) # check if there are *two* or more children w/ the max_so_children any(it) if any(it): return max_so_children + 1 return max_so_children return 1
[ "def", "strahler_order", "(", "section", ")", ":", "if", "section", ".", "children", ":", "child_orders", "=", "[", "strahler_order", "(", "child", ")", "for", "child", "in", "section", ".", "children", "]", "max_so_children", "=", "max", "(", "child_orders", ")", "it", "=", "iter", "(", "co", "==", "max_so_children", "for", "co", "in", "child_orders", ")", "# check if there are *two* or more children w/ the max_so_children", "any", "(", "it", ")", "if", "any", "(", "it", ")", ":", "return", "max_so_children", "+", "1", "return", "max_so_children", "return", "1" ]
Branching order of a tree section The strahler order is the inverse of the branch order, since this is computed from the tips of the tree towards the root. This implementation is a translation of the three steps described in Wikipedia (https://en.wikipedia.org/wiki/Strahler_number): - If the node is a leaf (has no children), its Strahler number is one. - If the node has one child with Strahler number i, and all other children have Strahler numbers less than i, then the Strahler number of the node is i again. - If the node has two or more children with Strahler number i, and no children with greater number, then the Strahler number of the node is i + 1. No efforts have been invested in making it computationnaly efficient, but it computes acceptably fast on tested morphologies (i.e., no waiting time).
[ "Branching", "order", "of", "a", "tree", "section" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/fst/sectionfunc.py#L108-L138
2,581
BlueBrain/NeuroM
neurom/view/common.py
figure_naming
def figure_naming(pretitle='', posttitle='', prefile='', postfile=''): """ Helper function to define the strings that handle pre-post conventions for viewing - plotting title and saving options. Args: pretitle(str): String to include before the general title of the figure. posttitle(str): String to include after the general title of the figure. prefile(str): String to include before the general filename of the figure. postfile(str): String to include after the general filename of the figure. Returns: str: String to include in the figure name and title, in a suitable form. """ if pretitle: pretitle = "%s -- " % pretitle if posttitle: posttitle = " -- %s" % posttitle if prefile: prefile = "%s_" % prefile if postfile: postfile = "_%s" % postfile return pretitle, posttitle, prefile, postfile
python
def figure_naming(pretitle='', posttitle='', prefile='', postfile=''): """ Helper function to define the strings that handle pre-post conventions for viewing - plotting title and saving options. Args: pretitle(str): String to include before the general title of the figure. posttitle(str): String to include after the general title of the figure. prefile(str): String to include before the general filename of the figure. postfile(str): String to include after the general filename of the figure. Returns: str: String to include in the figure name and title, in a suitable form. """ if pretitle: pretitle = "%s -- " % pretitle if posttitle: posttitle = " -- %s" % posttitle if prefile: prefile = "%s_" % prefile if postfile: postfile = "_%s" % postfile return pretitle, posttitle, prefile, postfile
[ "def", "figure_naming", "(", "pretitle", "=", "''", ",", "posttitle", "=", "''", ",", "prefile", "=", "''", ",", "postfile", "=", "''", ")", ":", "if", "pretitle", ":", "pretitle", "=", "\"%s -- \"", "%", "pretitle", "if", "posttitle", ":", "posttitle", "=", "\" -- %s\"", "%", "posttitle", "if", "prefile", ":", "prefile", "=", "\"%s_\"", "%", "prefile", "if", "postfile", ":", "postfile", "=", "\"_%s\"", "%", "postfile", "return", "pretitle", ",", "posttitle", ",", "prefile", ",", "postfile" ]
Helper function to define the strings that handle pre-post conventions for viewing - plotting title and saving options. Args: pretitle(str): String to include before the general title of the figure. posttitle(str): String to include after the general title of the figure. prefile(str): String to include before the general filename of the figure. postfile(str): String to include after the general filename of the figure. Returns: str: String to include in the figure name and title, in a suitable form.
[ "Helper", "function", "to", "define", "the", "strings", "that", "handle", "pre", "-", "post", "conventions", "for", "viewing", "-", "plotting", "title", "and", "saving", "options", "." ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L56-L82
2,582
BlueBrain/NeuroM
neurom/view/common.py
get_figure
def get_figure(new_fig=True, subplot='111', params=None): """ Function to be used for viewing - plotting, to initialize the matplotlib figure - axes. Args: new_fig(bool): Defines if a new figure will be created, if false current figure is used subplot (tuple or matplolib subplot specifier string): Create axes with these parameters params (dict): extra options passed to add_subplot() Returns: Matplotlib Figure and Axes """ _get_plt() if new_fig: fig = plt.figure() else: fig = plt.gcf() params = dict_if_none(params) if isinstance(subplot, (tuple, list)): ax = fig.add_subplot(*subplot, **params) else: ax = fig.add_subplot(subplot, **params) return fig, ax
python
def get_figure(new_fig=True, subplot='111', params=None): """ Function to be used for viewing - plotting, to initialize the matplotlib figure - axes. Args: new_fig(bool): Defines if a new figure will be created, if false current figure is used subplot (tuple or matplolib subplot specifier string): Create axes with these parameters params (dict): extra options passed to add_subplot() Returns: Matplotlib Figure and Axes """ _get_plt() if new_fig: fig = plt.figure() else: fig = plt.gcf() params = dict_if_none(params) if isinstance(subplot, (tuple, list)): ax = fig.add_subplot(*subplot, **params) else: ax = fig.add_subplot(subplot, **params) return fig, ax
[ "def", "get_figure", "(", "new_fig", "=", "True", ",", "subplot", "=", "'111'", ",", "params", "=", "None", ")", ":", "_get_plt", "(", ")", "if", "new_fig", ":", "fig", "=", "plt", ".", "figure", "(", ")", "else", ":", "fig", "=", "plt", ".", "gcf", "(", ")", "params", "=", "dict_if_none", "(", "params", ")", "if", "isinstance", "(", "subplot", ",", "(", "tuple", ",", "list", ")", ")", ":", "ax", "=", "fig", ".", "add_subplot", "(", "*", "subplot", ",", "*", "*", "params", ")", "else", ":", "ax", "=", "fig", ".", "add_subplot", "(", "subplot", ",", "*", "*", "params", ")", "return", "fig", ",", "ax" ]
Function to be used for viewing - plotting, to initialize the matplotlib figure - axes. Args: new_fig(bool): Defines if a new figure will be created, if false current figure is used subplot (tuple or matplolib subplot specifier string): Create axes with these parameters params (dict): extra options passed to add_subplot() Returns: Matplotlib Figure and Axes
[ "Function", "to", "be", "used", "for", "viewing", "-", "plotting", "to", "initialize", "the", "matplotlib", "figure", "-", "axes", "." ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L85-L112
2,583
BlueBrain/NeuroM
neurom/view/common.py
save_plot
def save_plot(fig, prefile='', postfile='', output_path='./', output_name='Figure', output_format='png', dpi=300, transparent=False, **_): """Generates a figure file in the selected directory. Args: fig: matplotlib figure prefile(str): Include before the general filename of the figure postfile(str): Included after the general filename of the figure output_path(str): Define the path to the output directory output_name(str): String to define the name of the output figure output_format(str): String to define the format of the output figure dpi(int): Define the DPI (Dots per Inch) of the figure transparent(bool): If True the saved figure will have a transparent background """ if not os.path.exists(output_path): os.makedirs(output_path) # Make output directory if non-exsiting output = os.path.join(output_path, prefile + output_name + postfile + "." + output_format) fig.savefig(output, dpi=dpi, transparent=transparent)
python
def save_plot(fig, prefile='', postfile='', output_path='./', output_name='Figure', output_format='png', dpi=300, transparent=False, **_): """Generates a figure file in the selected directory. Args: fig: matplotlib figure prefile(str): Include before the general filename of the figure postfile(str): Included after the general filename of the figure output_path(str): Define the path to the output directory output_name(str): String to define the name of the output figure output_format(str): String to define the format of the output figure dpi(int): Define the DPI (Dots per Inch) of the figure transparent(bool): If True the saved figure will have a transparent background """ if not os.path.exists(output_path): os.makedirs(output_path) # Make output directory if non-exsiting output = os.path.join(output_path, prefile + output_name + postfile + "." + output_format) fig.savefig(output, dpi=dpi, transparent=transparent)
[ "def", "save_plot", "(", "fig", ",", "prefile", "=", "''", ",", "postfile", "=", "''", ",", "output_path", "=", "'./'", ",", "output_name", "=", "'Figure'", ",", "output_format", "=", "'png'", ",", "dpi", "=", "300", ",", "transparent", "=", "False", ",", "*", "*", "_", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "output_path", ")", ":", "os", ".", "makedirs", "(", "output_path", ")", "# Make output directory if non-exsiting", "output", "=", "os", ".", "path", ".", "join", "(", "output_path", ",", "prefile", "+", "output_name", "+", "postfile", "+", "\".\"", "+", "output_format", ")", "fig", ".", "savefig", "(", "output", ",", "dpi", "=", "dpi", ",", "transparent", "=", "transparent", ")" ]
Generates a figure file in the selected directory. Args: fig: matplotlib figure prefile(str): Include before the general filename of the figure postfile(str): Included after the general filename of the figure output_path(str): Define the path to the output directory output_name(str): String to define the name of the output figure output_format(str): String to define the format of the output figure dpi(int): Define the DPI (Dots per Inch) of the figure transparent(bool): If True the saved figure will have a transparent background
[ "Generates", "a", "figure", "file", "in", "the", "selected", "directory", "." ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L115-L135
2,584
BlueBrain/NeuroM
neurom/view/common.py
plot_style
def plot_style(fig, ax, # pylint: disable=too-many-arguments, too-many-locals # plot_title pretitle='', title='Figure', posttitle='', title_fontsize=14, title_arg=None, # plot_labels label_fontsize=14, xlabel=None, xlabel_arg=None, ylabel=None, ylabel_arg=None, zlabel=None, zlabel_arg=None, # plot_ticks tick_fontsize=12, xticks=None, xticks_args=None, yticks=None, yticks_args=None, zticks=None, zticks_args=None, # update_plot_limits white_space=30, # plot_legend no_legend=True, legend_arg=None, # internal no_axes=False, aspect_ratio='equal', tight=False, **_): """Set the basic options of a matplotlib figure, to be used by viewing - plotting functions Args: fig(matplotlib figure): figure ax(matplotlib axes, belonging to `fig`): axes pretitle(str): String to include before the general title of the figure posttitle (str): String to include after the general title of the figure title (str): Set the title for the figure title_fontsize (int): Defines the size of the title's font title_arg (dict): Addition arguments for matplotlib.title() call label_fontsize(int): Size of the labels' font xlabel(str): The xlabel for the figure xlabel_arg(dict): Passsed into matplotlib as xlabel arguments ylabel(str): The ylabel for the figure ylabel_arg(dict): Passsed into matplotlib as ylabel arguments zlabel(str): The zlabel for the figure zlabel_arg(dict): Passsed into matplotlib as zlabel arguments tick_fontsize (int): Defines the size of the ticks' font xticks([list of ticks]): Defines the values of x ticks in the figure xticks_args(dict): Passsed into matplotlib as xticks arguments yticks([list of ticks]): Defines the values of y ticks in the figure yticks_args(dict): Passsed into matplotlib as yticks arguments zticks([list of ticks]): Defines the values of z ticks in the figure zticks_args(dict): Passsed into matplotlib as zticks arguments white_space(float): whitespace added to surround the tight limit of the data no_legend (bool): Defines the presence of a legend in the figure legend_arg (dict): Addition arguments for matplotlib.legend() call no_axes(bool): If True the labels and the frame will be set off aspect_ratio(str): Sets aspect ratio of the figure, according to matplotlib aspect_ratio tight(bool): If True the tight layout of matplotlib will be activated Returns: Matplotlib figure, matplotlib axes """ plot_title(ax, pretitle, title, posttitle, title_fontsize, title_arg) plot_labels(ax, label_fontsize, xlabel, xlabel_arg, ylabel, ylabel_arg, zlabel, zlabel_arg) plot_ticks(ax, tick_fontsize, xticks, xticks_args, yticks, yticks_args, zticks, zticks_args) update_plot_limits(ax, white_space) plot_legend(ax, no_legend, legend_arg) if no_axes: ax.set_frame_on(False) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) ax.set_aspect(aspect_ratio) if tight: fig.set_tight_layout(True)
python
def plot_style(fig, ax, # pylint: disable=too-many-arguments, too-many-locals # plot_title pretitle='', title='Figure', posttitle='', title_fontsize=14, title_arg=None, # plot_labels label_fontsize=14, xlabel=None, xlabel_arg=None, ylabel=None, ylabel_arg=None, zlabel=None, zlabel_arg=None, # plot_ticks tick_fontsize=12, xticks=None, xticks_args=None, yticks=None, yticks_args=None, zticks=None, zticks_args=None, # update_plot_limits white_space=30, # plot_legend no_legend=True, legend_arg=None, # internal no_axes=False, aspect_ratio='equal', tight=False, **_): """Set the basic options of a matplotlib figure, to be used by viewing - plotting functions Args: fig(matplotlib figure): figure ax(matplotlib axes, belonging to `fig`): axes pretitle(str): String to include before the general title of the figure posttitle (str): String to include after the general title of the figure title (str): Set the title for the figure title_fontsize (int): Defines the size of the title's font title_arg (dict): Addition arguments for matplotlib.title() call label_fontsize(int): Size of the labels' font xlabel(str): The xlabel for the figure xlabel_arg(dict): Passsed into matplotlib as xlabel arguments ylabel(str): The ylabel for the figure ylabel_arg(dict): Passsed into matplotlib as ylabel arguments zlabel(str): The zlabel for the figure zlabel_arg(dict): Passsed into matplotlib as zlabel arguments tick_fontsize (int): Defines the size of the ticks' font xticks([list of ticks]): Defines the values of x ticks in the figure xticks_args(dict): Passsed into matplotlib as xticks arguments yticks([list of ticks]): Defines the values of y ticks in the figure yticks_args(dict): Passsed into matplotlib as yticks arguments zticks([list of ticks]): Defines the values of z ticks in the figure zticks_args(dict): Passsed into matplotlib as zticks arguments white_space(float): whitespace added to surround the tight limit of the data no_legend (bool): Defines the presence of a legend in the figure legend_arg (dict): Addition arguments for matplotlib.legend() call no_axes(bool): If True the labels and the frame will be set off aspect_ratio(str): Sets aspect ratio of the figure, according to matplotlib aspect_ratio tight(bool): If True the tight layout of matplotlib will be activated Returns: Matplotlib figure, matplotlib axes """ plot_title(ax, pretitle, title, posttitle, title_fontsize, title_arg) plot_labels(ax, label_fontsize, xlabel, xlabel_arg, ylabel, ylabel_arg, zlabel, zlabel_arg) plot_ticks(ax, tick_fontsize, xticks, xticks_args, yticks, yticks_args, zticks, zticks_args) update_plot_limits(ax, white_space) plot_legend(ax, no_legend, legend_arg) if no_axes: ax.set_frame_on(False) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) ax.set_aspect(aspect_ratio) if tight: fig.set_tight_layout(True)
[ "def", "plot_style", "(", "fig", ",", "ax", ",", "# pylint: disable=too-many-arguments, too-many-locals", "# plot_title", "pretitle", "=", "''", ",", "title", "=", "'Figure'", ",", "posttitle", "=", "''", ",", "title_fontsize", "=", "14", ",", "title_arg", "=", "None", ",", "# plot_labels", "label_fontsize", "=", "14", ",", "xlabel", "=", "None", ",", "xlabel_arg", "=", "None", ",", "ylabel", "=", "None", ",", "ylabel_arg", "=", "None", ",", "zlabel", "=", "None", ",", "zlabel_arg", "=", "None", ",", "# plot_ticks", "tick_fontsize", "=", "12", ",", "xticks", "=", "None", ",", "xticks_args", "=", "None", ",", "yticks", "=", "None", ",", "yticks_args", "=", "None", ",", "zticks", "=", "None", ",", "zticks_args", "=", "None", ",", "# update_plot_limits", "white_space", "=", "30", ",", "# plot_legend", "no_legend", "=", "True", ",", "legend_arg", "=", "None", ",", "# internal", "no_axes", "=", "False", ",", "aspect_ratio", "=", "'equal'", ",", "tight", "=", "False", ",", "*", "*", "_", ")", ":", "plot_title", "(", "ax", ",", "pretitle", ",", "title", ",", "posttitle", ",", "title_fontsize", ",", "title_arg", ")", "plot_labels", "(", "ax", ",", "label_fontsize", ",", "xlabel", ",", "xlabel_arg", ",", "ylabel", ",", "ylabel_arg", ",", "zlabel", ",", "zlabel_arg", ")", "plot_ticks", "(", "ax", ",", "tick_fontsize", ",", "xticks", ",", "xticks_args", ",", "yticks", ",", "yticks_args", ",", "zticks", ",", "zticks_args", ")", "update_plot_limits", "(", "ax", ",", "white_space", ")", "plot_legend", "(", "ax", ",", "no_legend", ",", "legend_arg", ")", "if", "no_axes", ":", "ax", ".", "set_frame_on", "(", "False", ")", "ax", ".", "xaxis", ".", "set_visible", "(", "False", ")", "ax", ".", "yaxis", ".", "set_visible", "(", "False", ")", "ax", ".", "set_aspect", "(", "aspect_ratio", ")", "if", "tight", ":", "fig", ".", "set_tight_layout", "(", "True", ")" ]
Set the basic options of a matplotlib figure, to be used by viewing - plotting functions Args: fig(matplotlib figure): figure ax(matplotlib axes, belonging to `fig`): axes pretitle(str): String to include before the general title of the figure posttitle (str): String to include after the general title of the figure title (str): Set the title for the figure title_fontsize (int): Defines the size of the title's font title_arg (dict): Addition arguments for matplotlib.title() call label_fontsize(int): Size of the labels' font xlabel(str): The xlabel for the figure xlabel_arg(dict): Passsed into matplotlib as xlabel arguments ylabel(str): The ylabel for the figure ylabel_arg(dict): Passsed into matplotlib as ylabel arguments zlabel(str): The zlabel for the figure zlabel_arg(dict): Passsed into matplotlib as zlabel arguments tick_fontsize (int): Defines the size of the ticks' font xticks([list of ticks]): Defines the values of x ticks in the figure xticks_args(dict): Passsed into matplotlib as xticks arguments yticks([list of ticks]): Defines the values of y ticks in the figure yticks_args(dict): Passsed into matplotlib as yticks arguments zticks([list of ticks]): Defines the values of z ticks in the figure zticks_args(dict): Passsed into matplotlib as zticks arguments white_space(float): whitespace added to surround the tight limit of the data no_legend (bool): Defines the presence of a legend in the figure legend_arg (dict): Addition arguments for matplotlib.legend() call no_axes(bool): If True the labels and the frame will be set off aspect_ratio(str): Sets aspect ratio of the figure, according to matplotlib aspect_ratio tight(bool): If True the tight layout of matplotlib will be activated Returns: Matplotlib figure, matplotlib axes
[ "Set", "the", "basic", "options", "of", "a", "matplotlib", "figure", "to", "be", "used", "by", "viewing", "-", "plotting", "functions" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L138-L225
2,585
BlueBrain/NeuroM
neurom/view/common.py
plot_title
def plot_title(ax, pretitle='', title='Figure', posttitle='', title_fontsize=14, title_arg=None): """Set title options of a matplotlib plot Args: ax: matplotlib axes pretitle(str): String to include before the general title of the figure posttitle (str): String to include after the general title of the figure title (str): Set the title for the figure title_fontsize (int): Defines the size of the title's font title_arg (dict): Addition arguments for matplotlib.title() call """ current_title = ax.get_title() if not current_title: current_title = pretitle + title + posttitle title_arg = dict_if_none(title_arg) ax.set_title(current_title, fontsize=title_fontsize, **title_arg)
python
def plot_title(ax, pretitle='', title='Figure', posttitle='', title_fontsize=14, title_arg=None): """Set title options of a matplotlib plot Args: ax: matplotlib axes pretitle(str): String to include before the general title of the figure posttitle (str): String to include after the general title of the figure title (str): Set the title for the figure title_fontsize (int): Defines the size of the title's font title_arg (dict): Addition arguments for matplotlib.title() call """ current_title = ax.get_title() if not current_title: current_title = pretitle + title + posttitle title_arg = dict_if_none(title_arg) ax.set_title(current_title, fontsize=title_fontsize, **title_arg)
[ "def", "plot_title", "(", "ax", ",", "pretitle", "=", "''", ",", "title", "=", "'Figure'", ",", "posttitle", "=", "''", ",", "title_fontsize", "=", "14", ",", "title_arg", "=", "None", ")", ":", "current_title", "=", "ax", ".", "get_title", "(", ")", "if", "not", "current_title", ":", "current_title", "=", "pretitle", "+", "title", "+", "posttitle", "title_arg", "=", "dict_if_none", "(", "title_arg", ")", "ax", ".", "set_title", "(", "current_title", ",", "fontsize", "=", "title_fontsize", ",", "*", "*", "title_arg", ")" ]
Set title options of a matplotlib plot Args: ax: matplotlib axes pretitle(str): String to include before the general title of the figure posttitle (str): String to include after the general title of the figure title (str): Set the title for the figure title_fontsize (int): Defines the size of the title's font title_arg (dict): Addition arguments for matplotlib.title() call
[ "Set", "title", "options", "of", "a", "matplotlib", "plot" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L228-L246
2,586
BlueBrain/NeuroM
neurom/view/common.py
plot_labels
def plot_labels(ax, label_fontsize=14, xlabel=None, xlabel_arg=None, ylabel=None, ylabel_arg=None, zlabel=None, zlabel_arg=None): """Sets the labels options of a matplotlib plot Args: ax: matplotlib axes label_fontsize(int): Size of the labels' font xlabel(str): The xlabel for the figure xlabel_arg(dict): Passsed into matplotlib as xlabel arguments ylabel(str): The ylabel for the figure ylabel_arg(dict): Passsed into matplotlib as ylabel arguments zlabel(str): The zlabel for the figure zlabel_arg(dict): Passsed into matplotlib as zlabel arguments """ xlabel = xlabel if xlabel is not None else ax.get_xlabel() or 'X' ylabel = ylabel if ylabel is not None else ax.get_ylabel() or 'Y' xlabel_arg = dict_if_none(xlabel_arg) ylabel_arg = dict_if_none(ylabel_arg) ax.set_xlabel(xlabel, fontsize=label_fontsize, **xlabel_arg) ax.set_ylabel(ylabel, fontsize=label_fontsize, **ylabel_arg) if hasattr(ax, 'zaxis'): zlabel = zlabel if zlabel is not None else ax.get_zlabel() or 'Z' zlabel_arg = dict_if_none(zlabel_arg) ax.set_zlabel(zlabel, fontsize=label_fontsize, **zlabel_arg)
python
def plot_labels(ax, label_fontsize=14, xlabel=None, xlabel_arg=None, ylabel=None, ylabel_arg=None, zlabel=None, zlabel_arg=None): """Sets the labels options of a matplotlib plot Args: ax: matplotlib axes label_fontsize(int): Size of the labels' font xlabel(str): The xlabel for the figure xlabel_arg(dict): Passsed into matplotlib as xlabel arguments ylabel(str): The ylabel for the figure ylabel_arg(dict): Passsed into matplotlib as ylabel arguments zlabel(str): The zlabel for the figure zlabel_arg(dict): Passsed into matplotlib as zlabel arguments """ xlabel = xlabel if xlabel is not None else ax.get_xlabel() or 'X' ylabel = ylabel if ylabel is not None else ax.get_ylabel() or 'Y' xlabel_arg = dict_if_none(xlabel_arg) ylabel_arg = dict_if_none(ylabel_arg) ax.set_xlabel(xlabel, fontsize=label_fontsize, **xlabel_arg) ax.set_ylabel(ylabel, fontsize=label_fontsize, **ylabel_arg) if hasattr(ax, 'zaxis'): zlabel = zlabel if zlabel is not None else ax.get_zlabel() or 'Z' zlabel_arg = dict_if_none(zlabel_arg) ax.set_zlabel(zlabel, fontsize=label_fontsize, **zlabel_arg)
[ "def", "plot_labels", "(", "ax", ",", "label_fontsize", "=", "14", ",", "xlabel", "=", "None", ",", "xlabel_arg", "=", "None", ",", "ylabel", "=", "None", ",", "ylabel_arg", "=", "None", ",", "zlabel", "=", "None", ",", "zlabel_arg", "=", "None", ")", ":", "xlabel", "=", "xlabel", "if", "xlabel", "is", "not", "None", "else", "ax", ".", "get_xlabel", "(", ")", "or", "'X'", "ylabel", "=", "ylabel", "if", "ylabel", "is", "not", "None", "else", "ax", ".", "get_ylabel", "(", ")", "or", "'Y'", "xlabel_arg", "=", "dict_if_none", "(", "xlabel_arg", ")", "ylabel_arg", "=", "dict_if_none", "(", "ylabel_arg", ")", "ax", ".", "set_xlabel", "(", "xlabel", ",", "fontsize", "=", "label_fontsize", ",", "*", "*", "xlabel_arg", ")", "ax", ".", "set_ylabel", "(", "ylabel", ",", "fontsize", "=", "label_fontsize", ",", "*", "*", "ylabel_arg", ")", "if", "hasattr", "(", "ax", ",", "'zaxis'", ")", ":", "zlabel", "=", "zlabel", "if", "zlabel", "is", "not", "None", "else", "ax", ".", "get_zlabel", "(", ")", "or", "'Z'", "zlabel_arg", "=", "dict_if_none", "(", "zlabel_arg", ")", "ax", ".", "set_zlabel", "(", "zlabel", ",", "fontsize", "=", "label_fontsize", ",", "*", "*", "zlabel_arg", ")" ]
Sets the labels options of a matplotlib plot Args: ax: matplotlib axes label_fontsize(int): Size of the labels' font xlabel(str): The xlabel for the figure xlabel_arg(dict): Passsed into matplotlib as xlabel arguments ylabel(str): The ylabel for the figure ylabel_arg(dict): Passsed into matplotlib as ylabel arguments zlabel(str): The zlabel for the figure zlabel_arg(dict): Passsed into matplotlib as zlabel arguments
[ "Sets", "the", "labels", "options", "of", "a", "matplotlib", "plot" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L249-L277
2,587
BlueBrain/NeuroM
neurom/view/common.py
plot_ticks
def plot_ticks(ax, tick_fontsize=12, xticks=None, xticks_args=None, yticks=None, yticks_args=None, zticks=None, zticks_args=None): """Function that defines the labels options of a matplotlib plot. Args: ax: matplotlib axes tick_fontsize (int): Defines the size of the ticks' font xticks([list of ticks]): Defines the values of x ticks in the figure xticks_arg(dict): Passsed into matplotlib as xticks arguments yticks([list of ticks]): Defines the values of y ticks in the figure yticks_arg(dict): Passsed into matplotlib as yticks arguments zticks([list of ticks]): Defines the values of z ticks in the figure zticks_arg(dict): Passsed into matplotlib as zticks arguments """ if xticks is not None: ax.set_xticks(xticks) xticks_args = dict_if_none(xticks_args) ax.xaxis.set_tick_params(labelsize=tick_fontsize, **xticks_args) if yticks is not None: ax.set_yticks(yticks) yticks_args = dict_if_none(yticks_args) ax.yaxis.set_tick_params(labelsize=tick_fontsize, **yticks_args) if zticks is not None: ax.set_zticks(zticks) zticks_args = dict_if_none(zticks_args) ax.zaxis.set_tick_params(labelsize=tick_fontsize, **zticks_args)
python
def plot_ticks(ax, tick_fontsize=12, xticks=None, xticks_args=None, yticks=None, yticks_args=None, zticks=None, zticks_args=None): """Function that defines the labels options of a matplotlib plot. Args: ax: matplotlib axes tick_fontsize (int): Defines the size of the ticks' font xticks([list of ticks]): Defines the values of x ticks in the figure xticks_arg(dict): Passsed into matplotlib as xticks arguments yticks([list of ticks]): Defines the values of y ticks in the figure yticks_arg(dict): Passsed into matplotlib as yticks arguments zticks([list of ticks]): Defines the values of z ticks in the figure zticks_arg(dict): Passsed into matplotlib as zticks arguments """ if xticks is not None: ax.set_xticks(xticks) xticks_args = dict_if_none(xticks_args) ax.xaxis.set_tick_params(labelsize=tick_fontsize, **xticks_args) if yticks is not None: ax.set_yticks(yticks) yticks_args = dict_if_none(yticks_args) ax.yaxis.set_tick_params(labelsize=tick_fontsize, **yticks_args) if zticks is not None: ax.set_zticks(zticks) zticks_args = dict_if_none(zticks_args) ax.zaxis.set_tick_params(labelsize=tick_fontsize, **zticks_args)
[ "def", "plot_ticks", "(", "ax", ",", "tick_fontsize", "=", "12", ",", "xticks", "=", "None", ",", "xticks_args", "=", "None", ",", "yticks", "=", "None", ",", "yticks_args", "=", "None", ",", "zticks", "=", "None", ",", "zticks_args", "=", "None", ")", ":", "if", "xticks", "is", "not", "None", ":", "ax", ".", "set_xticks", "(", "xticks", ")", "xticks_args", "=", "dict_if_none", "(", "xticks_args", ")", "ax", ".", "xaxis", ".", "set_tick_params", "(", "labelsize", "=", "tick_fontsize", ",", "*", "*", "xticks_args", ")", "if", "yticks", "is", "not", "None", ":", "ax", ".", "set_yticks", "(", "yticks", ")", "yticks_args", "=", "dict_if_none", "(", "yticks_args", ")", "ax", ".", "yaxis", ".", "set_tick_params", "(", "labelsize", "=", "tick_fontsize", ",", "*", "*", "yticks_args", ")", "if", "zticks", "is", "not", "None", ":", "ax", ".", "set_zticks", "(", "zticks", ")", "zticks_args", "=", "dict_if_none", "(", "zticks_args", ")", "ax", ".", "zaxis", ".", "set_tick_params", "(", "labelsize", "=", "tick_fontsize", ",", "*", "*", "zticks_args", ")" ]
Function that defines the labels options of a matplotlib plot. Args: ax: matplotlib axes tick_fontsize (int): Defines the size of the ticks' font xticks([list of ticks]): Defines the values of x ticks in the figure xticks_arg(dict): Passsed into matplotlib as xticks arguments yticks([list of ticks]): Defines the values of y ticks in the figure yticks_arg(dict): Passsed into matplotlib as yticks arguments zticks([list of ticks]): Defines the values of z ticks in the figure zticks_arg(dict): Passsed into matplotlib as zticks arguments
[ "Function", "that", "defines", "the", "labels", "options", "of", "a", "matplotlib", "plot", "." ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L280-L309
2,588
BlueBrain/NeuroM
neurom/view/common.py
update_plot_limits
def update_plot_limits(ax, white_space): """Sets the limit options of a matplotlib plot. Args: ax: matplotlib axes white_space(float): whitespace added to surround the tight limit of the data Note: This relies on ax.dataLim (in 2d) and ax.[xy, zz]_dataLim being set in 3d """ if hasattr(ax, 'zz_dataLim'): bounds = ax.xy_dataLim.bounds ax.set_xlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space) ax.set_ylim(bounds[1] - white_space, bounds[1] + bounds[3] + white_space) bounds = ax.zz_dataLim.bounds ax.set_zlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space) else: bounds = ax.dataLim.bounds assert not any(map(np.isinf, bounds)), 'Cannot set bounds if dataLim has infinite elements' ax.set_xlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space) ax.set_ylim(bounds[1] - white_space, bounds[1] + bounds[3] + white_space)
python
def update_plot_limits(ax, white_space): """Sets the limit options of a matplotlib plot. Args: ax: matplotlib axes white_space(float): whitespace added to surround the tight limit of the data Note: This relies on ax.dataLim (in 2d) and ax.[xy, zz]_dataLim being set in 3d """ if hasattr(ax, 'zz_dataLim'): bounds = ax.xy_dataLim.bounds ax.set_xlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space) ax.set_ylim(bounds[1] - white_space, bounds[1] + bounds[3] + white_space) bounds = ax.zz_dataLim.bounds ax.set_zlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space) else: bounds = ax.dataLim.bounds assert not any(map(np.isinf, bounds)), 'Cannot set bounds if dataLim has infinite elements' ax.set_xlim(bounds[0] - white_space, bounds[0] + bounds[2] + white_space) ax.set_ylim(bounds[1] - white_space, bounds[1] + bounds[3] + white_space)
[ "def", "update_plot_limits", "(", "ax", ",", "white_space", ")", ":", "if", "hasattr", "(", "ax", ",", "'zz_dataLim'", ")", ":", "bounds", "=", "ax", ".", "xy_dataLim", ".", "bounds", "ax", ".", "set_xlim", "(", "bounds", "[", "0", "]", "-", "white_space", ",", "bounds", "[", "0", "]", "+", "bounds", "[", "2", "]", "+", "white_space", ")", "ax", ".", "set_ylim", "(", "bounds", "[", "1", "]", "-", "white_space", ",", "bounds", "[", "1", "]", "+", "bounds", "[", "3", "]", "+", "white_space", ")", "bounds", "=", "ax", ".", "zz_dataLim", ".", "bounds", "ax", ".", "set_zlim", "(", "bounds", "[", "0", "]", "-", "white_space", ",", "bounds", "[", "0", "]", "+", "bounds", "[", "2", "]", "+", "white_space", ")", "else", ":", "bounds", "=", "ax", ".", "dataLim", ".", "bounds", "assert", "not", "any", "(", "map", "(", "np", ".", "isinf", ",", "bounds", ")", ")", ",", "'Cannot set bounds if dataLim has infinite elements'", "ax", ".", "set_xlim", "(", "bounds", "[", "0", "]", "-", "white_space", ",", "bounds", "[", "0", "]", "+", "bounds", "[", "2", "]", "+", "white_space", ")", "ax", ".", "set_ylim", "(", "bounds", "[", "1", "]", "-", "white_space", ",", "bounds", "[", "1", "]", "+", "bounds", "[", "3", "]", "+", "white_space", ")" ]
Sets the limit options of a matplotlib plot. Args: ax: matplotlib axes white_space(float): whitespace added to surround the tight limit of the data Note: This relies on ax.dataLim (in 2d) and ax.[xy, zz]_dataLim being set in 3d
[ "Sets", "the", "limit", "options", "of", "a", "matplotlib", "plot", "." ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L312-L333
2,589
BlueBrain/NeuroM
neurom/view/common.py
plot_legend
def plot_legend(ax, no_legend=True, legend_arg=None): """ Function that defines the legend options of a matplotlib plot. Args: ax: matplotlib axes no_legend (bool): Defines the presence of a legend in the figure legend_arg (dict): Addition arguments for matplotlib.legend() call """ legend_arg = dict_if_none(legend_arg) if not no_legend: ax.legend(**legend_arg)
python
def plot_legend(ax, no_legend=True, legend_arg=None): """ Function that defines the legend options of a matplotlib plot. Args: ax: matplotlib axes no_legend (bool): Defines the presence of a legend in the figure legend_arg (dict): Addition arguments for matplotlib.legend() call """ legend_arg = dict_if_none(legend_arg) if not no_legend: ax.legend(**legend_arg)
[ "def", "plot_legend", "(", "ax", ",", "no_legend", "=", "True", ",", "legend_arg", "=", "None", ")", ":", "legend_arg", "=", "dict_if_none", "(", "legend_arg", ")", "if", "not", "no_legend", ":", "ax", ".", "legend", "(", "*", "*", "legend_arg", ")" ]
Function that defines the legend options of a matplotlib plot. Args: ax: matplotlib axes no_legend (bool): Defines the presence of a legend in the figure legend_arg (dict): Addition arguments for matplotlib.legend() call
[ "Function", "that", "defines", "the", "legend", "options", "of", "a", "matplotlib", "plot", "." ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L336-L349
2,590
BlueBrain/NeuroM
neurom/view/common.py
generate_cylindrical_points
def generate_cylindrical_points(start, end, start_radius, end_radius, linspace_count=_LINSPACE_COUNT): '''Generate a 3d mesh of a cylinder with start and end points, and varying radius Based on: http://stackoverflow.com/a/32383775 ''' v = end - start length = norm(v) v = v / length n1, n2 = _get_normals(v) # pylint: disable=unbalanced-tuple-unpacking l, theta = np.meshgrid(np.linspace(0, length, linspace_count), np.linspace(0, 2 * np.pi, linspace_count)) radii = np.linspace(start_radius, end_radius, linspace_count) rsin = np.multiply(radii, np.sin(theta)) rcos = np.multiply(radii, np.cos(theta)) return np.array([start[i] + v[i] * l + n1[i] * rsin + n2[i] * rcos for i in range(3)])
python
def generate_cylindrical_points(start, end, start_radius, end_radius, linspace_count=_LINSPACE_COUNT): '''Generate a 3d mesh of a cylinder with start and end points, and varying radius Based on: http://stackoverflow.com/a/32383775 ''' v = end - start length = norm(v) v = v / length n1, n2 = _get_normals(v) # pylint: disable=unbalanced-tuple-unpacking l, theta = np.meshgrid(np.linspace(0, length, linspace_count), np.linspace(0, 2 * np.pi, linspace_count)) radii = np.linspace(start_radius, end_radius, linspace_count) rsin = np.multiply(radii, np.sin(theta)) rcos = np.multiply(radii, np.cos(theta)) return np.array([start[i] + v[i] * l + n1[i] * rsin + n2[i] * rcos for i in range(3)])
[ "def", "generate_cylindrical_points", "(", "start", ",", "end", ",", "start_radius", ",", "end_radius", ",", "linspace_count", "=", "_LINSPACE_COUNT", ")", ":", "v", "=", "end", "-", "start", "length", "=", "norm", "(", "v", ")", "v", "=", "v", "/", "length", "n1", ",", "n2", "=", "_get_normals", "(", "v", ")", "# pylint: disable=unbalanced-tuple-unpacking", "l", ",", "theta", "=", "np", ".", "meshgrid", "(", "np", ".", "linspace", "(", "0", ",", "length", ",", "linspace_count", ")", ",", "np", ".", "linspace", "(", "0", ",", "2", "*", "np", ".", "pi", ",", "linspace_count", ")", ")", "radii", "=", "np", ".", "linspace", "(", "start_radius", ",", "end_radius", ",", "linspace_count", ")", "rsin", "=", "np", ".", "multiply", "(", "radii", ",", "np", ".", "sin", "(", "theta", ")", ")", "rcos", "=", "np", ".", "multiply", "(", "radii", ",", "np", ".", "cos", "(", "theta", ")", ")", "return", "np", ".", "array", "(", "[", "start", "[", "i", "]", "+", "v", "[", "i", "]", "*", "l", "+", "n1", "[", "i", "]", "*", "rsin", "+", "n2", "[", "i", "]", "*", "rcos", "for", "i", "in", "range", "(", "3", ")", "]", ")" ]
Generate a 3d mesh of a cylinder with start and end points, and varying radius Based on: http://stackoverflow.com/a/32383775
[ "Generate", "a", "3d", "mesh", "of", "a", "cylinder", "with", "start", "and", "end", "points", "and", "varying", "radius" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L369-L391
2,591
BlueBrain/NeuroM
neurom/view/common.py
plot_cylinder
def plot_cylinder(ax, start, end, start_radius, end_radius, color='black', alpha=1., linspace_count=_LINSPACE_COUNT): '''plot a 3d cylinder''' assert not np.all(start == end), 'Cylinder must have length' x, y, z = generate_cylindrical_points(start, end, start_radius, end_radius, linspace_count=linspace_count) ax.plot_surface(x, y, z, color=color, alpha=alpha)
python
def plot_cylinder(ax, start, end, start_radius, end_radius, color='black', alpha=1., linspace_count=_LINSPACE_COUNT): '''plot a 3d cylinder''' assert not np.all(start == end), 'Cylinder must have length' x, y, z = generate_cylindrical_points(start, end, start_radius, end_radius, linspace_count=linspace_count) ax.plot_surface(x, y, z, color=color, alpha=alpha)
[ "def", "plot_cylinder", "(", "ax", ",", "start", ",", "end", ",", "start_radius", ",", "end_radius", ",", "color", "=", "'black'", ",", "alpha", "=", "1.", ",", "linspace_count", "=", "_LINSPACE_COUNT", ")", ":", "assert", "not", "np", ".", "all", "(", "start", "==", "end", ")", ",", "'Cylinder must have length'", "x", ",", "y", ",", "z", "=", "generate_cylindrical_points", "(", "start", ",", "end", ",", "start_radius", ",", "end_radius", ",", "linspace_count", "=", "linspace_count", ")", "ax", ".", "plot_surface", "(", "x", ",", "y", ",", "z", ",", "color", "=", "color", ",", "alpha", "=", "alpha", ")" ]
plot a 3d cylinder
[ "plot", "a", "3d", "cylinder" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L421-L427
2,592
BlueBrain/NeuroM
neurom/view/common.py
plot_sphere
def plot_sphere(ax, center, radius, color='black', alpha=1., linspace_count=_LINSPACE_COUNT): """ Plots a 3d sphere, given the center and the radius. """ u = np.linspace(0, 2 * np.pi, linspace_count) v = np.linspace(0, np.pi, linspace_count) sin_v = np.sin(v) x = center[0] + radius * np.outer(np.cos(u), sin_v) y = center[1] + radius * np.outer(np.sin(u), sin_v) z = center[2] + radius * np.outer(np.ones_like(u), np.cos(v)) ax.plot_surface(x, y, z, linewidth=0.0, color=color, alpha=alpha)
python
def plot_sphere(ax, center, radius, color='black', alpha=1., linspace_count=_LINSPACE_COUNT): """ Plots a 3d sphere, given the center and the radius. """ u = np.linspace(0, 2 * np.pi, linspace_count) v = np.linspace(0, np.pi, linspace_count) sin_v = np.sin(v) x = center[0] + radius * np.outer(np.cos(u), sin_v) y = center[1] + radius * np.outer(np.sin(u), sin_v) z = center[2] + radius * np.outer(np.ones_like(u), np.cos(v)) ax.plot_surface(x, y, z, linewidth=0.0, color=color, alpha=alpha)
[ "def", "plot_sphere", "(", "ax", ",", "center", ",", "radius", ",", "color", "=", "'black'", ",", "alpha", "=", "1.", ",", "linspace_count", "=", "_LINSPACE_COUNT", ")", ":", "u", "=", "np", ".", "linspace", "(", "0", ",", "2", "*", "np", ".", "pi", ",", "linspace_count", ")", "v", "=", "np", ".", "linspace", "(", "0", ",", "np", ".", "pi", ",", "linspace_count", ")", "sin_v", "=", "np", ".", "sin", "(", "v", ")", "x", "=", "center", "[", "0", "]", "+", "radius", "*", "np", ".", "outer", "(", "np", ".", "cos", "(", "u", ")", ",", "sin_v", ")", "y", "=", "center", "[", "1", "]", "+", "radius", "*", "np", ".", "outer", "(", "np", ".", "sin", "(", "u", ")", ",", "sin_v", ")", "z", "=", "center", "[", "2", "]", "+", "radius", "*", "np", ".", "outer", "(", "np", ".", "ones_like", "(", "u", ")", ",", "np", ".", "cos", "(", "v", ")", ")", "ax", ".", "plot_surface", "(", "x", ",", "y", ",", "z", ",", "linewidth", "=", "0.0", ",", "color", "=", "color", ",", "alpha", "=", "alpha", ")" ]
Plots a 3d sphere, given the center and the radius.
[ "Plots", "a", "3d", "sphere", "given", "the", "center", "and", "the", "radius", "." ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/view/common.py#L430-L440
2,593
BlueBrain/NeuroM
neurom/check/structural_checks.py
has_sequential_ids
def has_sequential_ids(data_wrapper): '''Check that IDs are increasing and consecutive returns tuple (bool, list of IDs that are not consecutive with their predecessor) ''' db = data_wrapper.data_block ids = db[:, COLS.ID] steps = ids[np.where(np.diff(ids) != 1)[0] + 1].astype(int) return CheckResult(len(steps) == 0, steps)
python
def has_sequential_ids(data_wrapper): '''Check that IDs are increasing and consecutive returns tuple (bool, list of IDs that are not consecutive with their predecessor) ''' db = data_wrapper.data_block ids = db[:, COLS.ID] steps = ids[np.where(np.diff(ids) != 1)[0] + 1].astype(int) return CheckResult(len(steps) == 0, steps)
[ "def", "has_sequential_ids", "(", "data_wrapper", ")", ":", "db", "=", "data_wrapper", ".", "data_block", "ids", "=", "db", "[", ":", ",", "COLS", ".", "ID", "]", "steps", "=", "ids", "[", "np", ".", "where", "(", "np", ".", "diff", "(", "ids", ")", "!=", "1", ")", "[", "0", "]", "+", "1", "]", ".", "astype", "(", "int", ")", "return", "CheckResult", "(", "len", "(", "steps", ")", "==", "0", ",", "steps", ")" ]
Check that IDs are increasing and consecutive returns tuple (bool, list of IDs that are not consecutive with their predecessor)
[ "Check", "that", "IDs", "are", "increasing", "and", "consecutive" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L39-L48
2,594
BlueBrain/NeuroM
neurom/check/structural_checks.py
no_missing_parents
def no_missing_parents(data_wrapper): '''Check that all points have existing parents Point's parent ID must exist and parent must be declared before child. Returns: CheckResult with result and list of IDs that have no parent ''' db = data_wrapper.data_block ids = np.setdiff1d(db[:, COLS.P], db[:, COLS.ID])[1:] return CheckResult(len(ids) == 0, ids.astype(np.int) + 1)
python
def no_missing_parents(data_wrapper): '''Check that all points have existing parents Point's parent ID must exist and parent must be declared before child. Returns: CheckResult with result and list of IDs that have no parent ''' db = data_wrapper.data_block ids = np.setdiff1d(db[:, COLS.P], db[:, COLS.ID])[1:] return CheckResult(len(ids) == 0, ids.astype(np.int) + 1)
[ "def", "no_missing_parents", "(", "data_wrapper", ")", ":", "db", "=", "data_wrapper", ".", "data_block", "ids", "=", "np", ".", "setdiff1d", "(", "db", "[", ":", ",", "COLS", ".", "P", "]", ",", "db", "[", ":", ",", "COLS", ".", "ID", "]", ")", "[", "1", ":", "]", "return", "CheckResult", "(", "len", "(", "ids", ")", "==", "0", ",", "ids", ".", "astype", "(", "np", ".", "int", ")", "+", "1", ")" ]
Check that all points have existing parents Point's parent ID must exist and parent must be declared before child. Returns: CheckResult with result and list of IDs that have no parent
[ "Check", "that", "all", "points", "have", "existing", "parents", "Point", "s", "parent", "ID", "must", "exist", "and", "parent", "must", "be", "declared", "before", "child", "." ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L51-L61
2,595
BlueBrain/NeuroM
neurom/check/structural_checks.py
is_single_tree
def is_single_tree(data_wrapper): '''Check that data forms a single tree Only the first point has ID of -1. Returns: CheckResult with result and list of IDs Note: This assumes no_missing_parents passed. ''' db = data_wrapper.data_block bad_ids = db[db[:, COLS.P] == -1][1:, COLS.ID] return CheckResult(len(bad_ids) == 0, bad_ids.tolist())
python
def is_single_tree(data_wrapper): '''Check that data forms a single tree Only the first point has ID of -1. Returns: CheckResult with result and list of IDs Note: This assumes no_missing_parents passed. ''' db = data_wrapper.data_block bad_ids = db[db[:, COLS.P] == -1][1:, COLS.ID] return CheckResult(len(bad_ids) == 0, bad_ids.tolist())
[ "def", "is_single_tree", "(", "data_wrapper", ")", ":", "db", "=", "data_wrapper", ".", "data_block", "bad_ids", "=", "db", "[", "db", "[", ":", ",", "COLS", ".", "P", "]", "==", "-", "1", "]", "[", "1", ":", ",", "COLS", ".", "ID", "]", "return", "CheckResult", "(", "len", "(", "bad_ids", ")", "==", "0", ",", "bad_ids", ".", "tolist", "(", ")", ")" ]
Check that data forms a single tree Only the first point has ID of -1. Returns: CheckResult with result and list of IDs Note: This assumes no_missing_parents passed.
[ "Check", "that", "data", "forms", "a", "single", "tree" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L64-L77
2,596
BlueBrain/NeuroM
neurom/check/structural_checks.py
has_soma_points
def has_soma_points(data_wrapper): '''Checks if the TYPE column of raw data block has an element of type soma Returns: CheckResult with result ''' db = data_wrapper.data_block return CheckResult(POINT_TYPE.SOMA in db[:, COLS.TYPE], None)
python
def has_soma_points(data_wrapper): '''Checks if the TYPE column of raw data block has an element of type soma Returns: CheckResult with result ''' db = data_wrapper.data_block return CheckResult(POINT_TYPE.SOMA in db[:, COLS.TYPE], None)
[ "def", "has_soma_points", "(", "data_wrapper", ")", ":", "db", "=", "data_wrapper", ".", "data_block", "return", "CheckResult", "(", "POINT_TYPE", ".", "SOMA", "in", "db", "[", ":", ",", "COLS", ".", "TYPE", "]", ",", "None", ")" ]
Checks if the TYPE column of raw data block has an element of type soma Returns: CheckResult with result
[ "Checks", "if", "the", "TYPE", "column", "of", "raw", "data", "block", "has", "an", "element", "of", "type", "soma" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L93-L100
2,597
BlueBrain/NeuroM
neurom/check/structural_checks.py
has_all_finite_radius_neurites
def has_all_finite_radius_neurites(data_wrapper, threshold=0.0): '''Check that all points with neurite type have a finite radius Returns: CheckResult with result and list of IDs of neurite points with zero radius ''' db = data_wrapper.data_block neurite_ids = np.in1d(db[:, COLS.TYPE], POINT_TYPE.NEURITES) zero_radius_ids = db[:, COLS.R] <= threshold bad_pts = np.array(db[neurite_ids & zero_radius_ids][:, COLS.ID], dtype=int).tolist() return CheckResult(len(bad_pts) == 0, bad_pts)
python
def has_all_finite_radius_neurites(data_wrapper, threshold=0.0): '''Check that all points with neurite type have a finite radius Returns: CheckResult with result and list of IDs of neurite points with zero radius ''' db = data_wrapper.data_block neurite_ids = np.in1d(db[:, COLS.TYPE], POINT_TYPE.NEURITES) zero_radius_ids = db[:, COLS.R] <= threshold bad_pts = np.array(db[neurite_ids & zero_radius_ids][:, COLS.ID], dtype=int).tolist() return CheckResult(len(bad_pts) == 0, bad_pts)
[ "def", "has_all_finite_radius_neurites", "(", "data_wrapper", ",", "threshold", "=", "0.0", ")", ":", "db", "=", "data_wrapper", ".", "data_block", "neurite_ids", "=", "np", ".", "in1d", "(", "db", "[", ":", ",", "COLS", ".", "TYPE", "]", ",", "POINT_TYPE", ".", "NEURITES", ")", "zero_radius_ids", "=", "db", "[", ":", ",", "COLS", ".", "R", "]", "<=", "threshold", "bad_pts", "=", "np", ".", "array", "(", "db", "[", "neurite_ids", "&", "zero_radius_ids", "]", "[", ":", ",", "COLS", ".", "ID", "]", ",", "dtype", "=", "int", ")", ".", "tolist", "(", ")", "return", "CheckResult", "(", "len", "(", "bad_pts", ")", "==", "0", ",", "bad_pts", ")" ]
Check that all points with neurite type have a finite radius Returns: CheckResult with result and list of IDs of neurite points with zero radius
[ "Check", "that", "all", "points", "with", "neurite", "type", "have", "a", "finite", "radius" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L103-L114
2,598
BlueBrain/NeuroM
neurom/check/structural_checks.py
has_valid_soma
def has_valid_soma(data_wrapper): '''Check if a data block has a valid soma Returns: CheckResult with result ''' try: make_soma(data_wrapper.soma_points()) return CheckResult(True) except SomaError: return CheckResult(False)
python
def has_valid_soma(data_wrapper): '''Check if a data block has a valid soma Returns: CheckResult with result ''' try: make_soma(data_wrapper.soma_points()) return CheckResult(True) except SomaError: return CheckResult(False)
[ "def", "has_valid_soma", "(", "data_wrapper", ")", ":", "try", ":", "make_soma", "(", "data_wrapper", ".", "soma_points", "(", ")", ")", "return", "CheckResult", "(", "True", ")", "except", "SomaError", ":", "return", "CheckResult", "(", "False", ")" ]
Check if a data block has a valid soma Returns: CheckResult with result
[ "Check", "if", "a", "data", "block", "has", "a", "valid", "soma" ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L117-L127
2,599
BlueBrain/NeuroM
doc/source/conf.py
_pelita_member_filter
def _pelita_member_filter(parent_name, item_names): """ Filter a list of autodoc items for which to generate documentation. Include only imports that come from the documented module or its submodules. """ filtered_names = [] if parent_name not in sys.modules: return item_names module = sys.modules[parent_name] for item_name in item_names: item = getattr(module, item_name, None) location = getattr(item, '__module__', None) if location is None or (location + ".").startswith(parent_name + "."): filtered_names.append(item_name) return filtered_names
python
def _pelita_member_filter(parent_name, item_names): """ Filter a list of autodoc items for which to generate documentation. Include only imports that come from the documented module or its submodules. """ filtered_names = [] if parent_name not in sys.modules: return item_names module = sys.modules[parent_name] for item_name in item_names: item = getattr(module, item_name, None) location = getattr(item, '__module__', None) if location is None or (location + ".").startswith(parent_name + "."): filtered_names.append(item_name) return filtered_names
[ "def", "_pelita_member_filter", "(", "parent_name", ",", "item_names", ")", ":", "filtered_names", "=", "[", "]", "if", "parent_name", "not", "in", "sys", ".", "modules", ":", "return", "item_names", "module", "=", "sys", ".", "modules", "[", "parent_name", "]", "for", "item_name", "in", "item_names", ":", "item", "=", "getattr", "(", "module", ",", "item_name", ",", "None", ")", "location", "=", "getattr", "(", "item", ",", "'__module__'", ",", "None", ")", "if", "location", "is", "None", "or", "(", "location", "+", "\".\"", ")", ".", "startswith", "(", "parent_name", "+", "\".\"", ")", ":", "filtered_names", ".", "append", "(", "item_name", ")", "return", "filtered_names" ]
Filter a list of autodoc items for which to generate documentation. Include only imports that come from the documented module or its submodules.
[ "Filter", "a", "list", "of", "autodoc", "items", "for", "which", "to", "generate", "documentation", "." ]
254bb73535b20053d175bc4725bade662177d12b
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/doc/source/conf.py#L158-L179