body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
fca6cf70a6d7fbd1d10578387b0b0d8562dfb058f5bf919899c3f93bf7d2346a
def build_transaction(self, tokens_to_wrap: List[ITokenBundleToken], uri_for_wrapped_token: str, recipient: str, tx_params: Optional[TxParams]=None) -> dict: 'Construct calldata to be used as input to the method.' (tokens_to_wrap, uri_for_wrapped_token, recipient) = self.validate_and_normalize_inputs(tokens_to_wrap, uri_for_wrapped_token, recipient) tx_params = super().normalize_tx_params(tx_params) return self._underlying_method(tokens_to_wrap, uri_for_wrapped_token, recipient).buildTransaction(tx_params.as_dict())
Construct calldata to be used as input to the method.
thirdweb/abi/multiwrap.py
build_transaction
nftlabs/nftlabs-sdk-python
30
python
def build_transaction(self, tokens_to_wrap: List[ITokenBundleToken], uri_for_wrapped_token: str, recipient: str, tx_params: Optional[TxParams]=None) -> dict: (tokens_to_wrap, uri_for_wrapped_token, recipient) = self.validate_and_normalize_inputs(tokens_to_wrap, uri_for_wrapped_token, recipient) tx_params = super().normalize_tx_params(tx_params) return self._underlying_method(tokens_to_wrap, uri_for_wrapped_token, recipient).buildTransaction(tx_params.as_dict())
def build_transaction(self, tokens_to_wrap: List[ITokenBundleToken], uri_for_wrapped_token: str, recipient: str, tx_params: Optional[TxParams]=None) -> dict: (tokens_to_wrap, uri_for_wrapped_token, recipient) = self.validate_and_normalize_inputs(tokens_to_wrap, uri_for_wrapped_token, recipient) tx_params = super().normalize_tx_params(tx_params) return self._underlying_method(tokens_to_wrap, uri_for_wrapped_token, recipient).buildTransaction(tx_params.as_dict())<|docstring|>Construct calldata to be used as input to the method.<|endoftext|>
2f892c323993d84917535c0b82aac3233f494eb0c70ec4874141cbf1a69f7317
def estimate_gas(self, tokens_to_wrap: List[ITokenBundleToken], uri_for_wrapped_token: str, recipient: str, tx_params: Optional[TxParams]=None) -> int: 'Estimate gas consumption of method call.' (tokens_to_wrap, uri_for_wrapped_token, recipient) = self.validate_and_normalize_inputs(tokens_to_wrap, uri_for_wrapped_token, recipient) tx_params = super().normalize_tx_params(tx_params) return self._underlying_method(tokens_to_wrap, uri_for_wrapped_token, recipient).estimateGas(tx_params.as_dict())
Estimate gas consumption of method call.
thirdweb/abi/multiwrap.py
estimate_gas
nftlabs/nftlabs-sdk-python
30
python
def estimate_gas(self, tokens_to_wrap: List[ITokenBundleToken], uri_for_wrapped_token: str, recipient: str, tx_params: Optional[TxParams]=None) -> int: (tokens_to_wrap, uri_for_wrapped_token, recipient) = self.validate_and_normalize_inputs(tokens_to_wrap, uri_for_wrapped_token, recipient) tx_params = super().normalize_tx_params(tx_params) return self._underlying_method(tokens_to_wrap, uri_for_wrapped_token, recipient).estimateGas(tx_params.as_dict())
def estimate_gas(self, tokens_to_wrap: List[ITokenBundleToken], uri_for_wrapped_token: str, recipient: str, tx_params: Optional[TxParams]=None) -> int: (tokens_to_wrap, uri_for_wrapped_token, recipient) = self.validate_and_normalize_inputs(tokens_to_wrap, uri_for_wrapped_token, recipient) tx_params = super().normalize_tx_params(tx_params) return self._underlying_method(tokens_to_wrap, uri_for_wrapped_token, recipient).estimateGas(tx_params.as_dict())<|docstring|>Estimate gas consumption of method call.<|endoftext|>
5be96e16dcd15ae31233b2fce25711abf14a9605d5a89fe1356a65a73a7a80a6
def __init__(self, web3_or_provider: Union[(Web3, BaseProvider)], contract_address: str, validator: MultiwrapValidator=None): 'Get an instance of wrapper for smart contract.\n\n :param web3_or_provider: Either an instance of `web3.Web3`:code: or\n `web3.providers.base.BaseProvider`:code:\n :param contract_address: where the contract has been deployed\n :param validator: for validation of method inputs.\n ' self.contract_address = contract_address if (not validator): validator = MultiwrapValidator(web3_or_provider, contract_address) web3 = None if isinstance(web3_or_provider, BaseProvider): web3 = Web3(web3_or_provider) elif isinstance(web3_or_provider, Web3): web3 = web3_or_provider else: raise TypeError(("Expected parameter 'web3_or_provider' to be an instance of either" + ' Web3 or BaseProvider')) try: MIDDLEWARE except NameError: pass else: try: for middleware in MIDDLEWARE: web3.middleware_onion.inject(middleware['function'], layer=middleware['layer']) except ValueError as value_error: if (value_error.args == ("You can't add the same un-named instance twice",)): pass self._web3_eth = web3.eth functions = self._web3_eth.contract(address=to_checksum_address(contract_address), abi=Multiwrap.abi()).functions self.default_admin_role = DefaultAdminRoleMethod(web3_or_provider, contract_address, functions.DEFAULT_ADMIN_ROLE) self.approve = ApproveMethod(web3_or_provider, contract_address, functions.approve, validator) self.balance_of = BalanceOfMethod(web3_or_provider, contract_address, functions.balanceOf, validator) self.contract_type = ContractTypeMethod(web3_or_provider, contract_address, functions.contractType) self.contract_uri = ContractUriMethod(web3_or_provider, contract_address, functions.contractURI) self.contract_version = ContractVersionMethod(web3_or_provider, contract_address, functions.contractVersion) self.get_approved = GetApprovedMethod(web3_or_provider, contract_address, functions.getApproved, validator) self.get_default_royalty_info = GetDefaultRoyaltyInfoMethod(web3_or_provider, contract_address, functions.getDefaultRoyaltyInfo) self.get_role_admin = GetRoleAdminMethod(web3_or_provider, contract_address, functions.getRoleAdmin, validator) self.get_role_member = GetRoleMemberMethod(web3_or_provider, contract_address, functions.getRoleMember, validator) self.get_role_member_count = GetRoleMemberCountMethod(web3_or_provider, contract_address, functions.getRoleMemberCount, validator) self.get_royalty_info_for_token = GetRoyaltyInfoForTokenMethod(web3_or_provider, contract_address, functions.getRoyaltyInfoForToken, validator) self.get_token_count_of_bundle = GetTokenCountOfBundleMethod(web3_or_provider, contract_address, functions.getTokenCountOfBundle, validator) self.get_token_of_bundle = GetTokenOfBundleMethod(web3_or_provider, contract_address, functions.getTokenOfBundle, validator) self.get_uri_of_bundle = GetUriOfBundleMethod(web3_or_provider, contract_address, functions.getUriOfBundle, validator) self.get_wrapped_contents = GetWrappedContentsMethod(web3_or_provider, contract_address, functions.getWrappedContents, validator) self.grant_role = GrantRoleMethod(web3_or_provider, contract_address, functions.grantRole, validator) self.has_role = HasRoleMethod(web3_or_provider, contract_address, functions.hasRole, validator) self.has_role_with_switch = HasRoleWithSwitchMethod(web3_or_provider, contract_address, functions.hasRoleWithSwitch, validator) self.initialize = InitializeMethod(web3_or_provider, contract_address, functions.initialize, validator) self.is_approved_for_all = IsApprovedForAllMethod(web3_or_provider, contract_address, functions.isApprovedForAll, validator) self.is_trusted_forwarder = IsTrustedForwarderMethod(web3_or_provider, contract_address, functions.isTrustedForwarder, validator) self.multicall = MulticallMethod(web3_or_provider, contract_address, functions.multicall, validator) self.name = NameMethod(web3_or_provider, contract_address, functions.name) self.next_token_id_to_mint = NextTokenIdToMintMethod(web3_or_provider, contract_address, functions.nextTokenIdToMint) self.on_erc1155_batch_received = OnErc1155BatchReceivedMethod(web3_or_provider, contract_address, functions.onERC1155BatchReceived, validator) self.on_erc1155_received = OnErc1155ReceivedMethod(web3_or_provider, contract_address, functions.onERC1155Received, validator) self.on_erc721_received = OnErc721ReceivedMethod(web3_or_provider, contract_address, functions.onERC721Received, validator) self.owner = OwnerMethod(web3_or_provider, contract_address, functions.owner) self.owner_of = OwnerOfMethod(web3_or_provider, contract_address, functions.ownerOf, validator) self.renounce_role = RenounceRoleMethod(web3_or_provider, contract_address, functions.renounceRole, validator) self.revoke_role = RevokeRoleMethod(web3_or_provider, contract_address, functions.revokeRole, validator) self.royalty_info = RoyaltyInfoMethod(web3_or_provider, contract_address, functions.royaltyInfo, validator) self.safe_transfer_from1 = SafeTransferFrom1Method(web3_or_provider, contract_address, functions.safeTransferFrom, validator) self.safe_transfer_from2 = SafeTransferFrom2Method(web3_or_provider, contract_address, functions.safeTransferFrom, validator) self.set_approval_for_all = SetApprovalForAllMethod(web3_or_provider, contract_address, functions.setApprovalForAll, validator) self.set_contract_uri = SetContractUriMethod(web3_or_provider, contract_address, functions.setContractURI, validator) self.set_default_royalty_info = SetDefaultRoyaltyInfoMethod(web3_or_provider, contract_address, functions.setDefaultRoyaltyInfo, validator) self.set_owner = SetOwnerMethod(web3_or_provider, contract_address, functions.setOwner, validator) self.set_royalty_info_for_token = SetRoyaltyInfoForTokenMethod(web3_or_provider, contract_address, functions.setRoyaltyInfoForToken, validator) self.supports_interface = SupportsInterfaceMethod(web3_or_provider, contract_address, functions.supportsInterface, validator) self.symbol = SymbolMethod(web3_or_provider, contract_address, functions.symbol) self.token_uri = TokenUriMethod(web3_or_provider, contract_address, functions.tokenURI, validator) self.transfer_from = TransferFromMethod(web3_or_provider, contract_address, functions.transferFrom, validator) self.unwrap = UnwrapMethod(web3_or_provider, contract_address, functions.unwrap, validator) self.wrap = WrapMethod(web3_or_provider, contract_address, functions.wrap, validator)
Get an instance of wrapper for smart contract. :param web3_or_provider: Either an instance of `web3.Web3`:code: or `web3.providers.base.BaseProvider`:code: :param contract_address: where the contract has been deployed :param validator: for validation of method inputs.
thirdweb/abi/multiwrap.py
__init__
nftlabs/nftlabs-sdk-python
30
python
def __init__(self, web3_or_provider: Union[(Web3, BaseProvider)], contract_address: str, validator: MultiwrapValidator=None): 'Get an instance of wrapper for smart contract.\n\n :param web3_or_provider: Either an instance of `web3.Web3`:code: or\n `web3.providers.base.BaseProvider`:code:\n :param contract_address: where the contract has been deployed\n :param validator: for validation of method inputs.\n ' self.contract_address = contract_address if (not validator): validator = MultiwrapValidator(web3_or_provider, contract_address) web3 = None if isinstance(web3_or_provider, BaseProvider): web3 = Web3(web3_or_provider) elif isinstance(web3_or_provider, Web3): web3 = web3_or_provider else: raise TypeError(("Expected parameter 'web3_or_provider' to be an instance of either" + ' Web3 or BaseProvider')) try: MIDDLEWARE except NameError: pass else: try: for middleware in MIDDLEWARE: web3.middleware_onion.inject(middleware['function'], layer=middleware['layer']) except ValueError as value_error: if (value_error.args == ("You can't add the same un-named instance twice",)): pass self._web3_eth = web3.eth functions = self._web3_eth.contract(address=to_checksum_address(contract_address), abi=Multiwrap.abi()).functions self.default_admin_role = DefaultAdminRoleMethod(web3_or_provider, contract_address, functions.DEFAULT_ADMIN_ROLE) self.approve = ApproveMethod(web3_or_provider, contract_address, functions.approve, validator) self.balance_of = BalanceOfMethod(web3_or_provider, contract_address, functions.balanceOf, validator) self.contract_type = ContractTypeMethod(web3_or_provider, contract_address, functions.contractType) self.contract_uri = ContractUriMethod(web3_or_provider, contract_address, functions.contractURI) self.contract_version = ContractVersionMethod(web3_or_provider, contract_address, functions.contractVersion) self.get_approved = GetApprovedMethod(web3_or_provider, contract_address, functions.getApproved, validator) self.get_default_royalty_info = GetDefaultRoyaltyInfoMethod(web3_or_provider, contract_address, functions.getDefaultRoyaltyInfo) self.get_role_admin = GetRoleAdminMethod(web3_or_provider, contract_address, functions.getRoleAdmin, validator) self.get_role_member = GetRoleMemberMethod(web3_or_provider, contract_address, functions.getRoleMember, validator) self.get_role_member_count = GetRoleMemberCountMethod(web3_or_provider, contract_address, functions.getRoleMemberCount, validator) self.get_royalty_info_for_token = GetRoyaltyInfoForTokenMethod(web3_or_provider, contract_address, functions.getRoyaltyInfoForToken, validator) self.get_token_count_of_bundle = GetTokenCountOfBundleMethod(web3_or_provider, contract_address, functions.getTokenCountOfBundle, validator) self.get_token_of_bundle = GetTokenOfBundleMethod(web3_or_provider, contract_address, functions.getTokenOfBundle, validator) self.get_uri_of_bundle = GetUriOfBundleMethod(web3_or_provider, contract_address, functions.getUriOfBundle, validator) self.get_wrapped_contents = GetWrappedContentsMethod(web3_or_provider, contract_address, functions.getWrappedContents, validator) self.grant_role = GrantRoleMethod(web3_or_provider, contract_address, functions.grantRole, validator) self.has_role = HasRoleMethod(web3_or_provider, contract_address, functions.hasRole, validator) self.has_role_with_switch = HasRoleWithSwitchMethod(web3_or_provider, contract_address, functions.hasRoleWithSwitch, validator) self.initialize = InitializeMethod(web3_or_provider, contract_address, functions.initialize, validator) self.is_approved_for_all = IsApprovedForAllMethod(web3_or_provider, contract_address, functions.isApprovedForAll, validator) self.is_trusted_forwarder = IsTrustedForwarderMethod(web3_or_provider, contract_address, functions.isTrustedForwarder, validator) self.multicall = MulticallMethod(web3_or_provider, contract_address, functions.multicall, validator) self.name = NameMethod(web3_or_provider, contract_address, functions.name) self.next_token_id_to_mint = NextTokenIdToMintMethod(web3_or_provider, contract_address, functions.nextTokenIdToMint) self.on_erc1155_batch_received = OnErc1155BatchReceivedMethod(web3_or_provider, contract_address, functions.onERC1155BatchReceived, validator) self.on_erc1155_received = OnErc1155ReceivedMethod(web3_or_provider, contract_address, functions.onERC1155Received, validator) self.on_erc721_received = OnErc721ReceivedMethod(web3_or_provider, contract_address, functions.onERC721Received, validator) self.owner = OwnerMethod(web3_or_provider, contract_address, functions.owner) self.owner_of = OwnerOfMethod(web3_or_provider, contract_address, functions.ownerOf, validator) self.renounce_role = RenounceRoleMethod(web3_or_provider, contract_address, functions.renounceRole, validator) self.revoke_role = RevokeRoleMethod(web3_or_provider, contract_address, functions.revokeRole, validator) self.royalty_info = RoyaltyInfoMethod(web3_or_provider, contract_address, functions.royaltyInfo, validator) self.safe_transfer_from1 = SafeTransferFrom1Method(web3_or_provider, contract_address, functions.safeTransferFrom, validator) self.safe_transfer_from2 = SafeTransferFrom2Method(web3_or_provider, contract_address, functions.safeTransferFrom, validator) self.set_approval_for_all = SetApprovalForAllMethod(web3_or_provider, contract_address, functions.setApprovalForAll, validator) self.set_contract_uri = SetContractUriMethod(web3_or_provider, contract_address, functions.setContractURI, validator) self.set_default_royalty_info = SetDefaultRoyaltyInfoMethod(web3_or_provider, contract_address, functions.setDefaultRoyaltyInfo, validator) self.set_owner = SetOwnerMethod(web3_or_provider, contract_address, functions.setOwner, validator) self.set_royalty_info_for_token = SetRoyaltyInfoForTokenMethod(web3_or_provider, contract_address, functions.setRoyaltyInfoForToken, validator) self.supports_interface = SupportsInterfaceMethod(web3_or_provider, contract_address, functions.supportsInterface, validator) self.symbol = SymbolMethod(web3_or_provider, contract_address, functions.symbol) self.token_uri = TokenUriMethod(web3_or_provider, contract_address, functions.tokenURI, validator) self.transfer_from = TransferFromMethod(web3_or_provider, contract_address, functions.transferFrom, validator) self.unwrap = UnwrapMethod(web3_or_provider, contract_address, functions.unwrap, validator) self.wrap = WrapMethod(web3_or_provider, contract_address, functions.wrap, validator)
def __init__(self, web3_or_provider: Union[(Web3, BaseProvider)], contract_address: str, validator: MultiwrapValidator=None): 'Get an instance of wrapper for smart contract.\n\n :param web3_or_provider: Either an instance of `web3.Web3`:code: or\n `web3.providers.base.BaseProvider`:code:\n :param contract_address: where the contract has been deployed\n :param validator: for validation of method inputs.\n ' self.contract_address = contract_address if (not validator): validator = MultiwrapValidator(web3_or_provider, contract_address) web3 = None if isinstance(web3_or_provider, BaseProvider): web3 = Web3(web3_or_provider) elif isinstance(web3_or_provider, Web3): web3 = web3_or_provider else: raise TypeError(("Expected parameter 'web3_or_provider' to be an instance of either" + ' Web3 or BaseProvider')) try: MIDDLEWARE except NameError: pass else: try: for middleware in MIDDLEWARE: web3.middleware_onion.inject(middleware['function'], layer=middleware['layer']) except ValueError as value_error: if (value_error.args == ("You can't add the same un-named instance twice",)): pass self._web3_eth = web3.eth functions = self._web3_eth.contract(address=to_checksum_address(contract_address), abi=Multiwrap.abi()).functions self.default_admin_role = DefaultAdminRoleMethod(web3_or_provider, contract_address, functions.DEFAULT_ADMIN_ROLE) self.approve = ApproveMethod(web3_or_provider, contract_address, functions.approve, validator) self.balance_of = BalanceOfMethod(web3_or_provider, contract_address, functions.balanceOf, validator) self.contract_type = ContractTypeMethod(web3_or_provider, contract_address, functions.contractType) self.contract_uri = ContractUriMethod(web3_or_provider, contract_address, functions.contractURI) self.contract_version = ContractVersionMethod(web3_or_provider, contract_address, functions.contractVersion) self.get_approved = GetApprovedMethod(web3_or_provider, contract_address, functions.getApproved, validator) self.get_default_royalty_info = GetDefaultRoyaltyInfoMethod(web3_or_provider, contract_address, functions.getDefaultRoyaltyInfo) self.get_role_admin = GetRoleAdminMethod(web3_or_provider, contract_address, functions.getRoleAdmin, validator) self.get_role_member = GetRoleMemberMethod(web3_or_provider, contract_address, functions.getRoleMember, validator) self.get_role_member_count = GetRoleMemberCountMethod(web3_or_provider, contract_address, functions.getRoleMemberCount, validator) self.get_royalty_info_for_token = GetRoyaltyInfoForTokenMethod(web3_or_provider, contract_address, functions.getRoyaltyInfoForToken, validator) self.get_token_count_of_bundle = GetTokenCountOfBundleMethod(web3_or_provider, contract_address, functions.getTokenCountOfBundle, validator) self.get_token_of_bundle = GetTokenOfBundleMethod(web3_or_provider, contract_address, functions.getTokenOfBundle, validator) self.get_uri_of_bundle = GetUriOfBundleMethod(web3_or_provider, contract_address, functions.getUriOfBundle, validator) self.get_wrapped_contents = GetWrappedContentsMethod(web3_or_provider, contract_address, functions.getWrappedContents, validator) self.grant_role = GrantRoleMethod(web3_or_provider, contract_address, functions.grantRole, validator) self.has_role = HasRoleMethod(web3_or_provider, contract_address, functions.hasRole, validator) self.has_role_with_switch = HasRoleWithSwitchMethod(web3_or_provider, contract_address, functions.hasRoleWithSwitch, validator) self.initialize = InitializeMethod(web3_or_provider, contract_address, functions.initialize, validator) self.is_approved_for_all = IsApprovedForAllMethod(web3_or_provider, contract_address, functions.isApprovedForAll, validator) self.is_trusted_forwarder = IsTrustedForwarderMethod(web3_or_provider, contract_address, functions.isTrustedForwarder, validator) self.multicall = MulticallMethod(web3_or_provider, contract_address, functions.multicall, validator) self.name = NameMethod(web3_or_provider, contract_address, functions.name) self.next_token_id_to_mint = NextTokenIdToMintMethod(web3_or_provider, contract_address, functions.nextTokenIdToMint) self.on_erc1155_batch_received = OnErc1155BatchReceivedMethod(web3_or_provider, contract_address, functions.onERC1155BatchReceived, validator) self.on_erc1155_received = OnErc1155ReceivedMethod(web3_or_provider, contract_address, functions.onERC1155Received, validator) self.on_erc721_received = OnErc721ReceivedMethod(web3_or_provider, contract_address, functions.onERC721Received, validator) self.owner = OwnerMethod(web3_or_provider, contract_address, functions.owner) self.owner_of = OwnerOfMethod(web3_or_provider, contract_address, functions.ownerOf, validator) self.renounce_role = RenounceRoleMethod(web3_or_provider, contract_address, functions.renounceRole, validator) self.revoke_role = RevokeRoleMethod(web3_or_provider, contract_address, functions.revokeRole, validator) self.royalty_info = RoyaltyInfoMethod(web3_or_provider, contract_address, functions.royaltyInfo, validator) self.safe_transfer_from1 = SafeTransferFrom1Method(web3_or_provider, contract_address, functions.safeTransferFrom, validator) self.safe_transfer_from2 = SafeTransferFrom2Method(web3_or_provider, contract_address, functions.safeTransferFrom, validator) self.set_approval_for_all = SetApprovalForAllMethod(web3_or_provider, contract_address, functions.setApprovalForAll, validator) self.set_contract_uri = SetContractUriMethod(web3_or_provider, contract_address, functions.setContractURI, validator) self.set_default_royalty_info = SetDefaultRoyaltyInfoMethod(web3_or_provider, contract_address, functions.setDefaultRoyaltyInfo, validator) self.set_owner = SetOwnerMethod(web3_or_provider, contract_address, functions.setOwner, validator) self.set_royalty_info_for_token = SetRoyaltyInfoForTokenMethod(web3_or_provider, contract_address, functions.setRoyaltyInfoForToken, validator) self.supports_interface = SupportsInterfaceMethod(web3_or_provider, contract_address, functions.supportsInterface, validator) self.symbol = SymbolMethod(web3_or_provider, contract_address, functions.symbol) self.token_uri = TokenUriMethod(web3_or_provider, contract_address, functions.tokenURI, validator) self.transfer_from = TransferFromMethod(web3_or_provider, contract_address, functions.transferFrom, validator) self.unwrap = UnwrapMethod(web3_or_provider, contract_address, functions.unwrap, validator) self.wrap = WrapMethod(web3_or_provider, contract_address, functions.wrap, validator)<|docstring|>Get an instance of wrapper for smart contract. :param web3_or_provider: Either an instance of `web3.Web3`:code: or `web3.providers.base.BaseProvider`:code: :param contract_address: where the contract has been deployed :param validator: for validation of method inputs.<|endoftext|>
dd22877dc55dfaaf775c3dfa7353c9d5f7af975284c2ac94d902859f548312f3
def get_approval_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for Approval event.\n\n :param tx_hash: hash of transaction emitting Approval event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.Approval().processReceipt(tx_receipt)
Get log entry for Approval event. :param tx_hash: hash of transaction emitting Approval event
thirdweb/abi/multiwrap.py
get_approval_event
nftlabs/nftlabs-sdk-python
30
python
def get_approval_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for Approval event.\n\n :param tx_hash: hash of transaction emitting Approval event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.Approval().processReceipt(tx_receipt)
def get_approval_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for Approval event.\n\n :param tx_hash: hash of transaction emitting Approval event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.Approval().processReceipt(tx_receipt)<|docstring|>Get log entry for Approval event. :param tx_hash: hash of transaction emitting Approval event<|endoftext|>
2285ce7f1c963f78b0d0f1bf5229cd33ab8caf8f5757d87ed84b783397c2ea2f
def get_approval_for_all_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for ApprovalForAll event.\n\n :param tx_hash: hash of transaction emitting ApprovalForAll event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.ApprovalForAll().processReceipt(tx_receipt)
Get log entry for ApprovalForAll event. :param tx_hash: hash of transaction emitting ApprovalForAll event
thirdweb/abi/multiwrap.py
get_approval_for_all_event
nftlabs/nftlabs-sdk-python
30
python
def get_approval_for_all_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for ApprovalForAll event.\n\n :param tx_hash: hash of transaction emitting ApprovalForAll event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.ApprovalForAll().processReceipt(tx_receipt)
def get_approval_for_all_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for ApprovalForAll event.\n\n :param tx_hash: hash of transaction emitting ApprovalForAll event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.ApprovalForAll().processReceipt(tx_receipt)<|docstring|>Get log entry for ApprovalForAll event. :param tx_hash: hash of transaction emitting ApprovalForAll event<|endoftext|>
3b349ae729928ec69ad68f610610383d2c1a14d3dea286ef87c56027f6f487d6
def get_contract_uri_updated_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for ContractURIUpdated event.\n\n :param tx_hash: hash of transaction emitting ContractURIUpdated event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.ContractURIUpdated().processReceipt(tx_receipt)
Get log entry for ContractURIUpdated event. :param tx_hash: hash of transaction emitting ContractURIUpdated event
thirdweb/abi/multiwrap.py
get_contract_uri_updated_event
nftlabs/nftlabs-sdk-python
30
python
def get_contract_uri_updated_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for ContractURIUpdated event.\n\n :param tx_hash: hash of transaction emitting ContractURIUpdated event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.ContractURIUpdated().processReceipt(tx_receipt)
def get_contract_uri_updated_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for ContractURIUpdated event.\n\n :param tx_hash: hash of transaction emitting ContractURIUpdated event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.ContractURIUpdated().processReceipt(tx_receipt)<|docstring|>Get log entry for ContractURIUpdated event. :param tx_hash: hash of transaction emitting ContractURIUpdated event<|endoftext|>
28fe9ab2275ca867c791324fd8c4a9c33d490285382a37aa3881c3e5d191d775
def get_default_royalty_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for DefaultRoyalty event.\n\n :param tx_hash: hash of transaction emitting DefaultRoyalty event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.DefaultRoyalty().processReceipt(tx_receipt)
Get log entry for DefaultRoyalty event. :param tx_hash: hash of transaction emitting DefaultRoyalty event
thirdweb/abi/multiwrap.py
get_default_royalty_event
nftlabs/nftlabs-sdk-python
30
python
def get_default_royalty_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for DefaultRoyalty event.\n\n :param tx_hash: hash of transaction emitting DefaultRoyalty event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.DefaultRoyalty().processReceipt(tx_receipt)
def get_default_royalty_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for DefaultRoyalty event.\n\n :param tx_hash: hash of transaction emitting DefaultRoyalty event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.DefaultRoyalty().processReceipt(tx_receipt)<|docstring|>Get log entry for DefaultRoyalty event. :param tx_hash: hash of transaction emitting DefaultRoyalty event<|endoftext|>
08626ca22ee62846505e77fce7b27dd72386e9d3fe3d63dceff10690dba50d62
def get_owner_updated_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for OwnerUpdated event.\n\n :param tx_hash: hash of transaction emitting OwnerUpdated event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.OwnerUpdated().processReceipt(tx_receipt)
Get log entry for OwnerUpdated event. :param tx_hash: hash of transaction emitting OwnerUpdated event
thirdweb/abi/multiwrap.py
get_owner_updated_event
nftlabs/nftlabs-sdk-python
30
python
def get_owner_updated_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for OwnerUpdated event.\n\n :param tx_hash: hash of transaction emitting OwnerUpdated event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.OwnerUpdated().processReceipt(tx_receipt)
def get_owner_updated_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for OwnerUpdated event.\n\n :param tx_hash: hash of transaction emitting OwnerUpdated event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.OwnerUpdated().processReceipt(tx_receipt)<|docstring|>Get log entry for OwnerUpdated event. :param tx_hash: hash of transaction emitting OwnerUpdated event<|endoftext|>
01614399129aa7d8f47ded10947dfea8ccf3f139c0b413f23e7cf89b6f426776
def get_role_admin_changed_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for RoleAdminChanged event.\n\n :param tx_hash: hash of transaction emitting RoleAdminChanged event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.RoleAdminChanged().processReceipt(tx_receipt)
Get log entry for RoleAdminChanged event. :param tx_hash: hash of transaction emitting RoleAdminChanged event
thirdweb/abi/multiwrap.py
get_role_admin_changed_event
nftlabs/nftlabs-sdk-python
30
python
def get_role_admin_changed_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for RoleAdminChanged event.\n\n :param tx_hash: hash of transaction emitting RoleAdminChanged event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.RoleAdminChanged().processReceipt(tx_receipt)
def get_role_admin_changed_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for RoleAdminChanged event.\n\n :param tx_hash: hash of transaction emitting RoleAdminChanged event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.RoleAdminChanged().processReceipt(tx_receipt)<|docstring|>Get log entry for RoleAdminChanged event. :param tx_hash: hash of transaction emitting RoleAdminChanged event<|endoftext|>
85369f4dec7eaad742669df32906f11a5129264117d415628406695c036f784f
def get_role_granted_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for RoleGranted event.\n\n :param tx_hash: hash of transaction emitting RoleGranted event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.RoleGranted().processReceipt(tx_receipt)
Get log entry for RoleGranted event. :param tx_hash: hash of transaction emitting RoleGranted event
thirdweb/abi/multiwrap.py
get_role_granted_event
nftlabs/nftlabs-sdk-python
30
python
def get_role_granted_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for RoleGranted event.\n\n :param tx_hash: hash of transaction emitting RoleGranted event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.RoleGranted().processReceipt(tx_receipt)
def get_role_granted_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for RoleGranted event.\n\n :param tx_hash: hash of transaction emitting RoleGranted event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.RoleGranted().processReceipt(tx_receipt)<|docstring|>Get log entry for RoleGranted event. :param tx_hash: hash of transaction emitting RoleGranted event<|endoftext|>
76d2edfc6ea2a6f2b29216f1efc17372c7500f744902d0945012f199304da3e2
def get_role_revoked_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for RoleRevoked event.\n\n :param tx_hash: hash of transaction emitting RoleRevoked event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.RoleRevoked().processReceipt(tx_receipt)
Get log entry for RoleRevoked event. :param tx_hash: hash of transaction emitting RoleRevoked event
thirdweb/abi/multiwrap.py
get_role_revoked_event
nftlabs/nftlabs-sdk-python
30
python
def get_role_revoked_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for RoleRevoked event.\n\n :param tx_hash: hash of transaction emitting RoleRevoked event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.RoleRevoked().processReceipt(tx_receipt)
def get_role_revoked_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for RoleRevoked event.\n\n :param tx_hash: hash of transaction emitting RoleRevoked event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.RoleRevoked().processReceipt(tx_receipt)<|docstring|>Get log entry for RoleRevoked event. :param tx_hash: hash of transaction emitting RoleRevoked event<|endoftext|>
159f615bb7b0a25bde072644d8cce6aadb856ca14bb52d07652209625edc3923
def get_royalty_for_token_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for RoyaltyForToken event.\n\n :param tx_hash: hash of transaction emitting RoyaltyForToken event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.RoyaltyForToken().processReceipt(tx_receipt)
Get log entry for RoyaltyForToken event. :param tx_hash: hash of transaction emitting RoyaltyForToken event
thirdweb/abi/multiwrap.py
get_royalty_for_token_event
nftlabs/nftlabs-sdk-python
30
python
def get_royalty_for_token_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for RoyaltyForToken event.\n\n :param tx_hash: hash of transaction emitting RoyaltyForToken event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.RoyaltyForToken().processReceipt(tx_receipt)
def get_royalty_for_token_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for RoyaltyForToken event.\n\n :param tx_hash: hash of transaction emitting RoyaltyForToken event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.RoyaltyForToken().processReceipt(tx_receipt)<|docstring|>Get log entry for RoyaltyForToken event. :param tx_hash: hash of transaction emitting RoyaltyForToken event<|endoftext|>
f4cbc28886d1cd9a767e92f1df3a3dd24c49e1006b129aeb696575ccc3476d96
def get_tokens_unwrapped_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for TokensUnwrapped event.\n\n :param tx_hash: hash of transaction emitting TokensUnwrapped event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.TokensUnwrapped().processReceipt(tx_receipt)
Get log entry for TokensUnwrapped event. :param tx_hash: hash of transaction emitting TokensUnwrapped event
thirdweb/abi/multiwrap.py
get_tokens_unwrapped_event
nftlabs/nftlabs-sdk-python
30
python
def get_tokens_unwrapped_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for TokensUnwrapped event.\n\n :param tx_hash: hash of transaction emitting TokensUnwrapped event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.TokensUnwrapped().processReceipt(tx_receipt)
def get_tokens_unwrapped_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for TokensUnwrapped event.\n\n :param tx_hash: hash of transaction emitting TokensUnwrapped event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.TokensUnwrapped().processReceipt(tx_receipt)<|docstring|>Get log entry for TokensUnwrapped event. :param tx_hash: hash of transaction emitting TokensUnwrapped event<|endoftext|>
49e8253d03eaafcd41fc042ae610feba4f2af8e148f70b3fcfa9e59b09ede2b7
def get_tokens_wrapped_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for TokensWrapped event.\n\n :param tx_hash: hash of transaction emitting TokensWrapped event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.TokensWrapped().processReceipt(tx_receipt)
Get log entry for TokensWrapped event. :param tx_hash: hash of transaction emitting TokensWrapped event
thirdweb/abi/multiwrap.py
get_tokens_wrapped_event
nftlabs/nftlabs-sdk-python
30
python
def get_tokens_wrapped_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for TokensWrapped event.\n\n :param tx_hash: hash of transaction emitting TokensWrapped event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.TokensWrapped().processReceipt(tx_receipt)
def get_tokens_wrapped_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for TokensWrapped event.\n\n :param tx_hash: hash of transaction emitting TokensWrapped event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.TokensWrapped().processReceipt(tx_receipt)<|docstring|>Get log entry for TokensWrapped event. :param tx_hash: hash of transaction emitting TokensWrapped event<|endoftext|>
1fc7b178ba0babc6a6972b20d47faead51951f656099c7afd2400738ed51a047
def get_transfer_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for Transfer event.\n\n :param tx_hash: hash of transaction emitting Transfer event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.Transfer().processReceipt(tx_receipt)
Get log entry for Transfer event. :param tx_hash: hash of transaction emitting Transfer event
thirdweb/abi/multiwrap.py
get_transfer_event
nftlabs/nftlabs-sdk-python
30
python
def get_transfer_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for Transfer event.\n\n :param tx_hash: hash of transaction emitting Transfer event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.Transfer().processReceipt(tx_receipt)
def get_transfer_event(self, tx_hash: Union[(HexBytes, bytes)]) -> Tuple[AttributeDict]: 'Get log entry for Transfer event.\n\n :param tx_hash: hash of transaction emitting Transfer event\n ' tx_receipt = self._web3_eth.getTransactionReceipt(tx_hash) return self._web3_eth.contract(address=to_checksum_address(self.contract_address), abi=Multiwrap.abi()).events.Transfer().processReceipt(tx_receipt)<|docstring|>Get log entry for Transfer event. :param tx_hash: hash of transaction emitting Transfer event<|endoftext|>
e89a76374e80c559f622e462224c015f22f2158a4295469dc3bc2ca3a42c34d7
@staticmethod def abi(): 'Return the ABI to the underlying contract.' return json.loads('[{"inputs":[{"internalType":"address","name":"_nativeTokenWrapper","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"prevURI","type":"string"},{"indexed":false,"internalType":"string","name":"newURI","type":"string"}],"name":"ContractURIUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newRoyaltyRecipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"newRoyaltyBps","type":"uint256"}],"name":"DefaultRoyalty","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"prevOwner","type":"address"},{"indexed":false,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"royaltyRecipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"royaltyBps","type":"uint256"}],"name":"RoyaltyForToken","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"unwrapper","type":"address"},{"indexed":true,"internalType":"address","name":"recipientOfWrappedContents","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenIdOfWrappedToken","type":"uint256"}],"name":"TokensUnwrapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"wrapper","type":"address"},{"indexed":true,"internalType":"address","name":"recipientOfWrappedToken","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenIdOfWrappedToken","type":"uint256"},{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"enum ITokenBundle.TokenType","name":"tokenType","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"}],"indexed":false,"internalType":"struct ITokenBundle.Token[]","name":"wrappedContents","type":"tuple[]"}],"name":"TokensWrapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"contractType","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"contractURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"contractVersion","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getDefaultRoyaltyInfo","outputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getRoleMember","outputs":[{"internalType":"address","name":"member","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMemberCount","outputs":[{"internalType":"uint256","name":"count","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"getRoyaltyInfoForToken","outputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bundleId","type":"uint256"}],"name":"getTokenCountOfBundle","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bundleId","type":"uint256"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getTokenOfBundle","outputs":[{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"enum ITokenBundle.TokenType","name":"tokenType","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"}],"internalType":"struct ITokenBundle.Token","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bundleId","type":"uint256"}],"name":"getUriOfBundle","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"getWrappedContents","outputs":[{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"enum ITokenBundle.TokenType","name":"tokenType","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"}],"internalType":"struct ITokenBundle.Token[]","name":"contents","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRoleWithSwitch","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_defaultAdmin","type":"address"},{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"string","name":"_contractURI","type":"string"},{"internalType":"address[]","name":"_trustedForwarders","type":"address[]"},{"internalType":"address","name":"_royaltyRecipient","type":"address"},{"internalType":"uint256","name":"_royaltyBps","type":"uint256"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"forwarder","type":"address"}],"name":"isTrustedForwarder","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextTokenIdToMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"},{"internalType":"uint256[]","name":"index_2","type":"uint256[]"},{"internalType":"uint256[]","name":"index_3","type":"uint256[]"},{"internalType":"bytes","name":"index_4","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"},{"internalType":"uint256","name":"index_2","type":"uint256"},{"internalType":"uint256","name":"index_3","type":"uint256"},{"internalType":"bytes","name":"index_4","type":"bytes"}],"name":"onERC1155Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"},{"internalType":"uint256","name":"index_2","type":"uint256"},{"internalType":"bytes","name":"index_3","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"salePrice","type":"uint256"}],"name":"royaltyInfo","outputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"royaltyAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_uri","type":"string"}],"name":"setContractURI","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_royaltyRecipient","type":"address"},{"internalType":"uint256","name":"_royaltyBps","type":"uint256"}],"name":"setDefaultRoyaltyInfo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newOwner","type":"address"}],"name":"setOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"address","name":"_recipient","type":"address"},{"internalType":"uint256","name":"_bps","type":"uint256"}],"name":"setRoyaltyInfoForToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"address","name":"_recipient","type":"address"}],"name":"unwrap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"enum ITokenBundle.TokenType","name":"tokenType","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"}],"internalType":"struct ITokenBundle.Token[]","name":"_tokensToWrap","type":"tuple[]"},{"internalType":"string","name":"_uriForWrappedToken","type":"string"},{"internalType":"address","name":"_recipient","type":"address"}],"name":"wrap","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"payable","type":"function"}]')
Return the ABI to the underlying contract.
thirdweb/abi/multiwrap.py
abi
nftlabs/nftlabs-sdk-python
30
python
@staticmethod def abi(): return json.loads('[{"inputs":[{"internalType":"address","name":"_nativeTokenWrapper","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"prevURI","type":"string"},{"indexed":false,"internalType":"string","name":"newURI","type":"string"}],"name":"ContractURIUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newRoyaltyRecipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"newRoyaltyBps","type":"uint256"}],"name":"DefaultRoyalty","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"prevOwner","type":"address"},{"indexed":false,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"royaltyRecipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"royaltyBps","type":"uint256"}],"name":"RoyaltyForToken","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"unwrapper","type":"address"},{"indexed":true,"internalType":"address","name":"recipientOfWrappedContents","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenIdOfWrappedToken","type":"uint256"}],"name":"TokensUnwrapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"wrapper","type":"address"},{"indexed":true,"internalType":"address","name":"recipientOfWrappedToken","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenIdOfWrappedToken","type":"uint256"},{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"enum ITokenBundle.TokenType","name":"tokenType","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"}],"indexed":false,"internalType":"struct ITokenBundle.Token[]","name":"wrappedContents","type":"tuple[]"}],"name":"TokensWrapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":,"type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":,"type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"contractType","outputs":[{"internalType":"bytes32","name":,"type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"contractURI","outputs":[{"internalType":"string","name":,"type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"contractVersion","outputs":[{"internalType":"uint8","name":,"type":"uint8"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":,"type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getDefaultRoyaltyInfo","outputs":[{"internalType":"address","name":,"type":"address"},{"internalType":"uint16","name":,"type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":,"type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getRoleMember","outputs":[{"internalType":"address","name":"member","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMemberCount","outputs":[{"internalType":"uint256","name":"count","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"getRoyaltyInfoForToken","outputs":[{"internalType":"address","name":,"type":"address"},{"internalType":"uint16","name":,"type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bundleId","type":"uint256"}],"name":"getTokenCountOfBundle","outputs":[{"internalType":"uint256","name":,"type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bundleId","type":"uint256"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getTokenOfBundle","outputs":[{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"enum ITokenBundle.TokenType","name":"tokenType","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"}],"internalType":"struct ITokenBundle.Token","name":,"type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bundleId","type":"uint256"}],"name":"getUriOfBundle","outputs":[{"internalType":"string","name":,"type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"getWrappedContents","outputs":[{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"enum ITokenBundle.TokenType","name":"tokenType","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"}],"internalType":"struct ITokenBundle.Token[]","name":"contents","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":,"type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRoleWithSwitch","outputs":[{"internalType":"bool","name":,"type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_defaultAdmin","type":"address"},{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"string","name":"_contractURI","type":"string"},{"internalType":"address[]","name":"_trustedForwarders","type":"address[]"},{"internalType":"address","name":"_royaltyRecipient","type":"address"},{"internalType":"uint256","name":"_royaltyBps","type":"uint256"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":,"type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"forwarder","type":"address"}],"name":"isTrustedForwarder","outputs":[{"internalType":"bool","name":,"type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":,"type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextTokenIdToMint","outputs":[{"internalType":"uint256","name":,"type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"},{"internalType":"uint256[]","name":"index_2","type":"uint256[]"},{"internalType":"uint256[]","name":"index_3","type":"uint256[]"},{"internalType":"bytes","name":"index_4","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"internalType":"bytes4","name":,"type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"},{"internalType":"uint256","name":"index_2","type":"uint256"},{"internalType":"uint256","name":"index_3","type":"uint256"},{"internalType":"bytes","name":"index_4","type":"bytes"}],"name":"onERC1155Received","outputs":[{"internalType":"bytes4","name":,"type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"},{"internalType":"uint256","name":"index_2","type":"uint256"},{"internalType":"bytes","name":"index_3","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":,"type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":,"type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":,"type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"salePrice","type":"uint256"}],"name":"royaltyInfo","outputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"royaltyAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_uri","type":"string"}],"name":"setContractURI","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_royaltyRecipient","type":"address"},{"internalType":"uint256","name":"_royaltyBps","type":"uint256"}],"name":"setDefaultRoyaltyInfo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newOwner","type":"address"}],"name":"setOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"address","name":"_recipient","type":"address"},{"internalType":"uint256","name":"_bps","type":"uint256"}],"name":"setRoyaltyInfoForToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":,"type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":,"type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":,"type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"address","name":"_recipient","type":"address"}],"name":"unwrap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"enum ITokenBundle.TokenType","name":"tokenType","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"}],"internalType":"struct ITokenBundle.Token[]","name":"_tokensToWrap","type":"tuple[]"},{"internalType":"string","name":"_uriForWrappedToken","type":"string"},{"internalType":"address","name":"_recipient","type":"address"}],"name":"wrap","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"payable","type":"function"}]')
@staticmethod def abi(): return json.loads('[{"inputs":[{"internalType":"address","name":"_nativeTokenWrapper","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"prevURI","type":"string"},{"indexed":false,"internalType":"string","name":"newURI","type":"string"}],"name":"ContractURIUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newRoyaltyRecipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"newRoyaltyBps","type":"uint256"}],"name":"DefaultRoyalty","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"prevOwner","type":"address"},{"indexed":false,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"royaltyRecipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"royaltyBps","type":"uint256"}],"name":"RoyaltyForToken","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"unwrapper","type":"address"},{"indexed":true,"internalType":"address","name":"recipientOfWrappedContents","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenIdOfWrappedToken","type":"uint256"}],"name":"TokensUnwrapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"wrapper","type":"address"},{"indexed":true,"internalType":"address","name":"recipientOfWrappedToken","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenIdOfWrappedToken","type":"uint256"},{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"enum ITokenBundle.TokenType","name":"tokenType","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"}],"indexed":false,"internalType":"struct ITokenBundle.Token[]","name":"wrappedContents","type":"tuple[]"}],"name":"TokensWrapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":,"type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":,"type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"contractType","outputs":[{"internalType":"bytes32","name":,"type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"contractURI","outputs":[{"internalType":"string","name":,"type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"contractVersion","outputs":[{"internalType":"uint8","name":,"type":"uint8"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":,"type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getDefaultRoyaltyInfo","outputs":[{"internalType":"address","name":,"type":"address"},{"internalType":"uint16","name":,"type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":,"type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getRoleMember","outputs":[{"internalType":"address","name":"member","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMemberCount","outputs":[{"internalType":"uint256","name":"count","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"getRoyaltyInfoForToken","outputs":[{"internalType":"address","name":,"type":"address"},{"internalType":"uint16","name":,"type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bundleId","type":"uint256"}],"name":"getTokenCountOfBundle","outputs":[{"internalType":"uint256","name":,"type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bundleId","type":"uint256"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getTokenOfBundle","outputs":[{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"enum ITokenBundle.TokenType","name":"tokenType","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"}],"internalType":"struct ITokenBundle.Token","name":,"type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bundleId","type":"uint256"}],"name":"getUriOfBundle","outputs":[{"internalType":"string","name":,"type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"getWrappedContents","outputs":[{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"enum ITokenBundle.TokenType","name":"tokenType","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"}],"internalType":"struct ITokenBundle.Token[]","name":"contents","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":,"type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRoleWithSwitch","outputs":[{"internalType":"bool","name":,"type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_defaultAdmin","type":"address"},{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"string","name":"_contractURI","type":"string"},{"internalType":"address[]","name":"_trustedForwarders","type":"address[]"},{"internalType":"address","name":"_royaltyRecipient","type":"address"},{"internalType":"uint256","name":"_royaltyBps","type":"uint256"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":,"type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"forwarder","type":"address"}],"name":"isTrustedForwarder","outputs":[{"internalType":"bool","name":,"type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":,"type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextTokenIdToMint","outputs":[{"internalType":"uint256","name":,"type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"},{"internalType":"uint256[]","name":"index_2","type":"uint256[]"},{"internalType":"uint256[]","name":"index_3","type":"uint256[]"},{"internalType":"bytes","name":"index_4","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"internalType":"bytes4","name":,"type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"},{"internalType":"uint256","name":"index_2","type":"uint256"},{"internalType":"uint256","name":"index_3","type":"uint256"},{"internalType":"bytes","name":"index_4","type":"bytes"}],"name":"onERC1155Received","outputs":[{"internalType":"bytes4","name":,"type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"index_0","type":"address"},{"internalType":"address","name":"index_1","type":"address"},{"internalType":"uint256","name":"index_2","type":"uint256"},{"internalType":"bytes","name":"index_3","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":,"type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":,"type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":,"type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"salePrice","type":"uint256"}],"name":"royaltyInfo","outputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"royaltyAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_uri","type":"string"}],"name":"setContractURI","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_royaltyRecipient","type":"address"},{"internalType":"uint256","name":"_royaltyBps","type":"uint256"}],"name":"setDefaultRoyaltyInfo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newOwner","type":"address"}],"name":"setOwner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"address","name":"_recipient","type":"address"},{"internalType":"uint256","name":"_bps","type":"uint256"}],"name":"setRoyaltyInfoForToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":,"type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":,"type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":,"type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"internalType":"address","name":"_recipient","type":"address"}],"name":"unwrap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"enum ITokenBundle.TokenType","name":"tokenType","type":"uint8"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"totalAmount","type":"uint256"}],"internalType":"struct ITokenBundle.Token[]","name":"_tokensToWrap","type":"tuple[]"},{"internalType":"string","name":"_uriForWrappedToken","type":"string"},{"internalType":"address","name":"_recipient","type":"address"}],"name":"wrap","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"payable","type":"function"}]')<|docstring|>Return the ABI to the underlying contract.<|endoftext|>
b4336b2f4ff09a59fdb8a71ccd0ec60fbbfa9d48fcaa737fa0421d6700066b46
def setUp(self): 'Set up the tests.' webcompat.app.config['TESTING'] = True self.app = webcompat.app.test_client()
Set up the tests.
tests/unit/test_urls.py
setUp
softvision-oana-arbuzov/webcompat.com
2
python
def setUp(self): webcompat.app.config['TESTING'] = True self.app = webcompat.app.test_client()
def setUp(self): webcompat.app.config['TESTING'] = True self.app = webcompat.app.test_client()<|docstring|>Set up the tests.<|endoftext|>
ff56221943b1285762627cbf28c4dbc317906c6ba43c726f3d605cdcfd3bdde0
def tearDown(self): 'Tear down the tests.' pass
Tear down the tests.
tests/unit/test_urls.py
tearDown
softvision-oana-arbuzov/webcompat.com
2
python
def tearDown(self): pass
def tearDown(self): pass<|docstring|>Tear down the tests.<|endoftext|>
027011c3faaacbe7c461bd1b4ad98fa64714dad3513684cb3fa63d90f8326820
def test_home(self): 'Test that the home page exists.' rv = self.app.get('/', environ_base=headers) self.assertEqual(rv.status_code, 200)
Test that the home page exists.
tests/unit/test_urls.py
test_home
softvision-oana-arbuzov/webcompat.com
2
python
def test_home(self): rv = self.app.get('/', environ_base=headers) self.assertEqual(rv.status_code, 200)
def test_home(self): rv = self.app.get('/', environ_base=headers) self.assertEqual(rv.status_code, 200)<|docstring|>Test that the home page exists.<|endoftext|>
f934a2d976af52ae2e6baa2ac6f7624e111861b8244eacf4e58a687b4ac2a9d3
def test_new_issue(self): 'Test that /issues/new exists.' rv = self.app.get('/issues/new', environ_base=headers) self.assertEqual(rv.status_code, 200)
Test that /issues/new exists.
tests/unit/test_urls.py
test_new_issue
softvision-oana-arbuzov/webcompat.com
2
python
def test_new_issue(self): rv = self.app.get('/issues/new', environ_base=headers) self.assertEqual(rv.status_code, 200)
def test_new_issue(self): rv = self.app.get('/issues/new', environ_base=headers) self.assertEqual(rv.status_code, 200)<|docstring|>Test that /issues/new exists.<|endoftext|>
20160344198928338f17075030d30ef61cdf2aa1fd84984366a7721f2b86fa36
def test_about(self): 'Test that /about exists.' rv = self.app.get('/about') self.assertEqual(rv.status_code, 200)
Test that /about exists.
tests/unit/test_urls.py
test_about
softvision-oana-arbuzov/webcompat.com
2
python
def test_about(self): rv = self.app.get('/about') self.assertEqual(rv.status_code, 200)
def test_about(self): rv = self.app.get('/about') self.assertEqual(rv.status_code, 200)<|docstring|>Test that /about exists.<|endoftext|>
8e63b22f49f9ad55b1e238f708f73418f0b57ea3a65b42fd01263aac879375a7
def test_privacy(self): 'Test that /privacy exists.' rv = self.app.get('/privacy') self.assertEqual(rv.status_code, 200)
Test that /privacy exists.
tests/unit/test_urls.py
test_privacy
softvision-oana-arbuzov/webcompat.com
2
python
def test_privacy(self): rv = self.app.get('/privacy') self.assertEqual(rv.status_code, 200)
def test_privacy(self): rv = self.app.get('/privacy') self.assertEqual(rv.status_code, 200)<|docstring|>Test that /privacy exists.<|endoftext|>
81ae576278e8c537f1e6d6a7c55823ffd90607bc41b8d8e1facad211a5cdb9ae
def test_contributors(self): 'Test that /contributors exists.' rv = self.app.get('/contributors') self.assertEqual(rv.status_code, 200)
Test that /contributors exists.
tests/unit/test_urls.py
test_contributors
softvision-oana-arbuzov/webcompat.com
2
python
def test_contributors(self): rv = self.app.get('/contributors') self.assertEqual(rv.status_code, 200)
def test_contributors(self): rv = self.app.get('/contributors') self.assertEqual(rv.status_code, 200)<|docstring|>Test that /contributors exists.<|endoftext|>
3de4e5cefee81069134d38ab3d55fac948197733d5688abcccfdd0ba104ed62d
def test_contributors_report_bug(self): 'Test that /contributors/report-bug exists.' rv = self.app.get('/contributors/report-bug') self.assertEqual(rv.status_code, 200)
Test that /contributors/report-bug exists.
tests/unit/test_urls.py
test_contributors_report_bug
softvision-oana-arbuzov/webcompat.com
2
python
def test_contributors_report_bug(self): rv = self.app.get('/contributors/report-bug') self.assertEqual(rv.status_code, 200)
def test_contributors_report_bug(self): rv = self.app.get('/contributors/report-bug') self.assertEqual(rv.status_code, 200)<|docstring|>Test that /contributors/report-bug exists.<|endoftext|>
e2b3ac1470e160260ecbdee5d64e5ca309c63640a03bb74f1e2572f1d2bac5cb
def test_contributors_diagnose_bug(self): 'Test that /contributors/diagnose-bug exists.' rv = self.app.get('/contributors/diagnose-bug') self.assertEqual(rv.status_code, 200)
Test that /contributors/diagnose-bug exists.
tests/unit/test_urls.py
test_contributors_diagnose_bug
softvision-oana-arbuzov/webcompat.com
2
python
def test_contributors_diagnose_bug(self): rv = self.app.get('/contributors/diagnose-bug') self.assertEqual(rv.status_code, 200)
def test_contributors_diagnose_bug(self): rv = self.app.get('/contributors/diagnose-bug') self.assertEqual(rv.status_code, 200)<|docstring|>Test that /contributors/diagnose-bug exists.<|endoftext|>
7384c441257453045cb2da5361efb95181fd305435f0f422e45b4b33e126d7d1
def test_contributors_reproduce_bug(self): 'Test that /contributors/reproduce-bug exists.' rv = self.app.get('/contributors/reproduce-bug') self.assertEqual(rv.status_code, 200)
Test that /contributors/reproduce-bug exists.
tests/unit/test_urls.py
test_contributors_reproduce_bug
softvision-oana-arbuzov/webcompat.com
2
python
def test_contributors_reproduce_bug(self): rv = self.app.get('/contributors/reproduce-bug') self.assertEqual(rv.status_code, 200)
def test_contributors_reproduce_bug(self): rv = self.app.get('/contributors/reproduce-bug') self.assertEqual(rv.status_code, 200)<|docstring|>Test that /contributors/reproduce-bug exists.<|endoftext|>
5ecb025e9ab1fb3e5ce4cffd9c847a74d6a074900a9892121f3cc5bc4152cb9c
def test_contributors_site_outreach(self): 'Test that /contributors/site-outreach exists.' rv = self.app.get('/contributors/site-outreach') self.assertEqual(rv.status_code, 200)
Test that /contributors/site-outreach exists.
tests/unit/test_urls.py
test_contributors_site_outreach
softvision-oana-arbuzov/webcompat.com
2
python
def test_contributors_site_outreach(self): rv = self.app.get('/contributors/site-outreach') self.assertEqual(rv.status_code, 200)
def test_contributors_site_outreach(self): rv = self.app.get('/contributors/site-outreach') self.assertEqual(rv.status_code, 200)<|docstring|>Test that /contributors/site-outreach exists.<|endoftext|>
42a21e2f54fbcf6eadd5734bb40760f64756d72b8ed831414b99cd56fdb4c4d3
def test_contributors_build_tools(self): 'Test that /contributors/build-tools exists.' rv = self.app.get('/contributors/build-tools') self.assertEqual(rv.status_code, 200)
Test that /contributors/build-tools exists.
tests/unit/test_urls.py
test_contributors_build_tools
softvision-oana-arbuzov/webcompat.com
2
python
def test_contributors_build_tools(self): rv = self.app.get('/contributors/build-tools') self.assertEqual(rv.status_code, 200)
def test_contributors_build_tools(self): rv = self.app.get('/contributors/build-tools') self.assertEqual(rv.status_code, 200)<|docstring|>Test that /contributors/build-tools exists.<|endoftext|>
6a3e7b7cbc62fa85593536c4ba0a13f7940d5414550a01210ecc6ce0334d816a
def test_contributors_web_research(self): 'Test that /contributors/web-platform-research exists.' rv = self.app.get('/contributors/web-platform-research') self.assertEqual(rv.status_code, 200)
Test that /contributors/web-platform-research exists.
tests/unit/test_urls.py
test_contributors_web_research
softvision-oana-arbuzov/webcompat.com
2
python
def test_contributors_web_research(self): rv = self.app.get('/contributors/web-platform-research') self.assertEqual(rv.status_code, 200)
def test_contributors_web_research(self): rv = self.app.get('/contributors/web-platform-research') self.assertEqual(rv.status_code, 200)<|docstring|>Test that /contributors/web-platform-research exists.<|endoftext|>
065818a6cf17be6beee1933f6312d6948726dab52decd6896428bc98f64d8f29
def test_contributors_events(self): 'Test that /contributors/organize-webcompat-events exists.' rv = self.app.get('/contributors/organize-webcompat-events') self.assertEqual(rv.status_code, 200)
Test that /contributors/organize-webcompat-events exists.
tests/unit/test_urls.py
test_contributors_events
softvision-oana-arbuzov/webcompat.com
2
python
def test_contributors_events(self): rv = self.app.get('/contributors/organize-webcompat-events') self.assertEqual(rv.status_code, 200)
def test_contributors_events(self): rv = self.app.get('/contributors/organize-webcompat-events') self.assertEqual(rv.status_code, 200)<|docstring|>Test that /contributors/organize-webcompat-events exists.<|endoftext|>
f7096d2910cae83a8e03dc79e58d109af2689c566c6eaac72fc54a332b2de476
def test_contact(self): 'Test that /contact exists.' rv = self.app.get('/contact') self.assertEqual(rv.status_code, 200)
Test that /contact exists.
tests/unit/test_urls.py
test_contact
softvision-oana-arbuzov/webcompat.com
2
python
def test_contact(self): rv = self.app.get('/contact') self.assertEqual(rv.status_code, 200)
def test_contact(self): rv = self.app.get('/contact') self.assertEqual(rv.status_code, 200)<|docstring|>Test that /contact exists.<|endoftext|>
d9729652a83b8c03452f7e9c01956f9dcead7eb5bb9a3fc77f9376c1f7310d71
def test_activity_page_401_if_not_logged_in(self): 'Test that asks user to log in before displaying activity.' rv = self.app.get('/me') self.assertEqual(rv.status_code, 401)
Test that asks user to log in before displaying activity.
tests/unit/test_urls.py
test_activity_page_401_if_not_logged_in
softvision-oana-arbuzov/webcompat.com
2
python
def test_activity_page_401_if_not_logged_in(self): rv = self.app.get('/me') self.assertEqual(rv.status_code, 401)
def test_activity_page_401_if_not_logged_in(self): rv = self.app.get('/me') self.assertEqual(rv.status_code, 401)<|docstring|>Test that asks user to log in before displaying activity.<|endoftext|>
239e178b433672cec4f378260cd27e2f9063d40d88bcfdf96a694221717d0b45
def test_issue_int(self): 'Test if issues are really integer.\n\n * an issue only displays if <number> is an integer\n * /issues/<number> exists, and does not redirect.\n ' rv = self.app.get('/issues/3') self.assertEqual(rv.status_code, 200) self.assertNotEqual(rv.status_code, 404) rv = self.app.get('/issues/three') self.assertEqual(rv.status_code, 404) self.assertNotEqual(rv.status_code, 200)
Test if issues are really integer. * an issue only displays if <number> is an integer * /issues/<number> exists, and does not redirect.
tests/unit/test_urls.py
test_issue_int
softvision-oana-arbuzov/webcompat.com
2
python
def test_issue_int(self): 'Test if issues are really integer.\n\n * an issue only displays if <number> is an integer\n * /issues/<number> exists, and does not redirect.\n ' rv = self.app.get('/issues/3') self.assertEqual(rv.status_code, 200) self.assertNotEqual(rv.status_code, 404) rv = self.app.get('/issues/three') self.assertEqual(rv.status_code, 404) self.assertNotEqual(rv.status_code, 200)
def test_issue_int(self): 'Test if issues are really integer.\n\n * an issue only displays if <number> is an integer\n * /issues/<number> exists, and does not redirect.\n ' rv = self.app.get('/issues/3') self.assertEqual(rv.status_code, 200) self.assertNotEqual(rv.status_code, 404) rv = self.app.get('/issues/three') self.assertEqual(rv.status_code, 404) self.assertNotEqual(rv.status_code, 200)<|docstring|>Test if issues are really integer. * an issue only displays if <number> is an integer * /issues/<number> exists, and does not redirect.<|endoftext|>
467f8453de91d5a4932bacce6ecbdf12c595d25f2fc2604f8b2eb70e924cc245
def test_issue_redirect(self): 'Test that the /issues/<number> exists, and does not redirect.' rv = self.app.get('/issues/3') self.assertEqual(rv.status_code, 200) self.assertNotEqual(rv.status_code, 307)
Test that the /issues/<number> exists, and does not redirect.
tests/unit/test_urls.py
test_issue_redirect
softvision-oana-arbuzov/webcompat.com
2
python
def test_issue_redirect(self): rv = self.app.get('/issues/3') self.assertEqual(rv.status_code, 200) self.assertNotEqual(rv.status_code, 307)
def test_issue_redirect(self): rv = self.app.get('/issues/3') self.assertEqual(rv.status_code, 200) self.assertNotEqual(rv.status_code, 307)<|docstring|>Test that the /issues/<number> exists, and does not redirect.<|endoftext|>
59c3c592edf9fc1e9d45b5db24ac90ff5595749756899de8c0cf7865064da33b
def test_issues_list_page(self): 'Test that the /issues route gets 200 and does not redirect.' rv = self.app.get('/issues') self.assertEqual(rv.status_code, 200) self.assertNotEqual(rv.status_code, 307)
Test that the /issues route gets 200 and does not redirect.
tests/unit/test_urls.py
test_issues_list_page
softvision-oana-arbuzov/webcompat.com
2
python
def test_issues_list_page(self): rv = self.app.get('/issues') self.assertEqual(rv.status_code, 200) self.assertNotEqual(rv.status_code, 307)
def test_issues_list_page(self): rv = self.app.get('/issues') self.assertEqual(rv.status_code, 200) self.assertNotEqual(rv.status_code, 307)<|docstring|>Test that the /issues route gets 200 and does not redirect.<|endoftext|>
a9f341fbecdb2fbf7b0b96986290777b1265e283ba6f214b3cdf6ead0e13e19c
def test_csp_report_uri(self): 'Test POST to /csp-report w/ correct content-type returns 204.' headers = {'Content-Type': 'application/csp-report'} rv = self.app.post('/csp-report', headers=headers) self.assertEqual(rv.status_code, 204)
Test POST to /csp-report w/ correct content-type returns 204.
tests/unit/test_urls.py
test_csp_report_uri
softvision-oana-arbuzov/webcompat.com
2
python
def test_csp_report_uri(self): headers = {'Content-Type': 'application/csp-report'} rv = self.app.post('/csp-report', headers=headers) self.assertEqual(rv.status_code, 204)
def test_csp_report_uri(self): headers = {'Content-Type': 'application/csp-report'} rv = self.app.post('/csp-report', headers=headers) self.assertEqual(rv.status_code, 204)<|docstring|>Test POST to /csp-report w/ correct content-type returns 204.<|endoftext|>
90877a27c451a9ef0a45de4b4a3ad7e5f531209931842b3e8f64560be6ed322f
def test_csp_report_uri_bad_content_type(self): 'Test POST w/ wrong content-type to /csp-report returns 400.' headers = {'Content-Type': 'application/json'} rv = self.app.post('/csp-report', headers=headers) self.assertNotEqual(rv.status_code, 204) self.assertEqual(rv.status_code, 400)
Test POST w/ wrong content-type to /csp-report returns 400.
tests/unit/test_urls.py
test_csp_report_uri_bad_content_type
softvision-oana-arbuzov/webcompat.com
2
python
def test_csp_report_uri_bad_content_type(self): headers = {'Content-Type': 'application/json'} rv = self.app.post('/csp-report', headers=headers) self.assertNotEqual(rv.status_code, 204) self.assertEqual(rv.status_code, 400)
def test_csp_report_uri_bad_content_type(self): headers = {'Content-Type': 'application/json'} rv = self.app.post('/csp-report', headers=headers) self.assertNotEqual(rv.status_code, 204) self.assertEqual(rv.status_code, 400)<|docstring|>Test POST w/ wrong content-type to /csp-report returns 400.<|endoftext|>
c4dd8b133567beb6df2241edcaecc2f833aad24f434835b95cc30b0cb3516a8e
def test_tools_cssfixme(self): 'Test that the /tools/cssfixme route gets 200.' rv = self.app.get('/tools/cssfixme') self.assertEqual(rv.status_code, 410)
Test that the /tools/cssfixme route gets 200.
tests/unit/test_urls.py
test_tools_cssfixme
softvision-oana-arbuzov/webcompat.com
2
python
def test_tools_cssfixme(self): rv = self.app.get('/tools/cssfixme') self.assertEqual(rv.status_code, 410)
def test_tools_cssfixme(self): rv = self.app.get('/tools/cssfixme') self.assertEqual(rv.status_code, 410)<|docstring|>Test that the /tools/cssfixme route gets 200.<|endoftext|>
0a0ff17ff4744324eff21296f787e8f447d0da31f32fb7b3472a439cab6e4113
def test_rate_limit(self): 'Rate Limit URI sends 410 Gone.' rv = self.app.get('/rate_limit') self.assertEqual(rv.status_code, 410)
Rate Limit URI sends 410 Gone.
tests/unit/test_urls.py
test_rate_limit
softvision-oana-arbuzov/webcompat.com
2
python
def test_rate_limit(self): rv = self.app.get('/rate_limit') self.assertEqual(rv.status_code, 410)
def test_rate_limit(self): rv = self.app.get('/rate_limit') self.assertEqual(rv.status_code, 410)<|docstring|>Rate Limit URI sends 410 Gone.<|endoftext|>
ba673270073dbdfd390e8da9a048c09bb4487b8c6c61772e0c5819d38eef3d13
def test_missing_parameters_for_new_issue(self): 'Sends 400 to POST on /issues/new with missing parameters.' rv = self.app.post('/issues/new', data=dict(url='foo')) self.assertEqual(rv.status_code, 400)
Sends 400 to POST on /issues/new with missing parameters.
tests/unit/test_urls.py
test_missing_parameters_for_new_issue
softvision-oana-arbuzov/webcompat.com
2
python
def test_missing_parameters_for_new_issue(self): rv = self.app.post('/issues/new', data=dict(url='foo')) self.assertEqual(rv.status_code, 400)
def test_missing_parameters_for_new_issue(self): rv = self.app.post('/issues/new', data=dict(url='foo')) self.assertEqual(rv.status_code, 400)<|docstring|>Sends 400 to POST on /issues/new with missing parameters.<|endoftext|>
97302fb35180406d3bfb0dc793c4ce3acba60a24877dd3c94002acb6c89651d7
def test_new_issue_should_not_crash(self): '/issues/new POST exit with 400 if missing parameters.' data = {'problem_category': u'mobile_site_bug', 'description': u'foo', 'submit_type': u'github-proxy-report', 'url': u'http://example.com', 'os': u'Foobar', 'browser': u'BarFoo'} rv = self.app.post('/issues/new', data=data) self.assertEqual(rv.status_code, 400)
/issues/new POST exit with 400 if missing parameters.
tests/unit/test_urls.py
test_new_issue_should_not_crash
softvision-oana-arbuzov/webcompat.com
2
python
def test_new_issue_should_not_crash(self): data = {'problem_category': u'mobile_site_bug', 'description': u'foo', 'submit_type': u'github-proxy-report', 'url': u'http://example.com', 'os': u'Foobar', 'browser': u'BarFoo'} rv = self.app.post('/issues/new', data=data) self.assertEqual(rv.status_code, 400)
def test_new_issue_should_not_crash(self): data = {'problem_category': u'mobile_site_bug', 'description': u'foo', 'submit_type': u'github-proxy-report', 'url': u'http://example.com', 'os': u'Foobar', 'browser': u'BarFoo'} rv = self.app.post('/issues/new', data=data) self.assertEqual(rv.status_code, 400)<|docstring|>/issues/new POST exit with 400 if missing parameters.<|endoftext|>
3355bc29e93e8c091130d14cc8c19855f73b540e38031ed8dde9bd4e331266dd
def test_dashboard_triage(self): 'Request to /dashboard/triage should be 200.' rv = self.app.get('/dashboard/triage') self.assertEqual(rv.status_code, 200) self.assertTrue(('<h1><a href="/">Webcompat.com</a> // Triage Dashboard</h1>' in rv.data)) self.assertTrue(('text/html' in rv.content_type))
Request to /dashboard/triage should be 200.
tests/unit/test_urls.py
test_dashboard_triage
softvision-oana-arbuzov/webcompat.com
2
python
def test_dashboard_triage(self): rv = self.app.get('/dashboard/triage') self.assertEqual(rv.status_code, 200) self.assertTrue(('<h1><a href="/">Webcompat.com</a> // Triage Dashboard</h1>' in rv.data)) self.assertTrue(('text/html' in rv.content_type))
def test_dashboard_triage(self): rv = self.app.get('/dashboard/triage') self.assertEqual(rv.status_code, 200) self.assertTrue(('<h1><a href="/">Webcompat.com</a> // Triage Dashboard</h1>' in rv.data)) self.assertTrue(('text/html' in rv.content_type))<|docstring|>Request to /dashboard/triage should be 200.<|endoftext|>
0be02369ae9350ac50e8d7348be311c37d749479cbcbdb93c56b6044536d7ea5
def test_dashboard_route(self): 'Request to /dashboard should be 404.\n\n For now, the dashboard route has no purpose.\n ' rv = self.app.get('/dashboard/') content_test = ('Lost in Punk Cat Space (404)' in rv.data) self.assertEqual(rv.status_code, 404) self.assertTrue(('text/html' in rv.content_type)) self.assertTrue(content_test) rv = self.app.get('/dashboard') content_test = ('Lost in Punk Cat Space (404)' in rv.data) self.assertEqual(rv.status_code, 404) self.assertTrue(('text/html' in rv.content_type)) self.assertTrue(content_test)
Request to /dashboard should be 404. For now, the dashboard route has no purpose.
tests/unit/test_urls.py
test_dashboard_route
softvision-oana-arbuzov/webcompat.com
2
python
def test_dashboard_route(self): 'Request to /dashboard should be 404.\n\n For now, the dashboard route has no purpose.\n ' rv = self.app.get('/dashboard/') content_test = ('Lost in Punk Cat Space (404)' in rv.data) self.assertEqual(rv.status_code, 404) self.assertTrue(('text/html' in rv.content_type)) self.assertTrue(content_test) rv = self.app.get('/dashboard') content_test = ('Lost in Punk Cat Space (404)' in rv.data) self.assertEqual(rv.status_code, 404) self.assertTrue(('text/html' in rv.content_type)) self.assertTrue(content_test)
def test_dashboard_route(self): 'Request to /dashboard should be 404.\n\n For now, the dashboard route has no purpose.\n ' rv = self.app.get('/dashboard/') content_test = ('Lost in Punk Cat Space (404)' in rv.data) self.assertEqual(rv.status_code, 404) self.assertTrue(('text/html' in rv.content_type)) self.assertTrue(content_test) rv = self.app.get('/dashboard') content_test = ('Lost in Punk Cat Space (404)' in rv.data) self.assertEqual(rv.status_code, 404) self.assertTrue(('text/html' in rv.content_type)) self.assertTrue(content_test)<|docstring|>Request to /dashboard should be 404. For now, the dashboard route has no purpose.<|endoftext|>
b17b99cbf52823fb268a2890345c280adf303b7d079a2d1e2ab3865480f11ac0
def load_deps(path): 'Load dependencies from requirements file' with open(path) as fp: return [line.strip() for line in fp if (not is_ignored(line))]
Load dependencies from requirements file
setup.py
load_deps
yonittanenbaum/mlrun
0
python
def load_deps(path): with open(path) as fp: return [line.strip() for line in fp if (not is_ignored(line))]
def load_deps(path): with open(path) as fp: return [line.strip() for line in fp if (not is_ignored(line))]<|docstring|>Load dependencies from requirements file<|endoftext|>
d6868b14ba9352a49c57690d10365ff9c0c6266a6f97a5fd51c7a8efe65ddb8d
def reward_function(params): '\n Stay in the track and incentive higher speeds\n ' MAX_REWARD = float(10000) if (params['progress'] == 100): return MAX_REWARD all_wheels_on_track = params['all_wheels_on_track'] distance_from_center = params['distance_from_center'] track_width = params['track_width'] reward = 0.001 if (all_wheels_on_track and (((0.5 * track_width) - distance_from_center) >= 0.05)): reward = 1.0 reward *= (params['speed'] ** 2) return min(float(reward), MAX_REWARD)
Stay in the track and incentive higher speeds
deepracer/rewards/time-trial/speed_incentivized_simple_track_follow.py
reward_function
spowers42/rl-racing
0
python
def reward_function(params): '\n \n ' MAX_REWARD = float(10000) if (params['progress'] == 100): return MAX_REWARD all_wheels_on_track = params['all_wheels_on_track'] distance_from_center = params['distance_from_center'] track_width = params['track_width'] reward = 0.001 if (all_wheels_on_track and (((0.5 * track_width) - distance_from_center) >= 0.05)): reward = 1.0 reward *= (params['speed'] ** 2) return min(float(reward), MAX_REWARD)
def reward_function(params): '\n \n ' MAX_REWARD = float(10000) if (params['progress'] == 100): return MAX_REWARD all_wheels_on_track = params['all_wheels_on_track'] distance_from_center = params['distance_from_center'] track_width = params['track_width'] reward = 0.001 if (all_wheels_on_track and (((0.5 * track_width) - distance_from_center) >= 0.05)): reward = 1.0 reward *= (params['speed'] ** 2) return min(float(reward), MAX_REWARD)<|docstring|>Stay in the track and incentive higher speeds<|endoftext|>
68841d9e24e51befa61546debcaf2408ae44ef69acb7d1a9ac813e34b8b69f5a
def my_inference_detector(model, data): 'Inference image(s) with the detector.\n\n Args:\n model (nn.Module): The loaded detector.\n imgs (str/ndarray or list[str/ndarray]): Either image files or loaded\n images.\n\n Returns:\n If imgs is a str, a generator will be returned, otherwise return the\n detection results directly.\n ' cfg = model.cfg device = next(model.parameters()).device test_pipeline = cfg.data.test.pipeline[1:] test_pipeline = Compose(test_pipeline) data = test_pipeline(data) data = collate([data], samples_per_gpu=1) if next(model.parameters()).is_cuda: data = scatter(data, [device])[0] else: for m in model.modules(): if isinstance(m, (RoIPool, RoIAlign)): if (not m.aligned): m.use_torchvision = True warnings.warn('We set use_torchvision=True in CPU mode.') data['img_metas'] = data['img_metas'][0].data with torch.no_grad(): result = model(return_loss=False, rescale=True, **data) return result[0]
Inference image(s) with the detector. Args: model (nn.Module): The loaded detector. imgs (str/ndarray or list[str/ndarray]): Either image files or loaded images. Returns: If imgs is a str, a generator will be returned, otherwise return the detection results directly.
UFPMP-Det-Tools/eval_script/ufpmp_det_eval.py
my_inference_detector
PuAnysh/UFPMP-Det
9
python
def my_inference_detector(model, data): 'Inference image(s) with the detector.\n\n Args:\n model (nn.Module): The loaded detector.\n imgs (str/ndarray or list[str/ndarray]): Either image files or loaded\n images.\n\n Returns:\n If imgs is a str, a generator will be returned, otherwise return the\n detection results directly.\n ' cfg = model.cfg device = next(model.parameters()).device test_pipeline = cfg.data.test.pipeline[1:] test_pipeline = Compose(test_pipeline) data = test_pipeline(data) data = collate([data], samples_per_gpu=1) if next(model.parameters()).is_cuda: data = scatter(data, [device])[0] else: for m in model.modules(): if isinstance(m, (RoIPool, RoIAlign)): if (not m.aligned): m.use_torchvision = True warnings.warn('We set use_torchvision=True in CPU mode.') data['img_metas'] = data['img_metas'][0].data with torch.no_grad(): result = model(return_loss=False, rescale=True, **data) return result[0]
def my_inference_detector(model, data): 'Inference image(s) with the detector.\n\n Args:\n model (nn.Module): The loaded detector.\n imgs (str/ndarray or list[str/ndarray]): Either image files or loaded\n images.\n\n Returns:\n If imgs is a str, a generator will be returned, otherwise return the\n detection results directly.\n ' cfg = model.cfg device = next(model.parameters()).device test_pipeline = cfg.data.test.pipeline[1:] test_pipeline = Compose(test_pipeline) data = test_pipeline(data) data = collate([data], samples_per_gpu=1) if next(model.parameters()).is_cuda: data = scatter(data, [device])[0] else: for m in model.modules(): if isinstance(m, (RoIPool, RoIAlign)): if (not m.aligned): m.use_torchvision = True warnings.warn('We set use_torchvision=True in CPU mode.') data['img_metas'] = data['img_metas'][0].data with torch.no_grad(): result = model(return_loss=False, rescale=True, **data) return result[0]<|docstring|>Inference image(s) with the detector. Args: model (nn.Module): The loaded detector. imgs (str/ndarray or list[str/ndarray]): Either image files or loaded images. Returns: If imgs is a str, a generator will be returned, otherwise return the detection results directly.<|endoftext|>
207f67dd87ec988b3549a0a139539ecf3ec5edb2114b4bfc7449a2b6d37baada
def py_cpu_nms(dets, thresh): 'Pure Python NMS baseline.' dets = np.array(dets) x1 = dets[(:, 0)] y1 = dets[(:, 1)] x2 = dets[(:, 2)] y2 = dets[(:, 3)] scores = dets[(:, 4)] areas = (((x2 - x1) + 1) * ((y2 - y1) + 1)) order = scores.argsort()[::(- 1)] keep = [] while (order.size > 0): i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, ((xx2 - xx1) + 1)) h = np.maximum(0.0, ((yy2 - yy1) + 1)) inter = (w * h) ovr = (inter / ((areas[i] + areas[order[1:]]) - inter)) inds = np.where((ovr <= thresh))[0] order = order[(inds + 1)] return keep
Pure Python NMS baseline.
UFPMP-Det-Tools/eval_script/ufpmp_det_eval.py
py_cpu_nms
PuAnysh/UFPMP-Det
9
python
def py_cpu_nms(dets, thresh): dets = np.array(dets) x1 = dets[(:, 0)] y1 = dets[(:, 1)] x2 = dets[(:, 2)] y2 = dets[(:, 3)] scores = dets[(:, 4)] areas = (((x2 - x1) + 1) * ((y2 - y1) + 1)) order = scores.argsort()[::(- 1)] keep = [] while (order.size > 0): i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, ((xx2 - xx1) + 1)) h = np.maximum(0.0, ((yy2 - yy1) + 1)) inter = (w * h) ovr = (inter / ((areas[i] + areas[order[1:]]) - inter)) inds = np.where((ovr <= thresh))[0] order = order[(inds + 1)] return keep
def py_cpu_nms(dets, thresh): dets = np.array(dets) x1 = dets[(:, 0)] y1 = dets[(:, 1)] x2 = dets[(:, 2)] y2 = dets[(:, 3)] scores = dets[(:, 4)] areas = (((x2 - x1) + 1) * ((y2 - y1) + 1)) order = scores.argsort()[::(- 1)] keep = [] while (order.size > 0): i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, ((xx2 - xx1) + 1)) h = np.maximum(0.0, ((yy2 - yy1) + 1)) inter = (w * h) ovr = (inter / ((areas[i] + areas[order[1:]]) - inter)) inds = np.where((ovr <= thresh))[0] order = order[(inds + 1)] return keep<|docstring|>Pure Python NMS baseline.<|endoftext|>
b5fdb3435d45051dca51a28210bb8e7086da30e9e01a28fa41b6866c8cb90cb9
def __call__(self, results, bbox=None, img_data=None): 'Call function to load images into results.\n\n Args:\n results (dict): A result dict contains the file name\n of the image to be read.\n\n Returns:\n dict: ``results`` will be returned containing loaded image.\n ' if isinstance(results['img'], str): results['filename'] = results['img'] results['ori_filename'] = results['img'] else: results['filename'] = None results['ori_filename'] = None if (img_data is None): img = mmcv.imread(results['img']) else: img = img_data if bbox: (x1, x2, y1, y2, _) = bbox img = img[(x1:x2, y1:y2, :)] results['img'] = img results['img_fields'] = ['img'] results['img_shape'] = img.shape results['ori_shape'] = img.shape return results
Call function to load images into results. Args: results (dict): A result dict contains the file name of the image to be read. Returns: dict: ``results`` will be returned containing loaded image.
UFPMP-Det-Tools/eval_script/ufpmp_det_eval.py
__call__
PuAnysh/UFPMP-Det
9
python
def __call__(self, results, bbox=None, img_data=None): 'Call function to load images into results.\n\n Args:\n results (dict): A result dict contains the file name\n of the image to be read.\n\n Returns:\n dict: ``results`` will be returned containing loaded image.\n ' if isinstance(results['img'], str): results['filename'] = results['img'] results['ori_filename'] = results['img'] else: results['filename'] = None results['ori_filename'] = None if (img_data is None): img = mmcv.imread(results['img']) else: img = img_data if bbox: (x1, x2, y1, y2, _) = bbox img = img[(x1:x2, y1:y2, :)] results['img'] = img results['img_fields'] = ['img'] results['img_shape'] = img.shape results['ori_shape'] = img.shape return results
def __call__(self, results, bbox=None, img_data=None): 'Call function to load images into results.\n\n Args:\n results (dict): A result dict contains the file name\n of the image to be read.\n\n Returns:\n dict: ``results`` will be returned containing loaded image.\n ' if isinstance(results['img'], str): results['filename'] = results['img'] results['ori_filename'] = results['img'] else: results['filename'] = None results['ori_filename'] = None if (img_data is None): img = mmcv.imread(results['img']) else: img = img_data if bbox: (x1, x2, y1, y2, _) = bbox img = img[(x1:x2, y1:y2, :)] results['img'] = img results['img_fields'] = ['img'] results['img_shape'] = img.shape results['ori_shape'] = img.shape return results<|docstring|>Call function to load images into results. Args: results (dict): A result dict contains the file name of the image to be read. Returns: dict: ``results`` will be returned containing loaded image.<|endoftext|>
fea8e7de41bc3058a86d5ab89ebed39d4df65d648bd945e8fd7195800911ddbb
def __init__(self): '\n Constructor that will appropriately initialize a supervised learning object\n @ In, None\n @ Out, None\n ' super().__init__() import sklearn import sklearn.multiclass self.model = sklearn.multiclass.OutputCodeClassifier
Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
framework/SupervisedLearning/ScikitLearn/MultiClass/OutputCodeClassifier.py
__init__
greenwoodms06/raven
1
python
def __init__(self): '\n Constructor that will appropriately initialize a supervised learning object\n @ In, None\n @ Out, None\n ' super().__init__() import sklearn import sklearn.multiclass self.model = sklearn.multiclass.OutputCodeClassifier
def __init__(self): '\n Constructor that will appropriately initialize a supervised learning object\n @ In, None\n @ Out, None\n ' super().__init__() import sklearn import sklearn.multiclass self.model = sklearn.multiclass.OutputCodeClassifier<|docstring|>Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None<|endoftext|>
655c31687e9737678c96d3c37d5f38871acc36ff63a6f2c9f2242a24ecc50cb1
@classmethod def getInputSpecification(cls): '\n Method to get a reference to a class that specifies the input data for\n class cls.\n @ In, cls, the class for which we are retrieving the specification\n @ Out, inputSpecification, InputData.ParameterInput, class to use for\n specifying input of cls.\n ' specs = super().getInputSpecification() specs.description = 'The \\xmlNode{OutputCodeClassifier} (\\textit{(Error-Correcting) Output-Code multiclass strategy})\n Output-code based strategies consist in representing each class with a binary code (an array of\n 0s and 1s). At fitting time, one binary classifier per bit in the code book is fitted. At\n prediction time, the classifiers are used to project new points in the class space and the class\n closest to the points is chosen. The main advantage of these strategies is that the number of\n classifiers used can be controlled by the user, either for compressing the model\n (0 < code\\_size < 1) or for making the model more robust to errors (code\\_size > 1). See the\n documentation for more details.\n \\zNormalizationNotPerformed{OutputCodeClassifier}\n ' estimatorInput = InputData.assemblyInputFactory('estimator', contentType=InputTypes.StringType, descr='name of a ROM that can be used as an estimator', default='no-default') specs.addSub(estimatorInput) specs.addSub(InputData.parameterInputFactory('code_size', contentType=InputTypes.FloatType, descr='Percentage of the number of classes to be used to create\n the code book. A number between 0 and 1 will require fewer classifiers\n than one-vs-the-rest. A number greater than 1 will require more classifiers\n than one-vs-the-rest.', default=1.5)) specs.addSub(InputData.parameterInputFactory('random_state', contentType=InputTypes.IntegerType, descr='The generator used to initialize the codebook. Pass an int\n for reproducible output across multiple function calls. ', default=None)) specs.addSub(InputData.parameterInputFactory('n_jobs', contentType=InputTypes.IntegerType, descr='TThe number of jobs to use for the computation: the n\\_classes one-vs-rest\n problems are computed in parallel. None means 1 unless in a joblib.parallel\\_backend\n context. -1 means using all processors. See Glossary for more details.', default=None)) return specs
Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls.
framework/SupervisedLearning/ScikitLearn/MultiClass/OutputCodeClassifier.py
getInputSpecification
greenwoodms06/raven
1
python
@classmethod def getInputSpecification(cls): '\n Method to get a reference to a class that specifies the input data for\n class cls.\n @ In, cls, the class for which we are retrieving the specification\n @ Out, inputSpecification, InputData.ParameterInput, class to use for\n specifying input of cls.\n ' specs = super().getInputSpecification() specs.description = 'The \\xmlNode{OutputCodeClassifier} (\\textit{(Error-Correcting) Output-Code multiclass strategy})\n Output-code based strategies consist in representing each class with a binary code (an array of\n 0s and 1s). At fitting time, one binary classifier per bit in the code book is fitted. At\n prediction time, the classifiers are used to project new points in the class space and the class\n closest to the points is chosen. The main advantage of these strategies is that the number of\n classifiers used can be controlled by the user, either for compressing the model\n (0 < code\\_size < 1) or for making the model more robust to errors (code\\_size > 1). See the\n documentation for more details.\n \\zNormalizationNotPerformed{OutputCodeClassifier}\n ' estimatorInput = InputData.assemblyInputFactory('estimator', contentType=InputTypes.StringType, descr='name of a ROM that can be used as an estimator', default='no-default') specs.addSub(estimatorInput) specs.addSub(InputData.parameterInputFactory('code_size', contentType=InputTypes.FloatType, descr='Percentage of the number of classes to be used to create\n the code book. A number between 0 and 1 will require fewer classifiers\n than one-vs-the-rest. A number greater than 1 will require more classifiers\n than one-vs-the-rest.', default=1.5)) specs.addSub(InputData.parameterInputFactory('random_state', contentType=InputTypes.IntegerType, descr='The generator used to initialize the codebook. Pass an int\n for reproducible output across multiple function calls. ', default=None)) specs.addSub(InputData.parameterInputFactory('n_jobs', contentType=InputTypes.IntegerType, descr='TThe number of jobs to use for the computation: the n\\_classes one-vs-rest\n problems are computed in parallel. None means 1 unless in a joblib.parallel\\_backend\n context. -1 means using all processors. See Glossary for more details.', default=None)) return specs
@classmethod def getInputSpecification(cls): '\n Method to get a reference to a class that specifies the input data for\n class cls.\n @ In, cls, the class for which we are retrieving the specification\n @ Out, inputSpecification, InputData.ParameterInput, class to use for\n specifying input of cls.\n ' specs = super().getInputSpecification() specs.description = 'The \\xmlNode{OutputCodeClassifier} (\\textit{(Error-Correcting) Output-Code multiclass strategy})\n Output-code based strategies consist in representing each class with a binary code (an array of\n 0s and 1s). At fitting time, one binary classifier per bit in the code book is fitted. At\n prediction time, the classifiers are used to project new points in the class space and the class\n closest to the points is chosen. The main advantage of these strategies is that the number of\n classifiers used can be controlled by the user, either for compressing the model\n (0 < code\\_size < 1) or for making the model more robust to errors (code\\_size > 1). See the\n documentation for more details.\n \\zNormalizationNotPerformed{OutputCodeClassifier}\n ' estimatorInput = InputData.assemblyInputFactory('estimator', contentType=InputTypes.StringType, descr='name of a ROM that can be used as an estimator', default='no-default') specs.addSub(estimatorInput) specs.addSub(InputData.parameterInputFactory('code_size', contentType=InputTypes.FloatType, descr='Percentage of the number of classes to be used to create\n the code book. A number between 0 and 1 will require fewer classifiers\n than one-vs-the-rest. A number greater than 1 will require more classifiers\n than one-vs-the-rest.', default=1.5)) specs.addSub(InputData.parameterInputFactory('random_state', contentType=InputTypes.IntegerType, descr='The generator used to initialize the codebook. Pass an int\n for reproducible output across multiple function calls. ', default=None)) specs.addSub(InputData.parameterInputFactory('n_jobs', contentType=InputTypes.IntegerType, descr='TThe number of jobs to use for the computation: the n\\_classes one-vs-rest\n problems are computed in parallel. None means 1 unless in a joblib.parallel\\_backend\n context. -1 means using all processors. See Glossary for more details.', default=None)) return specs<|docstring|>Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls.<|endoftext|>
d5c36203d4cb584faf29b263b27cd91068103eeac8de0405a517e24cd8559e5d
def _handleInput(self, paramInput): '\n Function to handle the common parts of the distribution parameter input.\n @ In, paramInput, ParameterInput, the already parsed input.\n @ Out, None\n ' super()._handleInput(paramInput) (settings, notFound) = paramInput.findNodesAndExtractValues(['code_size', 'random_state', 'n_jobs']) assert (not notFound) self.settings = settings
Function to handle the common parts of the distribution parameter input. @ In, paramInput, ParameterInput, the already parsed input. @ Out, None
framework/SupervisedLearning/ScikitLearn/MultiClass/OutputCodeClassifier.py
_handleInput
greenwoodms06/raven
1
python
def _handleInput(self, paramInput): '\n Function to handle the common parts of the distribution parameter input.\n @ In, paramInput, ParameterInput, the already parsed input.\n @ Out, None\n ' super()._handleInput(paramInput) (settings, notFound) = paramInput.findNodesAndExtractValues(['code_size', 'random_state', 'n_jobs']) assert (not notFound) self.settings = settings
def _handleInput(self, paramInput): '\n Function to handle the common parts of the distribution parameter input.\n @ In, paramInput, ParameterInput, the already parsed input.\n @ Out, None\n ' super()._handleInput(paramInput) (settings, notFound) = paramInput.findNodesAndExtractValues(['code_size', 'random_state', 'n_jobs']) assert (not notFound) self.settings = settings<|docstring|>Function to handle the common parts of the distribution parameter input. @ In, paramInput, ParameterInput, the already parsed input. @ Out, None<|endoftext|>
786787ce3e5a22bfa39bd78c88d0936f411b5cb0a296604a49272f6e39a50905
def setEstimator(self, estimatorList): '\n Initialization method\n @ In, estimatorList, list of ROM instances/estimators used by ROM\n @ Out, None\n ' if (len(estimatorList) != 1): self.raiseAWarning('ROM', self.name, 'can only accept one estimator, but multiple estimators are provided!', 'Only the first one will be used, i.e.,', estimator.name) estimator = estimatorList[0] if estimator._interfaceROM.multioutputWrapper: sklEstimator = estimator._interfaceROM.model.get_params()['estimator'] else: sklEstimator = estimator._interfaceROM.model if (not callable(getattr(sklEstimator, 'fit', None))): self.raiseAnError(IOError, 'estimator:', estimator.name, 'can not be used! Please change to a different estimator') else: self.raiseADebug('A valid estimator', estimator.name, 'is provided!') settings = {'estimator': sklEstimator} self.settings.update(settings) self.initializeModel(self.settings)
Initialization method @ In, estimatorList, list of ROM instances/estimators used by ROM @ Out, None
framework/SupervisedLearning/ScikitLearn/MultiClass/OutputCodeClassifier.py
setEstimator
greenwoodms06/raven
1
python
def setEstimator(self, estimatorList): '\n Initialization method\n @ In, estimatorList, list of ROM instances/estimators used by ROM\n @ Out, None\n ' if (len(estimatorList) != 1): self.raiseAWarning('ROM', self.name, 'can only accept one estimator, but multiple estimators are provided!', 'Only the first one will be used, i.e.,', estimator.name) estimator = estimatorList[0] if estimator._interfaceROM.multioutputWrapper: sklEstimator = estimator._interfaceROM.model.get_params()['estimator'] else: sklEstimator = estimator._interfaceROM.model if (not callable(getattr(sklEstimator, 'fit', None))): self.raiseAnError(IOError, 'estimator:', estimator.name, 'can not be used! Please change to a different estimator') else: self.raiseADebug('A valid estimator', estimator.name, 'is provided!') settings = {'estimator': sklEstimator} self.settings.update(settings) self.initializeModel(self.settings)
def setEstimator(self, estimatorList): '\n Initialization method\n @ In, estimatorList, list of ROM instances/estimators used by ROM\n @ Out, None\n ' if (len(estimatorList) != 1): self.raiseAWarning('ROM', self.name, 'can only accept one estimator, but multiple estimators are provided!', 'Only the first one will be used, i.e.,', estimator.name) estimator = estimatorList[0] if estimator._interfaceROM.multioutputWrapper: sklEstimator = estimator._interfaceROM.model.get_params()['estimator'] else: sklEstimator = estimator._interfaceROM.model if (not callable(getattr(sklEstimator, 'fit', None))): self.raiseAnError(IOError, 'estimator:', estimator.name, 'can not be used! Please change to a different estimator') else: self.raiseADebug('A valid estimator', estimator.name, 'is provided!') settings = {'estimator': sklEstimator} self.settings.update(settings) self.initializeModel(self.settings)<|docstring|>Initialization method @ In, estimatorList, list of ROM instances/estimators used by ROM @ Out, None<|endoftext|>
b11541dfc3544767bd47c523854676ffb0b87e4783f4e3be87c95cd1db8de212
def add_user(new_user): '\n Add new user to userlist\n ' User.add_user(new_user)
Add new user to userlist
start.py
add_user
IsaiahKe/flask_Vault
0
python
def add_user(new_user): '\n \n ' User.add_user(new_user)
def add_user(new_user): '\n \n ' User.add_user(new_user)<|docstring|>Add new user to userlist<|endoftext|>
ad1146ca3ce7e2c35643f22d723edd87f977e445f22c45e21423601d5ac24dbf
def add_credential(credential): '\n Add credential to credential list\n ' Credential.add_credential(credential)
Add credential to credential list
start.py
add_credential
IsaiahKe/flask_Vault
0
python
def add_credential(credential): '\n \n ' Credential.add_credential(credential)
def add_credential(credential): '\n \n ' Credential.add_credential(credential)<|docstring|>Add credential to credential list<|endoftext|>
2ea4c34a0c292cdc4b42fc68cb4016b5ddb67033d0cd187ca59bbfbbd6e460fb
def delete_all(): '\n empty all list\n ' Credential.delete_all()
empty all list
start.py
delete_all
IsaiahKe/flask_Vault
0
python
def delete_all(): '\n \n ' Credential.delete_all()
def delete_all(): '\n \n ' Credential.delete_all()<|docstring|>empty all list<|endoftext|>
72ff4f9840386d5398e4188c7fd7d31a85f35700963cbad76fff4ef1a91e43d9
def delete_by_account_name(name): '\n Delete by account name\n ' Credential.delete_by_account(name)
Delete by account name
start.py
delete_by_account_name
IsaiahKe/flask_Vault
0
python
def delete_by_account_name(name): '\n \n ' Credential.delete_by_account(name)
def delete_by_account_name(name): '\n \n ' Credential.delete_by_account(name)<|docstring|>Delete by account name<|endoftext|>
eecf4e5ce1a4e37d170a5a9abe1a06ba3a31f3888e427b22cac0d57f696b3350
def __init__(self, USER_API_KEY): "\n Parameters\n ----------\n USER_API_KEY: str\n User's API key generated from the Materials Project database.\n See https://materialsproject.org/open\n " self.user_api_key = USER_API_KEY self.fp = {} self.implemented_features = ['stoichiometry', 'electronegativity', 'mass', 'volume', 'density', 'bulk modulus', 'shear modulus', 'poisson ratio', 'anisotropy', 'spacegroup', 'ionic character'] self.selected_features = None self.label = None
Parameters ---------- USER_API_KEY: str User's API key generated from the Materials Project database. See https://materialsproject.org/open
gibbsml/ellingham/fingerprint.py
__init__
atomisticnet/gibbsml
5
python
def __init__(self, USER_API_KEY): "\n Parameters\n ----------\n USER_API_KEY: str\n User's API key generated from the Materials Project database.\n See https://materialsproject.org/open\n " self.user_api_key = USER_API_KEY self.fp = {} self.implemented_features = ['stoichiometry', 'electronegativity', 'mass', 'volume', 'density', 'bulk modulus', 'shear modulus', 'poisson ratio', 'anisotropy', 'spacegroup', 'ionic character'] self.selected_features = None self.label = None
def __init__(self, USER_API_KEY): "\n Parameters\n ----------\n USER_API_KEY: str\n User's API key generated from the Materials Project database.\n See https://materialsproject.org/open\n " self.user_api_key = USER_API_KEY self.fp = {} self.implemented_features = ['stoichiometry', 'electronegativity', 'mass', 'volume', 'density', 'bulk modulus', 'shear modulus', 'poisson ratio', 'anisotropy', 'spacegroup', 'ionic character'] self.selected_features = None self.label = None<|docstring|>Parameters ---------- USER_API_KEY: str User's API key generated from the Materials Project database. See https://materialsproject.org/open<|endoftext|>
6f5253652425662f4f5bde9afa1e3bab2faa1e174d3b95070f9699562d87b0de
def extract_mp_features(self, id_mo, id_m1='', id_m2='', id_oxygen='mp-12957', selected_features='all', label=None, mo_energy_correction=True): "\n Generates a feature set for an oxidation for a given metal\n oxide (AxByOz) from the elements (A and B).\n\n Parameters\n ----------\n id_mo: str\n Materials Project mp-id for the metal oxide or chemical formula\n of the metal oxide, e.g. 'Al2SiO5' or 'mp-4753'.\n id_m1: str\n (optional) Materials Project mp-id for the metal A, e.g. 'mp-134'.\n id_m2: str\n (optional) Materials Project mp-id for the metal B, e.g. 'mp-149'.\n id_oxygen: str\n Materials project mp-id for oxygen in the gas phase.\n selected_features: list or str\n (option 1): list\n List of selected features to be considered to\n generate the fingerprint. Implemented are: 'stoichiometry',\n 'electronegativity', 'mass', 'volume', 'density',\n 'bulk modulus', 'shear modulus', 'poisson ratio',\n 'anisotropy', 'spacegroup' and 'ionic character'.\n (option 2): str\n 'all': Include all implemented features (see option 1).\n 'ellingham': Recommended features for building models for\n predicting Ellingham diagrams. Includes only\n the following features:\n 'stoichiometry', 'electronegativity',\n 'density', 'bulk modulus', 'ionic character'.\n\n 'label': str\n Defines the label tag for the fingerprint. The user can chose a\n name for the fingerprint for the data entry, e.g. 'Al2SiO5-PBEU'.\n 'mo_energy_correction': bool\n If True the algorithm only selects Material Project entries which\n in which energy corrections are available. See:\n https://materialsproject.org/docs/calculations#Total_Energy_Adjustments\n\n " if (selected_features == 'all'): self.selected_features = self.implemented_features if (selected_features == 'ellingham'): self.selected_features = ['stoichiometry', 'electronegativity', 'density', 'bulk modulus', 'ionic character'] else: self.selected_features = selected_features print(('Getting information for ' + id_mo)) if ('mp' not in id_mo): id_mo = self._find_id(id_mo) with MPRester(self.user_api_key) as m: data_mo = m.get_data(id_mo)[0] with MPRester(self.user_api_key) as m: try: e_adjus = m.get_entries(id_mo)[0].__dict__['energy_adjustments'] e_mo_corr = 0 for e_ad in e_adjus: e_mo_corr += e_ad.value except: e_adjus = m.get_entries(id_mo)[0].__dict__['correction'] e_mo_corr = e_adjus if (mo_energy_correction is False): e_mo_corr = 0.0 data_o2 = m.get_data(id_oxygen)[0] e_o2 = ((2 * data_o2['energy']) / data_o2['unit_cell_formula']['O']) n_elements = data_mo['nelements'] binary_oxide = False if (n_elements == 3): binary_oxide = True msg = 'Only unary and binary oxides are implemented.' assert (n_elements <= 3), NotImplementedError(msg) elements = data_mo['elements'] element_no_ox = np.array(elements)[(~ np.isin(elements, 'O'))] if (binary_oxide is True): (element_m1, element_m2) = (element_no_ox[0], element_no_ox[1]) else: (element_m1, element_m2) = (element_no_ox[0], element_no_ox[0]) if ('mp' not in id_m1): id_m1 = self._find_id(element_m1) if ('mp' not in id_m2): id_m2 = self._find_id(element_m2) data_m1 = m.get_data(id_m1)[0] data_m2 = m.get_data(id_m2)[0] formula_mo = data_mo['pretty_formula'] formula_m1 = data_m1['pretty_formula'] formula_m2 = data_m2['pretty_formula'] self.label = label if (self.label is None): self.label = ((formula_mo + '_') + id_mo) self.fp.update({self.label: {}}) self.fp[self.label]['target_features'] = {} self.fp[self.label]['features'] = {} atoms = [] for i in ['m1', 'm2', 'mo']: f_atoms = open('tmp_Atoms.cif', 'w') f_atoms.write(eval(('data_' + i))['cif']) f_atoms.close() atoms.append(read('tmp_Atoms.cif')) os.remove('tmp_Atoms.cif') (atoms_m1, atoms_m2, atoms_mo) = atoms (n_m1, fu_m1) = (2 * (len(atoms_m1),)) (n_m2, fu_m2) = (2 * (len(atoms_m2),)) fu_mo = self._get_atoms_per_unit_formula(atoms_mo) n_m1_in_mo = self._get_number_of_atoms_element(atoms_mo, symbol=element_m1) n_m1_in_mo /= fu_mo n_m2_in_mo = self._get_number_of_atoms_element(atoms_mo, symbol=element_m2) n_m2_in_mo /= fu_mo n_ox_in_mo = self._get_number_of_atoms_element(atoms_mo, symbol='O') n_ox_in_mo /= fu_mo self.fp[self.label]['raw data'] = {} self.fp[self.label]['raw data']['data mo'] = data_mo self.fp[self.label]['raw data']['data m1'] = data_m1 self.fp[self.label]['raw data']['data m2'] = data_m2 (e_m1, e_m2) = (data_m1['energy'], data_m2['energy']) e_mo = data_mo['energy'] (x, y, z) = (n_m1_in_mo, n_m2_in_mo, n_ox_in_mo) a = ((2 / z) * x) b = ((2 / z) * y) c = (2 / z) if (not binary_oxide): a /= 2 b /= 2 dH0 = ((c * (e_mo + e_mo_corr)) / fu_mo) dH0 -= ((a * e_m1) / fu_m1) dH0 -= ((b * e_m2) / fu_m2) dH0 -= e_o2 dH0 *= 96.485 self.add_feature(description='formation energy (kJ/mol)', value=dH0) balanced_reaction = None if (not binary_oxide): balanced_reaction = (((str((2 * a)) + ' ') + formula_m1) + ' + O2') balanced_reaction += ' --> ' balanced_reaction += ((str(c) + ' ') + formula_mo) if binary_oxide: balanced_reaction = (((str(a) + ' ') + formula_m1) + ' + ') balanced_reaction += (((str(b) + ' ') + formula_m2) + ' + O2') balanced_reaction += ' --> ' balanced_reaction += ((str(c) + ' ') + formula_mo) self.fp[self.label]['balanced reaction'] = balanced_reaction if ('stoichiometry' in self.selected_features): ratio_o_m1 = (n_m1_in_mo / n_ox_in_mo) ratio_o_m2 = (n_m2_in_mo / n_ox_in_mo) av_ox_state = ((n_ox_in_mo * 2) / (n_m1_in_mo + n_m2_in_mo)) (element_m1, element_m2) = (atoms_m1[0].symbol, atoms_m2[0].symbol) z_m1 = element(element_m1).atomic_number z_m2 = element(element_m2).atomic_number self.add_feature(description='ratio metal oxygen (mean)', value=np.mean([ratio_o_m1, ratio_o_m2])) self.add_feature(description='ratio metal oxygen (var)', value=np.var([ratio_o_m1, ratio_o_m2])) self.add_feature(description='average oxidation state', value=av_ox_state) self.add_feature(description='atomic number (mean)', value=np.mean([z_m1, z_m2])) self.add_feature(description='atomic number (var)', value=np.var([z_m1, z_m2])) if ('electronegativity' in self.selected_features): elecneg_m1 = element(element_m1).en_pauling elecneg_m2 = element(element_m2).en_pauling self.add_feature(description='pauling electronegativity (mean)', value=np.mean([elecneg_m1, elecneg_m2])) self.add_feature(description='pauling electronegativity (var)', value=np.var([elecneg_m1, elecneg_m2])) if ('ionic character' in self.selected_features): elnegdif_m1 = (element('O').en_pauling - element(element_m1).en_pauling) elnegdif_m2 = (element('O').en_pauling - element(element_m2).en_pauling) pio_m1 = (100 * (1 - np.exp((- (((1 / 2) * elnegdif_m1) ** 2))))) pio_m2 = (100 * (1 - np.exp((- (((1 / 2) * elnegdif_m2) ** 2))))) self.add_feature(description='% ionic character (mean)', value=np.mean([pio_m1, pio_m2])) self.add_feature(description='% ionic character (var)', value=np.var([pio_m1, pio_m2])) if ('volume' in self.selected_features): V_m1 = atoms_m1.get_volume() V_per_fu_m1 = (V_m1 / fu_m1) V_m2 = atoms_m2.get_volume() V_per_fu_m2 = (V_m2 / fu_m2) V_mo = atoms_mo.get_volume() V_per_fu_mo = (V_mo / fu_mo) self.add_feature(description='volume per formula unit (mean)', value=np.mean([V_per_fu_m1, V_per_fu_m2])) self.add_feature(description='volume per formula unit (var)', value=np.var([V_per_fu_m1, V_per_fu_m2])) self.add_feature(description='volume MO per formula unit', value=V_per_fu_mo) diff_V_per_fu_m1_mo = (V_per_fu_mo - V_per_fu_m1) diff_V_per_fu_m2_mo = (V_per_fu_mo - V_per_fu_m2) self.add_feature(description='difference volume (MO-M) (mean)', value=np.mean([diff_V_per_fu_m1_mo, diff_V_per_fu_m2_mo])) self.add_feature(description='difference volume (MO-M) (var)', value=np.var([diff_V_per_fu_m1_mo, diff_V_per_fu_m2_mo])) if ('mass' in self.selected_features): mass_m1 = np.average(atoms_m1.get_masses()) mass_m2 = np.average(atoms_m2.get_masses()) mass_mo = np.average(atoms_mo.get_masses()) mass_per_fu_m1 = (mass_m1 / fu_m1) mass_per_fu_m2 = (mass_m2 / fu_m2) mass_per_fu_mo = (mass_mo / fu_mo) self.add_feature(description='mass per formula unit (mean)', value=np.mean([mass_per_fu_m1, mass_per_fu_m2])) self.add_feature(description='mass per formula unit (var)', value=np.var([mass_per_fu_m1, mass_per_fu_m2])) self.add_feature(description='mass MO per formula unit', value=mass_per_fu_mo) diff_mass_per_fu_m1_mo = (mass_per_fu_mo - mass_per_fu_m1) diff_mass_per_fu_m2_mo = (mass_per_fu_mo - mass_per_fu_m2) self.add_feature(description='difference mass (MO-M) (mean)', value=np.mean([diff_mass_per_fu_m1_mo, diff_mass_per_fu_m2_mo])) self.add_feature(description='difference mass (MO-M) (var)', value=np.var([diff_mass_per_fu_m1_mo, diff_mass_per_fu_m2_mo])) if ('density' in self.selected_features): dens_m1 = data_m1['density'] dens_m2 = data_m2['density'] dens_mo = data_mo['density'] self.add_feature(description='density (mean)', value=np.mean([dens_m1, dens_m2])) self.add_feature(description='density (var)', value=np.var([dens_m1, dens_m2])) self.add_feature(description='density MO', value=dens_mo) diff_dens_m1_mo = (dens_mo - dens_m1) diff_dens_m2_mo = (dens_mo - dens_m2) self.add_feature(description='difference density (MO-M) (mean)', value=np.mean([diff_dens_m1_mo, diff_dens_m2_mo])) self.add_feature(description='difference density (MO-M) (var)', value=np.var([diff_dens_m1_mo, diff_dens_m2_mo])) if ('bulk modulus' in self.selected_features): elas_m1 = data_m1['elasticity'] elas_m2 = data_m2['elasticity'] elas_mo = data_mo['elasticity'] (Kv_m1, Kv_m2) = Kv_mo = (elas_m1['K_Voigt'], elas_m2['K_Voigt']) if elas_mo: Kv_mo = elas_mo['K_Voigt'] else: with MPRester(self.user_api_key) as m: Kv_mo = m.get_data(id_mo, prop='elastic_moduli', data_type='pred')[0]['elastic_moduli']['K'] self.add_feature(description='bulk modulus (mean)', value=np.mean([Kv_m1, Kv_m2])) self.add_feature(description='bulk modulus (var)', value=np.var([Kv_m1, Kv_m2])) self.add_feature(description='bulk modulus MO', value=Kv_mo) diff_Kv_m1_mo = (Kv_mo - Kv_m1) diff_Kv_m2_mo = (Kv_mo - Kv_m2) self.add_feature(description='difference bulk modulus (MO-M) (mean)', value=np.mean([diff_Kv_m1_mo, diff_Kv_m2_mo])) self.add_feature(description='difference bulk modulus (MO-M) (var)', value=np.var([diff_Kv_m1_mo, diff_Kv_m2_mo])) if ('shear modulus' in self.selected_features): elas_m1 = data_m1['elasticity'] elas_m2 = data_m2['elasticity'] elas_mo = data_mo['elasticity'] (Gv_m1, Gv_m2) = (elas_m1['G_Voigt'], elas_m2['G_Voigt']) if elas_mo: Gv_mo = elas_mo['G_Voigt'] else: with MPRester(self.user_api_key) as m: Gv_mo = m.get_data(id_mo, prop='elastic_moduli', data_type='pred')[0]['elastic_moduli']['G'] self.add_feature(description='shear modulus (mean)', value=np.mean([Gv_m1, Gv_m2])) self.add_feature(description='shear modulus (var)', value=np.var([Gv_m1, Gv_m2])) self.add_feature(description='shear modulus MO', value=Gv_mo) diff_Gv_m1_mo = (Gv_mo - Gv_m1) diff_Gv_m2_mo = (Gv_mo - Gv_m2) self.add_feature(description='difference shear modulus (MO-M) (mean)', value=np.mean([diff_Gv_m1_mo, diff_Gv_m2_mo])) self.add_feature(description='difference shear modulus (MO-M) (var)', value=np.var([diff_Gv_m1_mo, diff_Gv_m2_mo])) if ('poisson ratio' in self.selected_features): elas_m1 = data_m1['elasticity'] elas_m2 = data_m2['elasticity'] elas_mo = data_mo['elasticity'] (pois_m1, pois_m2, pois_mo) = (elas_m1['poisson_ratio'], elas_m2['poisson_ratio'], elas_mo['poisson_ratio']) self.add_feature(description='poisson ratio (mean)', value=np.mean([pois_m1, pois_m2])) self.add_feature(description='poisson ratio (var)', value=np.var([pois_m1, pois_m2])) self.add_feature(description='poisson ratio MO', value=pois_mo) diff_pois_m1_mo = (pois_mo - pois_m1) diff_pois_m2_mo = (pois_mo - pois_m2) self.add_feature(description='difference poisson ratio (MO-M) (mean)', value=np.mean([diff_pois_m1_mo, diff_pois_m2_mo])) self.add_feature(description='difference poisson ratio (MO-M) (var)', value=np.var([diff_pois_m1_mo, diff_pois_m2_mo])) if ('anisotropy' in self.selected_features): elas_m1 = data_m1['elasticity'] elas_m2 = data_m2['elasticity'] elas_mo = data_mo['elasticity'] (u_ani_m1, u_ani_m2, u_ani_mo) = (elas_m1['universal_anisotropy'], elas_m2['universal_anisotropy'], elas_mo['universal_anisotropy']) (el_ani_m1, el_ani_m2, el_ani_mo) = (elas_m1['elastic_anisotropy'], elas_m2['elastic_anisotropy'], elas_mo['elastic_anisotropy']) self.add_feature(description='universal anisotropy (mean)', value=np.mean([u_ani_m1, u_ani_m2])) self.add_feature(description='universal anisotropy (var)', value=np.var([u_ani_m1, u_ani_m2])) self.add_feature(description='universal anisotropy MO', value=u_ani_mo) diff_u_ani_m1_mo = (u_ani_mo - u_ani_m1) diff_u_ani_m2_mo = (u_ani_mo - u_ani_m2) self.add_feature(description='difference universal anisotropy (MO-M) (mean)', value=np.mean([diff_u_ani_m1_mo, diff_u_ani_m2_mo])) self.add_feature(description='difference universal anisotropy (MO-M) (var)', value=np.var([diff_u_ani_m1_mo, diff_u_ani_m2_mo])) self.add_feature(description='elastic anisotropy (mean)', value=np.mean([el_ani_m1, el_ani_m2])) self.add_feature(description='elastic anisotropy (var)', value=np.var([el_ani_m1, el_ani_m2])) self.add_feature(description='elastic anisotropy MO', value=el_ani_mo) diff_el_ani_m1_mo = (el_ani_mo - el_ani_m1) diff_el_ani_m2_mo = (el_ani_mo - el_ani_m2) self.add_feature(description='difference elastic anisotropy (MO-M) (mean)', value=np.mean([diff_el_ani_m1_mo, diff_el_ani_m2_mo])) self.add_feature(description='difference elastic anisotropy (MO-M) (var)', value=np.var([diff_el_ani_m1_mo, diff_el_ani_m2_mo])) if ('spacegroup' in self.selected_features): spacegroup_m1 = data_m1['spacegroup']['number'] spacegroup_m2 = data_m2['spacegroup']['number'] spacegroup_mo = data_mo['spacegroup']['number'] self.add_feature(description='Spacegroup M1', value=spacegroup_m1) self.add_feature(description='Spacegroup M2', value=spacegroup_m2) self.add_feature(description='Spacegroup MO', value=spacegroup_mo) print((('Fingerprint for ' + self.label) + ' completed.'))
Generates a feature set for an oxidation for a given metal oxide (AxByOz) from the elements (A and B). Parameters ---------- id_mo: str Materials Project mp-id for the metal oxide or chemical formula of the metal oxide, e.g. 'Al2SiO5' or 'mp-4753'. id_m1: str (optional) Materials Project mp-id for the metal A, e.g. 'mp-134'. id_m2: str (optional) Materials Project mp-id for the metal B, e.g. 'mp-149'. id_oxygen: str Materials project mp-id for oxygen in the gas phase. selected_features: list or str (option 1): list List of selected features to be considered to generate the fingerprint. Implemented are: 'stoichiometry', 'electronegativity', 'mass', 'volume', 'density', 'bulk modulus', 'shear modulus', 'poisson ratio', 'anisotropy', 'spacegroup' and 'ionic character'. (option 2): str 'all': Include all implemented features (see option 1). 'ellingham': Recommended features for building models for predicting Ellingham diagrams. Includes only the following features: 'stoichiometry', 'electronegativity', 'density', 'bulk modulus', 'ionic character'. 'label': str Defines the label tag for the fingerprint. The user can chose a name for the fingerprint for the data entry, e.g. 'Al2SiO5-PBEU'. 'mo_energy_correction': bool If True the algorithm only selects Material Project entries which in which energy corrections are available. See: https://materialsproject.org/docs/calculations#Total_Energy_Adjustments
gibbsml/ellingham/fingerprint.py
extract_mp_features
atomisticnet/gibbsml
5
python
def extract_mp_features(self, id_mo, id_m1=, id_m2=, id_oxygen='mp-12957', selected_features='all', label=None, mo_energy_correction=True): "\n Generates a feature set for an oxidation for a given metal\n oxide (AxByOz) from the elements (A and B).\n\n Parameters\n ----------\n id_mo: str\n Materials Project mp-id for the metal oxide or chemical formula\n of the metal oxide, e.g. 'Al2SiO5' or 'mp-4753'.\n id_m1: str\n (optional) Materials Project mp-id for the metal A, e.g. 'mp-134'.\n id_m2: str\n (optional) Materials Project mp-id for the metal B, e.g. 'mp-149'.\n id_oxygen: str\n Materials project mp-id for oxygen in the gas phase.\n selected_features: list or str\n (option 1): list\n List of selected features to be considered to\n generate the fingerprint. Implemented are: 'stoichiometry',\n 'electronegativity', 'mass', 'volume', 'density',\n 'bulk modulus', 'shear modulus', 'poisson ratio',\n 'anisotropy', 'spacegroup' and 'ionic character'.\n (option 2): str\n 'all': Include all implemented features (see option 1).\n 'ellingham': Recommended features for building models for\n predicting Ellingham diagrams. Includes only\n the following features:\n 'stoichiometry', 'electronegativity',\n 'density', 'bulk modulus', 'ionic character'.\n\n 'label': str\n Defines the label tag for the fingerprint. The user can chose a\n name for the fingerprint for the data entry, e.g. 'Al2SiO5-PBEU'.\n 'mo_energy_correction': bool\n If True the algorithm only selects Material Project entries which\n in which energy corrections are available. See:\n https://materialsproject.org/docs/calculations#Total_Energy_Adjustments\n\n " if (selected_features == 'all'): self.selected_features = self.implemented_features if (selected_features == 'ellingham'): self.selected_features = ['stoichiometry', 'electronegativity', 'density', 'bulk modulus', 'ionic character'] else: self.selected_features = selected_features print(('Getting information for ' + id_mo)) if ('mp' not in id_mo): id_mo = self._find_id(id_mo) with MPRester(self.user_api_key) as m: data_mo = m.get_data(id_mo)[0] with MPRester(self.user_api_key) as m: try: e_adjus = m.get_entries(id_mo)[0].__dict__['energy_adjustments'] e_mo_corr = 0 for e_ad in e_adjus: e_mo_corr += e_ad.value except: e_adjus = m.get_entries(id_mo)[0].__dict__['correction'] e_mo_corr = e_adjus if (mo_energy_correction is False): e_mo_corr = 0.0 data_o2 = m.get_data(id_oxygen)[0] e_o2 = ((2 * data_o2['energy']) / data_o2['unit_cell_formula']['O']) n_elements = data_mo['nelements'] binary_oxide = False if (n_elements == 3): binary_oxide = True msg = 'Only unary and binary oxides are implemented.' assert (n_elements <= 3), NotImplementedError(msg) elements = data_mo['elements'] element_no_ox = np.array(elements)[(~ np.isin(elements, 'O'))] if (binary_oxide is True): (element_m1, element_m2) = (element_no_ox[0], element_no_ox[1]) else: (element_m1, element_m2) = (element_no_ox[0], element_no_ox[0]) if ('mp' not in id_m1): id_m1 = self._find_id(element_m1) if ('mp' not in id_m2): id_m2 = self._find_id(element_m2) data_m1 = m.get_data(id_m1)[0] data_m2 = m.get_data(id_m2)[0] formula_mo = data_mo['pretty_formula'] formula_m1 = data_m1['pretty_formula'] formula_m2 = data_m2['pretty_formula'] self.label = label if (self.label is None): self.label = ((formula_mo + '_') + id_mo) self.fp.update({self.label: {}}) self.fp[self.label]['target_features'] = {} self.fp[self.label]['features'] = {} atoms = [] for i in ['m1', 'm2', 'mo']: f_atoms = open('tmp_Atoms.cif', 'w') f_atoms.write(eval(('data_' + i))['cif']) f_atoms.close() atoms.append(read('tmp_Atoms.cif')) os.remove('tmp_Atoms.cif') (atoms_m1, atoms_m2, atoms_mo) = atoms (n_m1, fu_m1) = (2 * (len(atoms_m1),)) (n_m2, fu_m2) = (2 * (len(atoms_m2),)) fu_mo = self._get_atoms_per_unit_formula(atoms_mo) n_m1_in_mo = self._get_number_of_atoms_element(atoms_mo, symbol=element_m1) n_m1_in_mo /= fu_mo n_m2_in_mo = self._get_number_of_atoms_element(atoms_mo, symbol=element_m2) n_m2_in_mo /= fu_mo n_ox_in_mo = self._get_number_of_atoms_element(atoms_mo, symbol='O') n_ox_in_mo /= fu_mo self.fp[self.label]['raw data'] = {} self.fp[self.label]['raw data']['data mo'] = data_mo self.fp[self.label]['raw data']['data m1'] = data_m1 self.fp[self.label]['raw data']['data m2'] = data_m2 (e_m1, e_m2) = (data_m1['energy'], data_m2['energy']) e_mo = data_mo['energy'] (x, y, z) = (n_m1_in_mo, n_m2_in_mo, n_ox_in_mo) a = ((2 / z) * x) b = ((2 / z) * y) c = (2 / z) if (not binary_oxide): a /= 2 b /= 2 dH0 = ((c * (e_mo + e_mo_corr)) / fu_mo) dH0 -= ((a * e_m1) / fu_m1) dH0 -= ((b * e_m2) / fu_m2) dH0 -= e_o2 dH0 *= 96.485 self.add_feature(description='formation energy (kJ/mol)', value=dH0) balanced_reaction = None if (not binary_oxide): balanced_reaction = (((str((2 * a)) + ' ') + formula_m1) + ' + O2') balanced_reaction += ' --> ' balanced_reaction += ((str(c) + ' ') + formula_mo) if binary_oxide: balanced_reaction = (((str(a) + ' ') + formula_m1) + ' + ') balanced_reaction += (((str(b) + ' ') + formula_m2) + ' + O2') balanced_reaction += ' --> ' balanced_reaction += ((str(c) + ' ') + formula_mo) self.fp[self.label]['balanced reaction'] = balanced_reaction if ('stoichiometry' in self.selected_features): ratio_o_m1 = (n_m1_in_mo / n_ox_in_mo) ratio_o_m2 = (n_m2_in_mo / n_ox_in_mo) av_ox_state = ((n_ox_in_mo * 2) / (n_m1_in_mo + n_m2_in_mo)) (element_m1, element_m2) = (atoms_m1[0].symbol, atoms_m2[0].symbol) z_m1 = element(element_m1).atomic_number z_m2 = element(element_m2).atomic_number self.add_feature(description='ratio metal oxygen (mean)', value=np.mean([ratio_o_m1, ratio_o_m2])) self.add_feature(description='ratio metal oxygen (var)', value=np.var([ratio_o_m1, ratio_o_m2])) self.add_feature(description='average oxidation state', value=av_ox_state) self.add_feature(description='atomic number (mean)', value=np.mean([z_m1, z_m2])) self.add_feature(description='atomic number (var)', value=np.var([z_m1, z_m2])) if ('electronegativity' in self.selected_features): elecneg_m1 = element(element_m1).en_pauling elecneg_m2 = element(element_m2).en_pauling self.add_feature(description='pauling electronegativity (mean)', value=np.mean([elecneg_m1, elecneg_m2])) self.add_feature(description='pauling electronegativity (var)', value=np.var([elecneg_m1, elecneg_m2])) if ('ionic character' in self.selected_features): elnegdif_m1 = (element('O').en_pauling - element(element_m1).en_pauling) elnegdif_m2 = (element('O').en_pauling - element(element_m2).en_pauling) pio_m1 = (100 * (1 - np.exp((- (((1 / 2) * elnegdif_m1) ** 2))))) pio_m2 = (100 * (1 - np.exp((- (((1 / 2) * elnegdif_m2) ** 2))))) self.add_feature(description='% ionic character (mean)', value=np.mean([pio_m1, pio_m2])) self.add_feature(description='% ionic character (var)', value=np.var([pio_m1, pio_m2])) if ('volume' in self.selected_features): V_m1 = atoms_m1.get_volume() V_per_fu_m1 = (V_m1 / fu_m1) V_m2 = atoms_m2.get_volume() V_per_fu_m2 = (V_m2 / fu_m2) V_mo = atoms_mo.get_volume() V_per_fu_mo = (V_mo / fu_mo) self.add_feature(description='volume per formula unit (mean)', value=np.mean([V_per_fu_m1, V_per_fu_m2])) self.add_feature(description='volume per formula unit (var)', value=np.var([V_per_fu_m1, V_per_fu_m2])) self.add_feature(description='volume MO per formula unit', value=V_per_fu_mo) diff_V_per_fu_m1_mo = (V_per_fu_mo - V_per_fu_m1) diff_V_per_fu_m2_mo = (V_per_fu_mo - V_per_fu_m2) self.add_feature(description='difference volume (MO-M) (mean)', value=np.mean([diff_V_per_fu_m1_mo, diff_V_per_fu_m2_mo])) self.add_feature(description='difference volume (MO-M) (var)', value=np.var([diff_V_per_fu_m1_mo, diff_V_per_fu_m2_mo])) if ('mass' in self.selected_features): mass_m1 = np.average(atoms_m1.get_masses()) mass_m2 = np.average(atoms_m2.get_masses()) mass_mo = np.average(atoms_mo.get_masses()) mass_per_fu_m1 = (mass_m1 / fu_m1) mass_per_fu_m2 = (mass_m2 / fu_m2) mass_per_fu_mo = (mass_mo / fu_mo) self.add_feature(description='mass per formula unit (mean)', value=np.mean([mass_per_fu_m1, mass_per_fu_m2])) self.add_feature(description='mass per formula unit (var)', value=np.var([mass_per_fu_m1, mass_per_fu_m2])) self.add_feature(description='mass MO per formula unit', value=mass_per_fu_mo) diff_mass_per_fu_m1_mo = (mass_per_fu_mo - mass_per_fu_m1) diff_mass_per_fu_m2_mo = (mass_per_fu_mo - mass_per_fu_m2) self.add_feature(description='difference mass (MO-M) (mean)', value=np.mean([diff_mass_per_fu_m1_mo, diff_mass_per_fu_m2_mo])) self.add_feature(description='difference mass (MO-M) (var)', value=np.var([diff_mass_per_fu_m1_mo, diff_mass_per_fu_m2_mo])) if ('density' in self.selected_features): dens_m1 = data_m1['density'] dens_m2 = data_m2['density'] dens_mo = data_mo['density'] self.add_feature(description='density (mean)', value=np.mean([dens_m1, dens_m2])) self.add_feature(description='density (var)', value=np.var([dens_m1, dens_m2])) self.add_feature(description='density MO', value=dens_mo) diff_dens_m1_mo = (dens_mo - dens_m1) diff_dens_m2_mo = (dens_mo - dens_m2) self.add_feature(description='difference density (MO-M) (mean)', value=np.mean([diff_dens_m1_mo, diff_dens_m2_mo])) self.add_feature(description='difference density (MO-M) (var)', value=np.var([diff_dens_m1_mo, diff_dens_m2_mo])) if ('bulk modulus' in self.selected_features): elas_m1 = data_m1['elasticity'] elas_m2 = data_m2['elasticity'] elas_mo = data_mo['elasticity'] (Kv_m1, Kv_m2) = Kv_mo = (elas_m1['K_Voigt'], elas_m2['K_Voigt']) if elas_mo: Kv_mo = elas_mo['K_Voigt'] else: with MPRester(self.user_api_key) as m: Kv_mo = m.get_data(id_mo, prop='elastic_moduli', data_type='pred')[0]['elastic_moduli']['K'] self.add_feature(description='bulk modulus (mean)', value=np.mean([Kv_m1, Kv_m2])) self.add_feature(description='bulk modulus (var)', value=np.var([Kv_m1, Kv_m2])) self.add_feature(description='bulk modulus MO', value=Kv_mo) diff_Kv_m1_mo = (Kv_mo - Kv_m1) diff_Kv_m2_mo = (Kv_mo - Kv_m2) self.add_feature(description='difference bulk modulus (MO-M) (mean)', value=np.mean([diff_Kv_m1_mo, diff_Kv_m2_mo])) self.add_feature(description='difference bulk modulus (MO-M) (var)', value=np.var([diff_Kv_m1_mo, diff_Kv_m2_mo])) if ('shear modulus' in self.selected_features): elas_m1 = data_m1['elasticity'] elas_m2 = data_m2['elasticity'] elas_mo = data_mo['elasticity'] (Gv_m1, Gv_m2) = (elas_m1['G_Voigt'], elas_m2['G_Voigt']) if elas_mo: Gv_mo = elas_mo['G_Voigt'] else: with MPRester(self.user_api_key) as m: Gv_mo = m.get_data(id_mo, prop='elastic_moduli', data_type='pred')[0]['elastic_moduli']['G'] self.add_feature(description='shear modulus (mean)', value=np.mean([Gv_m1, Gv_m2])) self.add_feature(description='shear modulus (var)', value=np.var([Gv_m1, Gv_m2])) self.add_feature(description='shear modulus MO', value=Gv_mo) diff_Gv_m1_mo = (Gv_mo - Gv_m1) diff_Gv_m2_mo = (Gv_mo - Gv_m2) self.add_feature(description='difference shear modulus (MO-M) (mean)', value=np.mean([diff_Gv_m1_mo, diff_Gv_m2_mo])) self.add_feature(description='difference shear modulus (MO-M) (var)', value=np.var([diff_Gv_m1_mo, diff_Gv_m2_mo])) if ('poisson ratio' in self.selected_features): elas_m1 = data_m1['elasticity'] elas_m2 = data_m2['elasticity'] elas_mo = data_mo['elasticity'] (pois_m1, pois_m2, pois_mo) = (elas_m1['poisson_ratio'], elas_m2['poisson_ratio'], elas_mo['poisson_ratio']) self.add_feature(description='poisson ratio (mean)', value=np.mean([pois_m1, pois_m2])) self.add_feature(description='poisson ratio (var)', value=np.var([pois_m1, pois_m2])) self.add_feature(description='poisson ratio MO', value=pois_mo) diff_pois_m1_mo = (pois_mo - pois_m1) diff_pois_m2_mo = (pois_mo - pois_m2) self.add_feature(description='difference poisson ratio (MO-M) (mean)', value=np.mean([diff_pois_m1_mo, diff_pois_m2_mo])) self.add_feature(description='difference poisson ratio (MO-M) (var)', value=np.var([diff_pois_m1_mo, diff_pois_m2_mo])) if ('anisotropy' in self.selected_features): elas_m1 = data_m1['elasticity'] elas_m2 = data_m2['elasticity'] elas_mo = data_mo['elasticity'] (u_ani_m1, u_ani_m2, u_ani_mo) = (elas_m1['universal_anisotropy'], elas_m2['universal_anisotropy'], elas_mo['universal_anisotropy']) (el_ani_m1, el_ani_m2, el_ani_mo) = (elas_m1['elastic_anisotropy'], elas_m2['elastic_anisotropy'], elas_mo['elastic_anisotropy']) self.add_feature(description='universal anisotropy (mean)', value=np.mean([u_ani_m1, u_ani_m2])) self.add_feature(description='universal anisotropy (var)', value=np.var([u_ani_m1, u_ani_m2])) self.add_feature(description='universal anisotropy MO', value=u_ani_mo) diff_u_ani_m1_mo = (u_ani_mo - u_ani_m1) diff_u_ani_m2_mo = (u_ani_mo - u_ani_m2) self.add_feature(description='difference universal anisotropy (MO-M) (mean)', value=np.mean([diff_u_ani_m1_mo, diff_u_ani_m2_mo])) self.add_feature(description='difference universal anisotropy (MO-M) (var)', value=np.var([diff_u_ani_m1_mo, diff_u_ani_m2_mo])) self.add_feature(description='elastic anisotropy (mean)', value=np.mean([el_ani_m1, el_ani_m2])) self.add_feature(description='elastic anisotropy (var)', value=np.var([el_ani_m1, el_ani_m2])) self.add_feature(description='elastic anisotropy MO', value=el_ani_mo) diff_el_ani_m1_mo = (el_ani_mo - el_ani_m1) diff_el_ani_m2_mo = (el_ani_mo - el_ani_m2) self.add_feature(description='difference elastic anisotropy (MO-M) (mean)', value=np.mean([diff_el_ani_m1_mo, diff_el_ani_m2_mo])) self.add_feature(description='difference elastic anisotropy (MO-M) (var)', value=np.var([diff_el_ani_m1_mo, diff_el_ani_m2_mo])) if ('spacegroup' in self.selected_features): spacegroup_m1 = data_m1['spacegroup']['number'] spacegroup_m2 = data_m2['spacegroup']['number'] spacegroup_mo = data_mo['spacegroup']['number'] self.add_feature(description='Spacegroup M1', value=spacegroup_m1) self.add_feature(description='Spacegroup M2', value=spacegroup_m2) self.add_feature(description='Spacegroup MO', value=spacegroup_mo) print((('Fingerprint for ' + self.label) + ' completed.'))
def extract_mp_features(self, id_mo, id_m1=, id_m2=, id_oxygen='mp-12957', selected_features='all', label=None, mo_energy_correction=True): "\n Generates a feature set for an oxidation for a given metal\n oxide (AxByOz) from the elements (A and B).\n\n Parameters\n ----------\n id_mo: str\n Materials Project mp-id for the metal oxide or chemical formula\n of the metal oxide, e.g. 'Al2SiO5' or 'mp-4753'.\n id_m1: str\n (optional) Materials Project mp-id for the metal A, e.g. 'mp-134'.\n id_m2: str\n (optional) Materials Project mp-id for the metal B, e.g. 'mp-149'.\n id_oxygen: str\n Materials project mp-id for oxygen in the gas phase.\n selected_features: list or str\n (option 1): list\n List of selected features to be considered to\n generate the fingerprint. Implemented are: 'stoichiometry',\n 'electronegativity', 'mass', 'volume', 'density',\n 'bulk modulus', 'shear modulus', 'poisson ratio',\n 'anisotropy', 'spacegroup' and 'ionic character'.\n (option 2): str\n 'all': Include all implemented features (see option 1).\n 'ellingham': Recommended features for building models for\n predicting Ellingham diagrams. Includes only\n the following features:\n 'stoichiometry', 'electronegativity',\n 'density', 'bulk modulus', 'ionic character'.\n\n 'label': str\n Defines the label tag for the fingerprint. The user can chose a\n name for the fingerprint for the data entry, e.g. 'Al2SiO5-PBEU'.\n 'mo_energy_correction': bool\n If True the algorithm only selects Material Project entries which\n in which energy corrections are available. See:\n https://materialsproject.org/docs/calculations#Total_Energy_Adjustments\n\n " if (selected_features == 'all'): self.selected_features = self.implemented_features if (selected_features == 'ellingham'): self.selected_features = ['stoichiometry', 'electronegativity', 'density', 'bulk modulus', 'ionic character'] else: self.selected_features = selected_features print(('Getting information for ' + id_mo)) if ('mp' not in id_mo): id_mo = self._find_id(id_mo) with MPRester(self.user_api_key) as m: data_mo = m.get_data(id_mo)[0] with MPRester(self.user_api_key) as m: try: e_adjus = m.get_entries(id_mo)[0].__dict__['energy_adjustments'] e_mo_corr = 0 for e_ad in e_adjus: e_mo_corr += e_ad.value except: e_adjus = m.get_entries(id_mo)[0].__dict__['correction'] e_mo_corr = e_adjus if (mo_energy_correction is False): e_mo_corr = 0.0 data_o2 = m.get_data(id_oxygen)[0] e_o2 = ((2 * data_o2['energy']) / data_o2['unit_cell_formula']['O']) n_elements = data_mo['nelements'] binary_oxide = False if (n_elements == 3): binary_oxide = True msg = 'Only unary and binary oxides are implemented.' assert (n_elements <= 3), NotImplementedError(msg) elements = data_mo['elements'] element_no_ox = np.array(elements)[(~ np.isin(elements, 'O'))] if (binary_oxide is True): (element_m1, element_m2) = (element_no_ox[0], element_no_ox[1]) else: (element_m1, element_m2) = (element_no_ox[0], element_no_ox[0]) if ('mp' not in id_m1): id_m1 = self._find_id(element_m1) if ('mp' not in id_m2): id_m2 = self._find_id(element_m2) data_m1 = m.get_data(id_m1)[0] data_m2 = m.get_data(id_m2)[0] formula_mo = data_mo['pretty_formula'] formula_m1 = data_m1['pretty_formula'] formula_m2 = data_m2['pretty_formula'] self.label = label if (self.label is None): self.label = ((formula_mo + '_') + id_mo) self.fp.update({self.label: {}}) self.fp[self.label]['target_features'] = {} self.fp[self.label]['features'] = {} atoms = [] for i in ['m1', 'm2', 'mo']: f_atoms = open('tmp_Atoms.cif', 'w') f_atoms.write(eval(('data_' + i))['cif']) f_atoms.close() atoms.append(read('tmp_Atoms.cif')) os.remove('tmp_Atoms.cif') (atoms_m1, atoms_m2, atoms_mo) = atoms (n_m1, fu_m1) = (2 * (len(atoms_m1),)) (n_m2, fu_m2) = (2 * (len(atoms_m2),)) fu_mo = self._get_atoms_per_unit_formula(atoms_mo) n_m1_in_mo = self._get_number_of_atoms_element(atoms_mo, symbol=element_m1) n_m1_in_mo /= fu_mo n_m2_in_mo = self._get_number_of_atoms_element(atoms_mo, symbol=element_m2) n_m2_in_mo /= fu_mo n_ox_in_mo = self._get_number_of_atoms_element(atoms_mo, symbol='O') n_ox_in_mo /= fu_mo self.fp[self.label]['raw data'] = {} self.fp[self.label]['raw data']['data mo'] = data_mo self.fp[self.label]['raw data']['data m1'] = data_m1 self.fp[self.label]['raw data']['data m2'] = data_m2 (e_m1, e_m2) = (data_m1['energy'], data_m2['energy']) e_mo = data_mo['energy'] (x, y, z) = (n_m1_in_mo, n_m2_in_mo, n_ox_in_mo) a = ((2 / z) * x) b = ((2 / z) * y) c = (2 / z) if (not binary_oxide): a /= 2 b /= 2 dH0 = ((c * (e_mo + e_mo_corr)) / fu_mo) dH0 -= ((a * e_m1) / fu_m1) dH0 -= ((b * e_m2) / fu_m2) dH0 -= e_o2 dH0 *= 96.485 self.add_feature(description='formation energy (kJ/mol)', value=dH0) balanced_reaction = None if (not binary_oxide): balanced_reaction = (((str((2 * a)) + ' ') + formula_m1) + ' + O2') balanced_reaction += ' --> ' balanced_reaction += ((str(c) + ' ') + formula_mo) if binary_oxide: balanced_reaction = (((str(a) + ' ') + formula_m1) + ' + ') balanced_reaction += (((str(b) + ' ') + formula_m2) + ' + O2') balanced_reaction += ' --> ' balanced_reaction += ((str(c) + ' ') + formula_mo) self.fp[self.label]['balanced reaction'] = balanced_reaction if ('stoichiometry' in self.selected_features): ratio_o_m1 = (n_m1_in_mo / n_ox_in_mo) ratio_o_m2 = (n_m2_in_mo / n_ox_in_mo) av_ox_state = ((n_ox_in_mo * 2) / (n_m1_in_mo + n_m2_in_mo)) (element_m1, element_m2) = (atoms_m1[0].symbol, atoms_m2[0].symbol) z_m1 = element(element_m1).atomic_number z_m2 = element(element_m2).atomic_number self.add_feature(description='ratio metal oxygen (mean)', value=np.mean([ratio_o_m1, ratio_o_m2])) self.add_feature(description='ratio metal oxygen (var)', value=np.var([ratio_o_m1, ratio_o_m2])) self.add_feature(description='average oxidation state', value=av_ox_state) self.add_feature(description='atomic number (mean)', value=np.mean([z_m1, z_m2])) self.add_feature(description='atomic number (var)', value=np.var([z_m1, z_m2])) if ('electronegativity' in self.selected_features): elecneg_m1 = element(element_m1).en_pauling elecneg_m2 = element(element_m2).en_pauling self.add_feature(description='pauling electronegativity (mean)', value=np.mean([elecneg_m1, elecneg_m2])) self.add_feature(description='pauling electronegativity (var)', value=np.var([elecneg_m1, elecneg_m2])) if ('ionic character' in self.selected_features): elnegdif_m1 = (element('O').en_pauling - element(element_m1).en_pauling) elnegdif_m2 = (element('O').en_pauling - element(element_m2).en_pauling) pio_m1 = (100 * (1 - np.exp((- (((1 / 2) * elnegdif_m1) ** 2))))) pio_m2 = (100 * (1 - np.exp((- (((1 / 2) * elnegdif_m2) ** 2))))) self.add_feature(description='% ionic character (mean)', value=np.mean([pio_m1, pio_m2])) self.add_feature(description='% ionic character (var)', value=np.var([pio_m1, pio_m2])) if ('volume' in self.selected_features): V_m1 = atoms_m1.get_volume() V_per_fu_m1 = (V_m1 / fu_m1) V_m2 = atoms_m2.get_volume() V_per_fu_m2 = (V_m2 / fu_m2) V_mo = atoms_mo.get_volume() V_per_fu_mo = (V_mo / fu_mo) self.add_feature(description='volume per formula unit (mean)', value=np.mean([V_per_fu_m1, V_per_fu_m2])) self.add_feature(description='volume per formula unit (var)', value=np.var([V_per_fu_m1, V_per_fu_m2])) self.add_feature(description='volume MO per formula unit', value=V_per_fu_mo) diff_V_per_fu_m1_mo = (V_per_fu_mo - V_per_fu_m1) diff_V_per_fu_m2_mo = (V_per_fu_mo - V_per_fu_m2) self.add_feature(description='difference volume (MO-M) (mean)', value=np.mean([diff_V_per_fu_m1_mo, diff_V_per_fu_m2_mo])) self.add_feature(description='difference volume (MO-M) (var)', value=np.var([diff_V_per_fu_m1_mo, diff_V_per_fu_m2_mo])) if ('mass' in self.selected_features): mass_m1 = np.average(atoms_m1.get_masses()) mass_m2 = np.average(atoms_m2.get_masses()) mass_mo = np.average(atoms_mo.get_masses()) mass_per_fu_m1 = (mass_m1 / fu_m1) mass_per_fu_m2 = (mass_m2 / fu_m2) mass_per_fu_mo = (mass_mo / fu_mo) self.add_feature(description='mass per formula unit (mean)', value=np.mean([mass_per_fu_m1, mass_per_fu_m2])) self.add_feature(description='mass per formula unit (var)', value=np.var([mass_per_fu_m1, mass_per_fu_m2])) self.add_feature(description='mass MO per formula unit', value=mass_per_fu_mo) diff_mass_per_fu_m1_mo = (mass_per_fu_mo - mass_per_fu_m1) diff_mass_per_fu_m2_mo = (mass_per_fu_mo - mass_per_fu_m2) self.add_feature(description='difference mass (MO-M) (mean)', value=np.mean([diff_mass_per_fu_m1_mo, diff_mass_per_fu_m2_mo])) self.add_feature(description='difference mass (MO-M) (var)', value=np.var([diff_mass_per_fu_m1_mo, diff_mass_per_fu_m2_mo])) if ('density' in self.selected_features): dens_m1 = data_m1['density'] dens_m2 = data_m2['density'] dens_mo = data_mo['density'] self.add_feature(description='density (mean)', value=np.mean([dens_m1, dens_m2])) self.add_feature(description='density (var)', value=np.var([dens_m1, dens_m2])) self.add_feature(description='density MO', value=dens_mo) diff_dens_m1_mo = (dens_mo - dens_m1) diff_dens_m2_mo = (dens_mo - dens_m2) self.add_feature(description='difference density (MO-M) (mean)', value=np.mean([diff_dens_m1_mo, diff_dens_m2_mo])) self.add_feature(description='difference density (MO-M) (var)', value=np.var([diff_dens_m1_mo, diff_dens_m2_mo])) if ('bulk modulus' in self.selected_features): elas_m1 = data_m1['elasticity'] elas_m2 = data_m2['elasticity'] elas_mo = data_mo['elasticity'] (Kv_m1, Kv_m2) = Kv_mo = (elas_m1['K_Voigt'], elas_m2['K_Voigt']) if elas_mo: Kv_mo = elas_mo['K_Voigt'] else: with MPRester(self.user_api_key) as m: Kv_mo = m.get_data(id_mo, prop='elastic_moduli', data_type='pred')[0]['elastic_moduli']['K'] self.add_feature(description='bulk modulus (mean)', value=np.mean([Kv_m1, Kv_m2])) self.add_feature(description='bulk modulus (var)', value=np.var([Kv_m1, Kv_m2])) self.add_feature(description='bulk modulus MO', value=Kv_mo) diff_Kv_m1_mo = (Kv_mo - Kv_m1) diff_Kv_m2_mo = (Kv_mo - Kv_m2) self.add_feature(description='difference bulk modulus (MO-M) (mean)', value=np.mean([diff_Kv_m1_mo, diff_Kv_m2_mo])) self.add_feature(description='difference bulk modulus (MO-M) (var)', value=np.var([diff_Kv_m1_mo, diff_Kv_m2_mo])) if ('shear modulus' in self.selected_features): elas_m1 = data_m1['elasticity'] elas_m2 = data_m2['elasticity'] elas_mo = data_mo['elasticity'] (Gv_m1, Gv_m2) = (elas_m1['G_Voigt'], elas_m2['G_Voigt']) if elas_mo: Gv_mo = elas_mo['G_Voigt'] else: with MPRester(self.user_api_key) as m: Gv_mo = m.get_data(id_mo, prop='elastic_moduli', data_type='pred')[0]['elastic_moduli']['G'] self.add_feature(description='shear modulus (mean)', value=np.mean([Gv_m1, Gv_m2])) self.add_feature(description='shear modulus (var)', value=np.var([Gv_m1, Gv_m2])) self.add_feature(description='shear modulus MO', value=Gv_mo) diff_Gv_m1_mo = (Gv_mo - Gv_m1) diff_Gv_m2_mo = (Gv_mo - Gv_m2) self.add_feature(description='difference shear modulus (MO-M) (mean)', value=np.mean([diff_Gv_m1_mo, diff_Gv_m2_mo])) self.add_feature(description='difference shear modulus (MO-M) (var)', value=np.var([diff_Gv_m1_mo, diff_Gv_m2_mo])) if ('poisson ratio' in self.selected_features): elas_m1 = data_m1['elasticity'] elas_m2 = data_m2['elasticity'] elas_mo = data_mo['elasticity'] (pois_m1, pois_m2, pois_mo) = (elas_m1['poisson_ratio'], elas_m2['poisson_ratio'], elas_mo['poisson_ratio']) self.add_feature(description='poisson ratio (mean)', value=np.mean([pois_m1, pois_m2])) self.add_feature(description='poisson ratio (var)', value=np.var([pois_m1, pois_m2])) self.add_feature(description='poisson ratio MO', value=pois_mo) diff_pois_m1_mo = (pois_mo - pois_m1) diff_pois_m2_mo = (pois_mo - pois_m2) self.add_feature(description='difference poisson ratio (MO-M) (mean)', value=np.mean([diff_pois_m1_mo, diff_pois_m2_mo])) self.add_feature(description='difference poisson ratio (MO-M) (var)', value=np.var([diff_pois_m1_mo, diff_pois_m2_mo])) if ('anisotropy' in self.selected_features): elas_m1 = data_m1['elasticity'] elas_m2 = data_m2['elasticity'] elas_mo = data_mo['elasticity'] (u_ani_m1, u_ani_m2, u_ani_mo) = (elas_m1['universal_anisotropy'], elas_m2['universal_anisotropy'], elas_mo['universal_anisotropy']) (el_ani_m1, el_ani_m2, el_ani_mo) = (elas_m1['elastic_anisotropy'], elas_m2['elastic_anisotropy'], elas_mo['elastic_anisotropy']) self.add_feature(description='universal anisotropy (mean)', value=np.mean([u_ani_m1, u_ani_m2])) self.add_feature(description='universal anisotropy (var)', value=np.var([u_ani_m1, u_ani_m2])) self.add_feature(description='universal anisotropy MO', value=u_ani_mo) diff_u_ani_m1_mo = (u_ani_mo - u_ani_m1) diff_u_ani_m2_mo = (u_ani_mo - u_ani_m2) self.add_feature(description='difference universal anisotropy (MO-M) (mean)', value=np.mean([diff_u_ani_m1_mo, diff_u_ani_m2_mo])) self.add_feature(description='difference universal anisotropy (MO-M) (var)', value=np.var([diff_u_ani_m1_mo, diff_u_ani_m2_mo])) self.add_feature(description='elastic anisotropy (mean)', value=np.mean([el_ani_m1, el_ani_m2])) self.add_feature(description='elastic anisotropy (var)', value=np.var([el_ani_m1, el_ani_m2])) self.add_feature(description='elastic anisotropy MO', value=el_ani_mo) diff_el_ani_m1_mo = (el_ani_mo - el_ani_m1) diff_el_ani_m2_mo = (el_ani_mo - el_ani_m2) self.add_feature(description='difference elastic anisotropy (MO-M) (mean)', value=np.mean([diff_el_ani_m1_mo, diff_el_ani_m2_mo])) self.add_feature(description='difference elastic anisotropy (MO-M) (var)', value=np.var([diff_el_ani_m1_mo, diff_el_ani_m2_mo])) if ('spacegroup' in self.selected_features): spacegroup_m1 = data_m1['spacegroup']['number'] spacegroup_m2 = data_m2['spacegroup']['number'] spacegroup_mo = data_mo['spacegroup']['number'] self.add_feature(description='Spacegroup M1', value=spacegroup_m1) self.add_feature(description='Spacegroup M2', value=spacegroup_m2) self.add_feature(description='Spacegroup MO', value=spacegroup_mo) print((('Fingerprint for ' + self.label) + ' completed.'))<|docstring|>Generates a feature set for an oxidation for a given metal oxide (AxByOz) from the elements (A and B). Parameters ---------- id_mo: str Materials Project mp-id for the metal oxide or chemical formula of the metal oxide, e.g. 'Al2SiO5' or 'mp-4753'. id_m1: str (optional) Materials Project mp-id for the metal A, e.g. 'mp-134'. id_m2: str (optional) Materials Project mp-id for the metal B, e.g. 'mp-149'. id_oxygen: str Materials project mp-id for oxygen in the gas phase. selected_features: list or str (option 1): list List of selected features to be considered to generate the fingerprint. Implemented are: 'stoichiometry', 'electronegativity', 'mass', 'volume', 'density', 'bulk modulus', 'shear modulus', 'poisson ratio', 'anisotropy', 'spacegroup' and 'ionic character'. (option 2): str 'all': Include all implemented features (see option 1). 'ellingham': Recommended features for building models for predicting Ellingham diagrams. Includes only the following features: 'stoichiometry', 'electronegativity', 'density', 'bulk modulus', 'ionic character'. 'label': str Defines the label tag for the fingerprint. The user can chose a name for the fingerprint for the data entry, e.g. 'Al2SiO5-PBEU'. 'mo_energy_correction': bool If True the algorithm only selects Material Project entries which in which energy corrections are available. See: https://materialsproject.org/docs/calculations#Total_Energy_Adjustments<|endoftext|>
0c43707edb9ed6db0e2d54842aa1bc55053e9369b602a335f87721bf53abf3e8
def _find_id(self, compound): " Find Materials Project ID for a given compound.\n\n Parameters\n ----------\n compound: str\n Compound formula. Examples: ``'Li2O'``,\n ``'AlLiO2'``, ``'Mg2SiO4'``.\n user_api: str\n Materials Project users API.\n\n Returns\n -------\n id_compound: str\n Materials Project compound ID.\n\n " with MPRester(self.user_api_key) as m: info_MOs = m.get_entries(compound, inc_structure='final', property_data=['elasticity', 'e_above_hull', 'Correction'], sort_by_e_above_hull=True) for i in range(len(info_MOs)): id_compound = info_MOs[i].__dict__['entry_id'] elasticity = m.get_data(id_compound)[0]['elasticity'] if elasticity: break if (not elasticity): id_compound = info_MOs[0].__dict__['entry_id'] return id_compound
Find Materials Project ID for a given compound. Parameters ---------- compound: str Compound formula. Examples: ``'Li2O'``, ``'AlLiO2'``, ``'Mg2SiO4'``. user_api: str Materials Project users API. Returns ------- id_compound: str Materials Project compound ID.
gibbsml/ellingham/fingerprint.py
_find_id
atomisticnet/gibbsml
5
python
def _find_id(self, compound): " Find Materials Project ID for a given compound.\n\n Parameters\n ----------\n compound: str\n Compound formula. Examples: ``'Li2O'``,\n ``'AlLiO2'``, ``'Mg2SiO4'``.\n user_api: str\n Materials Project users API.\n\n Returns\n -------\n id_compound: str\n Materials Project compound ID.\n\n " with MPRester(self.user_api_key) as m: info_MOs = m.get_entries(compound, inc_structure='final', property_data=['elasticity', 'e_above_hull', 'Correction'], sort_by_e_above_hull=True) for i in range(len(info_MOs)): id_compound = info_MOs[i].__dict__['entry_id'] elasticity = m.get_data(id_compound)[0]['elasticity'] if elasticity: break if (not elasticity): id_compound = info_MOs[0].__dict__['entry_id'] return id_compound
def _find_id(self, compound): " Find Materials Project ID for a given compound.\n\n Parameters\n ----------\n compound: str\n Compound formula. Examples: ``'Li2O'``,\n ``'AlLiO2'``, ``'Mg2SiO4'``.\n user_api: str\n Materials Project users API.\n\n Returns\n -------\n id_compound: str\n Materials Project compound ID.\n\n " with MPRester(self.user_api_key) as m: info_MOs = m.get_entries(compound, inc_structure='final', property_data=['elasticity', 'e_above_hull', 'Correction'], sort_by_e_above_hull=True) for i in range(len(info_MOs)): id_compound = info_MOs[i].__dict__['entry_id'] elasticity = m.get_data(id_compound)[0]['elasticity'] if elasticity: break if (not elasticity): id_compound = info_MOs[0].__dict__['entry_id'] return id_compound<|docstring|>Find Materials Project ID for a given compound. Parameters ---------- compound: str Compound formula. Examples: ``'Li2O'``, ``'AlLiO2'``, ``'Mg2SiO4'``. user_api: str Materials Project users API. Returns ------- id_compound: str Materials Project compound ID.<|endoftext|>
a4aac19791ee77889bb9cf2923e2f607c6613f558c2ccbb1878e15b9669d7eaa
def add_feature(self, description, value): "\n Parameters\n ----------\n description: str\n Description of the property to append (e.g. 'Formation energy').\n value: float\n Numerical value for a given property.\n\n Returns\n -------\n Adds a feature to the fingerprint (stored in self.fp).\n " self.fp[self.label]['features'].update({description: value})
Parameters ---------- description: str Description of the property to append (e.g. 'Formation energy'). value: float Numerical value for a given property. Returns ------- Adds a feature to the fingerprint (stored in self.fp).
gibbsml/ellingham/fingerprint.py
add_feature
atomisticnet/gibbsml
5
python
def add_feature(self, description, value): "\n Parameters\n ----------\n description: str\n Description of the property to append (e.g. 'Formation energy').\n value: float\n Numerical value for a given property.\n\n Returns\n -------\n Adds a feature to the fingerprint (stored in self.fp).\n " self.fp[self.label]['features'].update({description: value})
def add_feature(self, description, value): "\n Parameters\n ----------\n description: str\n Description of the property to append (e.g. 'Formation energy').\n value: float\n Numerical value for a given property.\n\n Returns\n -------\n Adds a feature to the fingerprint (stored in self.fp).\n " self.fp[self.label]['features'].update({description: value})<|docstring|>Parameters ---------- description: str Description of the property to append (e.g. 'Formation energy'). value: float Numerical value for a given property. Returns ------- Adds a feature to the fingerprint (stored in self.fp).<|endoftext|>
d0094bc0237b9f980ffee3ffdb6ba8ac96a98bf8d905f0f9bf910b6ac5535d7e
def add_target_feature(self, description, value): "\n Parameters\n ----------\n description: str\n Description of the property to be appended (e.g. 'Reduction\n temperature').\n value: float\n Numerical value for a given property.\n\n Returns\n -------\n Adds a target feature to the fingerprint (stored in self.fp).\n Note: In this case the properties and values will be only used for\n training the model (commonly know as train_y).\n " self.fp[self.label]['target_features'].update({description: value})
Parameters ---------- description: str Description of the property to be appended (e.g. 'Reduction temperature'). value: float Numerical value for a given property. Returns ------- Adds a target feature to the fingerprint (stored in self.fp). Note: In this case the properties and values will be only used for training the model (commonly know as train_y).
gibbsml/ellingham/fingerprint.py
add_target_feature
atomisticnet/gibbsml
5
python
def add_target_feature(self, description, value): "\n Parameters\n ----------\n description: str\n Description of the property to be appended (e.g. 'Reduction\n temperature').\n value: float\n Numerical value for a given property.\n\n Returns\n -------\n Adds a target feature to the fingerprint (stored in self.fp).\n Note: In this case the properties and values will be only used for\n training the model (commonly know as train_y).\n " self.fp[self.label]['target_features'].update({description: value})
def add_target_feature(self, description, value): "\n Parameters\n ----------\n description: str\n Description of the property to be appended (e.g. 'Reduction\n temperature').\n value: float\n Numerical value for a given property.\n\n Returns\n -------\n Adds a target feature to the fingerprint (stored in self.fp).\n Note: In this case the properties and values will be only used for\n training the model (commonly know as train_y).\n " self.fp[self.label]['target_features'].update({description: value})<|docstring|>Parameters ---------- description: str Description of the property to be appended (e.g. 'Reduction temperature'). value: float Numerical value for a given property. Returns ------- Adds a target feature to the fingerprint (stored in self.fp). Note: In this case the properties and values will be only used for training the model (commonly know as train_y).<|endoftext|>
b997254d5a347f2ccb3084da598d166d62109b7889b34dacac5986cd0b899524
def get_labels(self): '\n Returns the list of species (labelled), e.g. CaO-mp-2605.\n ' return list(self.fp.keys())
Returns the list of species (labelled), e.g. CaO-mp-2605.
gibbsml/ellingham/fingerprint.py
get_labels
atomisticnet/gibbsml
5
python
def get_labels(self): '\n \n ' return list(self.fp.keys())
def get_labels(self): '\n \n ' return list(self.fp.keys())<|docstring|>Returns the list of species (labelled), e.g. CaO-mp-2605.<|endoftext|>
02d34ec3eb459c98930034bfb42e40d21aab6d56ac974a9fcf6dfe7efa88ba65
def get_features_names(self): '\n Returns a list containing the names of the features, e.g. formation\n energy (kJ/mol).\n ' species = list(self.fp.keys()) features_names = list(self.fp[species[0]]['features'].keys()) return features_names
Returns a list containing the names of the features, e.g. formation energy (kJ/mol).
gibbsml/ellingham/fingerprint.py
get_features_names
atomisticnet/gibbsml
5
python
def get_features_names(self): '\n Returns a list containing the names of the features, e.g. formation\n energy (kJ/mol).\n ' species = list(self.fp.keys()) features_names = list(self.fp[species[0]]['features'].keys()) return features_names
def get_features_names(self): '\n Returns a list containing the names of the features, e.g. formation\n energy (kJ/mol).\n ' species = list(self.fp.keys()) features_names = list(self.fp[species[0]]['features'].keys()) return features_names<|docstring|>Returns a list containing the names of the features, e.g. formation energy (kJ/mol).<|endoftext|>
0b8d7829f90c22d800cae598dddab71ea44eeac41a39d0e4b5723305accb7ba3
def get_target_features_names(self): '\n Returns the list of target features. These features are\n user-defined and must be included with the add_target_features\n function.\n ' species = list(self.fp.keys()) features_names = list(self.fp[species[0]]['target_features'].keys()) return features_names
Returns the list of target features. These features are user-defined and must be included with the add_target_features function.
gibbsml/ellingham/fingerprint.py
get_target_features_names
atomisticnet/gibbsml
5
python
def get_target_features_names(self): '\n Returns the list of target features. These features are\n user-defined and must be included with the add_target_features\n function.\n ' species = list(self.fp.keys()) features_names = list(self.fp[species[0]]['target_features'].keys()) return features_names
def get_target_features_names(self): '\n Returns the list of target features. These features are\n user-defined and must be included with the add_target_features\n function.\n ' species = list(self.fp.keys()) features_names = list(self.fp[species[0]]['target_features'].keys()) return features_names<|docstring|>Returns the list of target features. These features are user-defined and must be included with the add_target_features function.<|endoftext|>
063353fdbf2a2630abffc31bdf9a3e3f45d80df6db0bc9a14deb3c1c20925c8e
def dump_set(self, filename='fingerprint.json'): '\n Parameters\n ----------\n filename: str\n Name of the file to save the generated Fingerprint class.\n\n Returns\n -------\n Saves the whole Fingerprint class into a json file.\n ' self.label = 0.0 fp_dict = self.__dict__ del fp_dict['user_api_key'] with open(filename, 'w') as fp: json.dump(fp_dict, fp)
Parameters ---------- filename: str Name of the file to save the generated Fingerprint class. Returns ------- Saves the whole Fingerprint class into a json file.
gibbsml/ellingham/fingerprint.py
dump_set
atomisticnet/gibbsml
5
python
def dump_set(self, filename='fingerprint.json'): '\n Parameters\n ----------\n filename: str\n Name of the file to save the generated Fingerprint class.\n\n Returns\n -------\n Saves the whole Fingerprint class into a json file.\n ' self.label = 0.0 fp_dict = self.__dict__ del fp_dict['user_api_key'] with open(filename, 'w') as fp: json.dump(fp_dict, fp)
def dump_set(self, filename='fingerprint.json'): '\n Parameters\n ----------\n filename: str\n Name of the file to save the generated Fingerprint class.\n\n Returns\n -------\n Saves the whole Fingerprint class into a json file.\n ' self.label = 0.0 fp_dict = self.__dict__ del fp_dict['user_api_key'] with open(filename, 'w') as fp: json.dump(fp_dict, fp)<|docstring|>Parameters ---------- filename: str Name of the file to save the generated Fingerprint class. Returns ------- Saves the whole Fingerprint class into a json file.<|endoftext|>
4569602b19d261b5d7cd97766c7cb47149ca3dc6952e02177d3d4a202345f2ae
def load_set(self, filename): '\n Parameters\n ----------\n filename: str\n Name of the file to load (json format).\n\n Returns\n -------\n Load a json file containing a previously saved Fingerprint (see\n dump_set function).\n ' with open(filename, 'r') as fp: self.__dict__ = json.load(fp)
Parameters ---------- filename: str Name of the file to load (json format). Returns ------- Load a json file containing a previously saved Fingerprint (see dump_set function).
gibbsml/ellingham/fingerprint.py
load_set
atomisticnet/gibbsml
5
python
def load_set(self, filename): '\n Parameters\n ----------\n filename: str\n Name of the file to load (json format).\n\n Returns\n -------\n Load a json file containing a previously saved Fingerprint (see\n dump_set function).\n ' with open(filename, 'r') as fp: self.__dict__ = json.load(fp)
def load_set(self, filename): '\n Parameters\n ----------\n filename: str\n Name of the file to load (json format).\n\n Returns\n -------\n Load a json file containing a previously saved Fingerprint (see\n dump_set function).\n ' with open(filename, 'r') as fp: self.__dict__ = json.load(fp)<|docstring|>Parameters ---------- filename: str Name of the file to load (json format). Returns ------- Load a json file containing a previously saved Fingerprint (see dump_set function).<|endoftext|>
48ce9cdb82e2936e9c4ac660159436f8cab213a00375afce248dcbeba95b67b4
def initialize(self): ' An overridden initializer method.\n\n This method adds the window to the static set of Windows.\n\n ' super(Window, self).initialize() Window.windows.add(self)
An overridden initializer method. This method adds the window to the static set of Windows.
enaml/widgets/window.py
initialize
AndiEcker/enaml
1,080
python
def initialize(self): ' An overridden initializer method.\n\n This method adds the window to the static set of Windows.\n\n ' super(Window, self).initialize() Window.windows.add(self)
def initialize(self): ' An overridden initializer method.\n\n This method adds the window to the static set of Windows.\n\n ' super(Window, self).initialize() Window.windows.add(self)<|docstring|>An overridden initializer method. This method adds the window to the static set of Windows.<|endoftext|>
9003acd451fae75ceb6043314be43e2d382c06c5f26196a07d644631dc38854c
def destroy(self): ' An overridden destructor method.\n\n This method removes the window from the static set of Windows.\n\n ' super(Window, self).destroy() Window.windows.discard(self)
An overridden destructor method. This method removes the window from the static set of Windows.
enaml/widgets/window.py
destroy
AndiEcker/enaml
1,080
python
def destroy(self): ' An overridden destructor method.\n\n This method removes the window from the static set of Windows.\n\n ' super(Window, self).destroy() Window.windows.discard(self)
def destroy(self): ' An overridden destructor method.\n\n This method removes the window from the static set of Windows.\n\n ' super(Window, self).destroy() Window.windows.discard(self)<|docstring|>An overridden destructor method. This method removes the window from the static set of Windows.<|endoftext|>
aa21c0ab7c94839b6e2f8a141487cb3939ddf9f5d2a75bde61c319fd21b1e987
def central_widget(self): ' Get the central widget defined on the window.\n\n The last `Container` child of the window is the central widget.\n\n ' for child in reversed(self.children): if isinstance(child, Container): return child
Get the central widget defined on the window. The last `Container` child of the window is the central widget.
enaml/widgets/window.py
central_widget
AndiEcker/enaml
1,080
python
def central_widget(self): ' Get the central widget defined on the window.\n\n The last `Container` child of the window is the central widget.\n\n ' for child in reversed(self.children): if isinstance(child, Container): return child
def central_widget(self): ' Get the central widget defined on the window.\n\n The last `Container` child of the window is the central widget.\n\n ' for child in reversed(self.children): if isinstance(child, Container): return child<|docstring|>Get the central widget defined on the window. The last `Container` child of the window is the central widget.<|endoftext|>
c4976f7da412e8585c9d08ad489680cb94047c2383649f0c1546e0cf09757ef2
def position(self): ' Get the position of the window frame.\n\n Returns\n -------\n result : Pos\n The current position of the window frame.\n\n ' if self.proxy_is_active: return self.proxy.position() return Pos((- 1), (- 1))
Get the position of the window frame. Returns ------- result : Pos The current position of the window frame.
enaml/widgets/window.py
position
AndiEcker/enaml
1,080
python
def position(self): ' Get the position of the window frame.\n\n Returns\n -------\n result : Pos\n The current position of the window frame.\n\n ' if self.proxy_is_active: return self.proxy.position() return Pos((- 1), (- 1))
def position(self): ' Get the position of the window frame.\n\n Returns\n -------\n result : Pos\n The current position of the window frame.\n\n ' if self.proxy_is_active: return self.proxy.position() return Pos((- 1), (- 1))<|docstring|>Get the position of the window frame. Returns ------- result : Pos The current position of the window frame.<|endoftext|>
1cb03f615a5b04c7133f7b9425c27b91b2381a16e4d93ea61b8e61622d74714f
def set_position(self, pos): ' Set the position of the window frame.\n\n Parameters\n ----------\n pos : Pos\n The desired position of the window the window frame.\n\n ' if self.proxy_is_active: self.proxy.set_position(pos)
Set the position of the window frame. Parameters ---------- pos : Pos The desired position of the window the window frame.
enaml/widgets/window.py
set_position
AndiEcker/enaml
1,080
python
def set_position(self, pos): ' Set the position of the window frame.\n\n Parameters\n ----------\n pos : Pos\n The desired position of the window the window frame.\n\n ' if self.proxy_is_active: self.proxy.set_position(pos)
def set_position(self, pos): ' Set the position of the window frame.\n\n Parameters\n ----------\n pos : Pos\n The desired position of the window the window frame.\n\n ' if self.proxy_is_active: self.proxy.set_position(pos)<|docstring|>Set the position of the window frame. Parameters ---------- pos : Pos The desired position of the window the window frame.<|endoftext|>
d79339f1b08a9bad66c88eace19cbb7640b68c405d074d619968012aa298c83f
def size(self): ' Get the size of the window client area.\n\n Returns\n -------\n result : Size\n The current size of the window client area.\n\n ' if self.proxy_is_active: return self.proxy.size() return Size((- 1), (- 1))
Get the size of the window client area. Returns ------- result : Size The current size of the window client area.
enaml/widgets/window.py
size
AndiEcker/enaml
1,080
python
def size(self): ' Get the size of the window client area.\n\n Returns\n -------\n result : Size\n The current size of the window client area.\n\n ' if self.proxy_is_active: return self.proxy.size() return Size((- 1), (- 1))
def size(self): ' Get the size of the window client area.\n\n Returns\n -------\n result : Size\n The current size of the window client area.\n\n ' if self.proxy_is_active: return self.proxy.size() return Size((- 1), (- 1))<|docstring|>Get the size of the window client area. Returns ------- result : Size The current size of the window client area.<|endoftext|>
76f0b4b9c77d5fd6eaa0a197ab03f79972086eace7dbc46df2d5b8ea2f8752e9
def set_size(self, size): ' Set the size of the window client area.\n\n Parameters\n ----------\n size : Size\n The desired size of the window client area.\n\n ' if self.proxy_is_active: self.proxy.set_size(size)
Set the size of the window client area. Parameters ---------- size : Size The desired size of the window client area.
enaml/widgets/window.py
set_size
AndiEcker/enaml
1,080
python
def set_size(self, size): ' Set the size of the window client area.\n\n Parameters\n ----------\n size : Size\n The desired size of the window client area.\n\n ' if self.proxy_is_active: self.proxy.set_size(size)
def set_size(self, size): ' Set the size of the window client area.\n\n Parameters\n ----------\n size : Size\n The desired size of the window client area.\n\n ' if self.proxy_is_active: self.proxy.set_size(size)<|docstring|>Set the size of the window client area. Parameters ---------- size : Size The desired size of the window client area.<|endoftext|>
cf096b4dcbf84bcb60fabf9ee9aad1d233291dd7574dbf858b8c06c8e25a86aa
def geometry(self): ' Get the geometry of the window client area.\n\n Returns\n -------\n result : Rect\n The current geometry of the window client area.\n\n ' if self.proxy_is_active: return self.proxy.geometry() return Rect((- 1), (- 1), (- 1), (- 1))
Get the geometry of the window client area. Returns ------- result : Rect The current geometry of the window client area.
enaml/widgets/window.py
geometry
AndiEcker/enaml
1,080
python
def geometry(self): ' Get the geometry of the window client area.\n\n Returns\n -------\n result : Rect\n The current geometry of the window client area.\n\n ' if self.proxy_is_active: return self.proxy.geometry() return Rect((- 1), (- 1), (- 1), (- 1))
def geometry(self): ' Get the geometry of the window client area.\n\n Returns\n -------\n result : Rect\n The current geometry of the window client area.\n\n ' if self.proxy_is_active: return self.proxy.geometry() return Rect((- 1), (- 1), (- 1), (- 1))<|docstring|>Get the geometry of the window client area. Returns ------- result : Rect The current geometry of the window client area.<|endoftext|>
ed1180bf23c9ea3eca315a050de183aaed0a04e4733faf969ea8722ea7d94367
def set_geometry(self, rect): ' Set the geometry of the window client area.\n\n Parameters\n ----------\n rect : Rect\n The desired geometry of the window client area.\n\n ' if self.proxy_is_active: self.proxy.set_geometry(rect)
Set the geometry of the window client area. Parameters ---------- rect : Rect The desired geometry of the window client area.
enaml/widgets/window.py
set_geometry
AndiEcker/enaml
1,080
python
def set_geometry(self, rect): ' Set the geometry of the window client area.\n\n Parameters\n ----------\n rect : Rect\n The desired geometry of the window client area.\n\n ' if self.proxy_is_active: self.proxy.set_geometry(rect)
def set_geometry(self, rect): ' Set the geometry of the window client area.\n\n Parameters\n ----------\n rect : Rect\n The desired geometry of the window client area.\n\n ' if self.proxy_is_active: self.proxy.set_geometry(rect)<|docstring|>Set the geometry of the window client area. Parameters ---------- rect : Rect The desired geometry of the window client area.<|endoftext|>
97b1985c8a5a7f3e9c549d5f636096ee92965d25a1d120b083b5764262d8e996
def frame_geometry(self): ' Get the geometry of the window frame.\n\n Returns\n -------\n result : Rect\n The current geometry of the window frame.\n\n ' if self.proxy_is_active: return self.proxy.frame_geometry() return Rect((- 1), (- 1), (- 1), (- 1))
Get the geometry of the window frame. Returns ------- result : Rect The current geometry of the window frame.
enaml/widgets/window.py
frame_geometry
AndiEcker/enaml
1,080
python
def frame_geometry(self): ' Get the geometry of the window frame.\n\n Returns\n -------\n result : Rect\n The current geometry of the window frame.\n\n ' if self.proxy_is_active: return self.proxy.frame_geometry() return Rect((- 1), (- 1), (- 1), (- 1))
def frame_geometry(self): ' Get the geometry of the window frame.\n\n Returns\n -------\n result : Rect\n The current geometry of the window frame.\n\n ' if self.proxy_is_active: return self.proxy.frame_geometry() return Rect((- 1), (- 1), (- 1), (- 1))<|docstring|>Get the geometry of the window frame. Returns ------- result : Rect The current geometry of the window frame.<|endoftext|>
636d55ec74b6ba1eefeb1dcc5191725c79a566a6e3eefc8f2d16ba8af9bc00e3
def maximize(self): ' Maximize the window.\n\n ' if self.proxy_is_active: self.proxy.maximize()
Maximize the window.
enaml/widgets/window.py
maximize
AndiEcker/enaml
1,080
python
def maximize(self): ' \n\n ' if self.proxy_is_active: self.proxy.maximize()
def maximize(self): ' \n\n ' if self.proxy_is_active: self.proxy.maximize()<|docstring|>Maximize the window.<|endoftext|>
032ee8aa2c7c3f5f415d148da6fd2e15f28bce8ea43f31af8ea5967ab7ab5b79
def is_maximized(self): ' Get whether the window is maximized.\n\n ' if self.proxy_is_active: return self.proxy.is_maximized() return False
Get whether the window is maximized.
enaml/widgets/window.py
is_maximized
AndiEcker/enaml
1,080
python
def is_maximized(self): ' \n\n ' if self.proxy_is_active: return self.proxy.is_maximized() return False
def is_maximized(self): ' \n\n ' if self.proxy_is_active: return self.proxy.is_maximized() return False<|docstring|>Get whether the window is maximized.<|endoftext|>
c18e251ac188c1e879642b18b911afbdbdcb98bb8551ac53c160fa0af044b522
def minimize(self): ' Minimize the window.\n\n ' if self.proxy_is_active: self.proxy.minimize()
Minimize the window.
enaml/widgets/window.py
minimize
AndiEcker/enaml
1,080
python
def minimize(self): ' \n\n ' if self.proxy_is_active: self.proxy.minimize()
def minimize(self): ' \n\n ' if self.proxy_is_active: self.proxy.minimize()<|docstring|>Minimize the window.<|endoftext|>
3d3b2fa392510dc8bdf164c3cb529a1de9d7dbe97376dc784ede10ee1aca4947
def is_minimized(self): ' Get whether the window is minimized.\n\n ' if self.proxy_is_active: return self.proxy.is_minimized() return False
Get whether the window is minimized.
enaml/widgets/window.py
is_minimized
AndiEcker/enaml
1,080
python
def is_minimized(self): ' \n\n ' if self.proxy_is_active: return self.proxy.is_minimized() return False
def is_minimized(self): ' \n\n ' if self.proxy_is_active: return self.proxy.is_minimized() return False<|docstring|>Get whether the window is minimized.<|endoftext|>
3b77c392f328813397ce36ac7b8c88e017e4318d0dce6cbf46f3a1e489bc9e75
def restore(self): ' Restore the window from a maximized or minimized state.\n\n ' if self.proxy_is_active: self.proxy.restore()
Restore the window from a maximized or minimized state.
enaml/widgets/window.py
restore
AndiEcker/enaml
1,080
python
def restore(self): ' \n\n ' if self.proxy_is_active: self.proxy.restore()
def restore(self): ' \n\n ' if self.proxy_is_active: self.proxy.restore()<|docstring|>Restore the window from a maximized or minimized state.<|endoftext|>
77d3c4239a1803a23d6334bc9125f947d75e6d3c1641f0c3d8d2f152c9d9f29e
def send_to_front(self): ' Send the window to the top of the Z-order.\n\n This will only affect the Z-order of the window relative to the\n Z-order of other windows in the same application.\n\n ' if self.proxy_is_active: self.proxy.send_to_front()
Send the window to the top of the Z-order. This will only affect the Z-order of the window relative to the Z-order of other windows in the same application.
enaml/widgets/window.py
send_to_front
AndiEcker/enaml
1,080
python
def send_to_front(self): ' Send the window to the top of the Z-order.\n\n This will only affect the Z-order of the window relative to the\n Z-order of other windows in the same application.\n\n ' if self.proxy_is_active: self.proxy.send_to_front()
def send_to_front(self): ' Send the window to the top of the Z-order.\n\n This will only affect the Z-order of the window relative to the\n Z-order of other windows in the same application.\n\n ' if self.proxy_is_active: self.proxy.send_to_front()<|docstring|>Send the window to the top of the Z-order. This will only affect the Z-order of the window relative to the Z-order of other windows in the same application.<|endoftext|>
e4d3f16e6e4a7fd131063a9d8169e2d887feda309e5395d2664b9bdbda9e1c62
def send_to_back(self): ' Send the window to the bottom of the Z-order.\n\n This will only affect the Z-order of the window relative to the\n Z-order of other windows in the same application.\n\n ' if self.proxy_is_active: self.proxy.send_to_back()
Send the window to the bottom of the Z-order. This will only affect the Z-order of the window relative to the Z-order of other windows in the same application.
enaml/widgets/window.py
send_to_back
AndiEcker/enaml
1,080
python
def send_to_back(self): ' Send the window to the bottom of the Z-order.\n\n This will only affect the Z-order of the window relative to the\n Z-order of other windows in the same application.\n\n ' if self.proxy_is_active: self.proxy.send_to_back()
def send_to_back(self): ' Send the window to the bottom of the Z-order.\n\n This will only affect the Z-order of the window relative to the\n Z-order of other windows in the same application.\n\n ' if self.proxy_is_active: self.proxy.send_to_back()<|docstring|>Send the window to the bottom of the Z-order. This will only affect the Z-order of the window relative to the Z-order of other windows in the same application.<|endoftext|>
484cae1decb96f2be24d74c1770c9bd789e0af83f2a01e20e2dcc552598cc432
def activate_window(self): ' Set this window to be the active application window.\n\n This performs the same operation as clicking the mouse on the\n title bar of the window, except that it will not effect the Z\n order of the window.\n\n On Windows, this will cause the taskbar icon to flash if the\n window does not belong to the active application.\n\n ' if self.proxy_is_active: self.proxy.activate_window()
Set this window to be the active application window. This performs the same operation as clicking the mouse on the title bar of the window, except that it will not effect the Z order of the window. On Windows, this will cause the taskbar icon to flash if the window does not belong to the active application.
enaml/widgets/window.py
activate_window
AndiEcker/enaml
1,080
python
def activate_window(self): ' Set this window to be the active application window.\n\n This performs the same operation as clicking the mouse on the\n title bar of the window, except that it will not effect the Z\n order of the window.\n\n On Windows, this will cause the taskbar icon to flash if the\n window does not belong to the active application.\n\n ' if self.proxy_is_active: self.proxy.activate_window()
def activate_window(self): ' Set this window to be the active application window.\n\n This performs the same operation as clicking the mouse on the\n title bar of the window, except that it will not effect the Z\n order of the window.\n\n On Windows, this will cause the taskbar icon to flash if the\n window does not belong to the active application.\n\n ' if self.proxy_is_active: self.proxy.activate_window()<|docstring|>Set this window to be the active application window. This performs the same operation as clicking the mouse on the title bar of the window, except that it will not effect the Z order of the window. On Windows, this will cause the taskbar icon to flash if the window does not belong to the active application.<|endoftext|>
7385616c81817e37e0c33050cef8ec98f3f9f9fdb0f40e0dab1eb33e122e38ce
def center_on_screen(self): ' Center the window on the screen.\n\n ' if self.proxy_is_active: self.proxy.center_on_screen()
Center the window on the screen.
enaml/widgets/window.py
center_on_screen
AndiEcker/enaml
1,080
python
def center_on_screen(self): ' \n\n ' if self.proxy_is_active: self.proxy.center_on_screen()
def center_on_screen(self): ' \n\n ' if self.proxy_is_active: self.proxy.center_on_screen()<|docstring|>Center the window on the screen.<|endoftext|>
0ed84c58394630eb03952684fd5101dc618bf034c1b5f1476d996244db36f444
def center_on_widget(self, other): ' Center this window on another widget.\n\n Parameters\n ----------\n other : Widget\n The widget onto which to center this window.\n\n ' assert isinstance(other, Widget) if (self.proxy_is_active and other.proxy_is_active): self.proxy.center_on_widget(other)
Center this window on another widget. Parameters ---------- other : Widget The widget onto which to center this window.
enaml/widgets/window.py
center_on_widget
AndiEcker/enaml
1,080
python
def center_on_widget(self, other): ' Center this window on another widget.\n\n Parameters\n ----------\n other : Widget\n The widget onto which to center this window.\n\n ' assert isinstance(other, Widget) if (self.proxy_is_active and other.proxy_is_active): self.proxy.center_on_widget(other)
def center_on_widget(self, other): ' Center this window on another widget.\n\n Parameters\n ----------\n other : Widget\n The widget onto which to center this window.\n\n ' assert isinstance(other, Widget) if (self.proxy_is_active and other.proxy_is_active): self.proxy.center_on_widget(other)<|docstring|>Center this window on another widget. Parameters ---------- other : Widget The widget onto which to center this window.<|endoftext|>
347b908773a2f89bfa3971880f0880ed0abea71409ac9d927e11db3fd49989da
def close(self): " Close the window.\n\n This will cause the window to be hidden, the 'closed' event\n to be fired, and the window subsequently destroyed.\n\n " if self.proxy_is_active: self.proxy.close()
Close the window. This will cause the window to be hidden, the 'closed' event to be fired, and the window subsequently destroyed.
enaml/widgets/window.py
close
AndiEcker/enaml
1,080
python
def close(self): " Close the window.\n\n This will cause the window to be hidden, the 'closed' event\n to be fired, and the window subsequently destroyed.\n\n " if self.proxy_is_active: self.proxy.close()
def close(self): " Close the window.\n\n This will cause the window to be hidden, the 'closed' event\n to be fired, and the window subsequently destroyed.\n\n " if self.proxy_is_active: self.proxy.close()<|docstring|>Close the window. This will cause the window to be hidden, the 'closed' event to be fired, and the window subsequently destroyed.<|endoftext|>
25a6ec70c308a245b4a3905324896c965099955a1a9b91bc6f88d9911ee9e591
def show(self): ' Show the window to the screen.\n\n This is a reimplemented parent class method which will init\n and build the window hierarchy if needed.\n\n ' if (not self.is_initialized): self.initialize() if (not self.proxy_is_active): self.activate_proxy() super(Window, self).show()
Show the window to the screen. This is a reimplemented parent class method which will init and build the window hierarchy if needed.
enaml/widgets/window.py
show
AndiEcker/enaml
1,080
python
def show(self): ' Show the window to the screen.\n\n This is a reimplemented parent class method which will init\n and build the window hierarchy if needed.\n\n ' if (not self.is_initialized): self.initialize() if (not self.proxy_is_active): self.activate_proxy() super(Window, self).show()
def show(self): ' Show the window to the screen.\n\n This is a reimplemented parent class method which will init\n and build the window hierarchy if needed.\n\n ' if (not self.is_initialized): self.initialize() if (not self.proxy_is_active): self.activate_proxy() super(Window, self).show()<|docstring|>Show the window to the screen. This is a reimplemented parent class method which will init and build the window hierarchy if needed.<|endoftext|>
51d81e2216290eb79b877c6f5f89225c5d43a7a207c0d13381a9aa79f1194cb9
@observe('title', 'modality', 'icon') def _update_proxy(self, change): ' Update the ProxyWindow when the Window data changes.\n\n ' super(Window, self)._update_proxy(change)
Update the ProxyWindow when the Window data changes.
enaml/widgets/window.py
_update_proxy
AndiEcker/enaml
1,080
python
@observe('title', 'modality', 'icon') def _update_proxy(self, change): ' \n\n ' super(Window, self)._update_proxy(change)
@observe('title', 'modality', 'icon') def _update_proxy(self, change): ' \n\n ' super(Window, self)._update_proxy(change)<|docstring|>Update the ProxyWindow when the Window data changes.<|endoftext|>
4b679ce5f0be647fd4337a0de1d7121e17cb49e5db92266ae52e643d38c5b5b1
@contextmanager def cached(): 'Context manager that enables the caching system within parametrizations\n registered with :func:`register_parametrization`.\n\n The value of the parametrized objects is computed and cached the first time\n they are required when this context manager is active. The cached values are\n discarded when leaving the context manager.\n\n This is useful when using a parametrized parameter more than once in the forward pass.\n An example of this is when parametrizing the recurrent kernel of an RNN or when\n sharing weights.\n\n The simplest way to activate the cache is by wrapping the forward pass of the neural network\n\n .. code-block:: python\n\n import torch.nn.utils.parametrize as P\n ...\n with P.cached():\n output = model(inputs)\n\n in training and evaluation. One may also wrap the parts of the modules that use\n several times the parametrized tensors. For example, the loop of an RNN with a\n parametrized recurrent kernel:\n\n .. code-block:: python\n\n with P.cached():\n for x in xs:\n out_rnn = self.rnn_cell(x, out_rnn)\n ' global _cache global _cache_enabled _cache_enabled += 1 try: (yield) finally: _cache_enabled -= 1 if (not _cache_enabled): _cache = {}
Context manager that enables the caching system within parametrizations registered with :func:`register_parametrization`. The value of the parametrized objects is computed and cached the first time they are required when this context manager is active. The cached values are discarded when leaving the context manager. This is useful when using a parametrized parameter more than once in the forward pass. An example of this is when parametrizing the recurrent kernel of an RNN or when sharing weights. The simplest way to activate the cache is by wrapping the forward pass of the neural network .. code-block:: python import torch.nn.utils.parametrize as P ... with P.cached(): output = model(inputs) in training and evaluation. One may also wrap the parts of the modules that use several times the parametrized tensors. For example, the loop of an RNN with a parametrized recurrent kernel: .. code-block:: python with P.cached(): for x in xs: out_rnn = self.rnn_cell(x, out_rnn)
torch/nn/utils/parametrize.py
cached
joker-eph/pytorch
60,067
python
@contextmanager def cached(): 'Context manager that enables the caching system within parametrizations\n registered with :func:`register_parametrization`.\n\n The value of the parametrized objects is computed and cached the first time\n they are required when this context manager is active. The cached values are\n discarded when leaving the context manager.\n\n This is useful when using a parametrized parameter more than once in the forward pass.\n An example of this is when parametrizing the recurrent kernel of an RNN or when\n sharing weights.\n\n The simplest way to activate the cache is by wrapping the forward pass of the neural network\n\n .. code-block:: python\n\n import torch.nn.utils.parametrize as P\n ...\n with P.cached():\n output = model(inputs)\n\n in training and evaluation. One may also wrap the parts of the modules that use\n several times the parametrized tensors. For example, the loop of an RNN with a\n parametrized recurrent kernel:\n\n .. code-block:: python\n\n with P.cached():\n for x in xs:\n out_rnn = self.rnn_cell(x, out_rnn)\n ' global _cache global _cache_enabled _cache_enabled += 1 try: (yield) finally: _cache_enabled -= 1 if (not _cache_enabled): _cache = {}
@contextmanager def cached(): 'Context manager that enables the caching system within parametrizations\n registered with :func:`register_parametrization`.\n\n The value of the parametrized objects is computed and cached the first time\n they are required when this context manager is active. The cached values are\n discarded when leaving the context manager.\n\n This is useful when using a parametrized parameter more than once in the forward pass.\n An example of this is when parametrizing the recurrent kernel of an RNN or when\n sharing weights.\n\n The simplest way to activate the cache is by wrapping the forward pass of the neural network\n\n .. code-block:: python\n\n import torch.nn.utils.parametrize as P\n ...\n with P.cached():\n output = model(inputs)\n\n in training and evaluation. One may also wrap the parts of the modules that use\n several times the parametrized tensors. For example, the loop of an RNN with a\n parametrized recurrent kernel:\n\n .. code-block:: python\n\n with P.cached():\n for x in xs:\n out_rnn = self.rnn_cell(x, out_rnn)\n ' global _cache global _cache_enabled _cache_enabled += 1 try: (yield) finally: _cache_enabled -= 1 if (not _cache_enabled): _cache = {}<|docstring|>Context manager that enables the caching system within parametrizations registered with :func:`register_parametrization`. The value of the parametrized objects is computed and cached the first time they are required when this context manager is active. The cached values are discarded when leaving the context manager. This is useful when using a parametrized parameter more than once in the forward pass. An example of this is when parametrizing the recurrent kernel of an RNN or when sharing weights. The simplest way to activate the cache is by wrapping the forward pass of the neural network .. code-block:: python import torch.nn.utils.parametrize as P ... with P.cached(): output = model(inputs) in training and evaluation. One may also wrap the parts of the modules that use several times the parametrized tensors. For example, the loop of an RNN with a parametrized recurrent kernel: .. code-block:: python with P.cached(): for x in xs: out_rnn = self.rnn_cell(x, out_rnn)<|endoftext|>
6890dd4538583e754317fb95bf50b5db50ed6c674605fac5c52c82b3cb6c506a
def _inject_new_class(module: Module) -> None: 'Sets up a module to be parametrized.\n\n This works by substituting the class of the module by a class\n that extends it to be able to inject a property\n\n Args:\n module (nn.Module): module into which to inject the property\n ' cls = module.__class__ def getstate(self): raise RuntimeError('Serialization of parametrized modules is only supported through state_dict(). See:\nhttps://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-a-general-checkpoint-for-inference-and-or-resuming-training') param_cls = type(f'Parametrized{cls.__name__}', (cls,), {'__getstate__': getstate}) module.__class__ = param_cls
Sets up a module to be parametrized. This works by substituting the class of the module by a class that extends it to be able to inject a property Args: module (nn.Module): module into which to inject the property
torch/nn/utils/parametrize.py
_inject_new_class
joker-eph/pytorch
60,067
python
def _inject_new_class(module: Module) -> None: 'Sets up a module to be parametrized.\n\n This works by substituting the class of the module by a class\n that extends it to be able to inject a property\n\n Args:\n module (nn.Module): module into which to inject the property\n ' cls = module.__class__ def getstate(self): raise RuntimeError('Serialization of parametrized modules is only supported through state_dict(). See:\nhttps://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-a-general-checkpoint-for-inference-and-or-resuming-training') param_cls = type(f'Parametrized{cls.__name__}', (cls,), {'__getstate__': getstate}) module.__class__ = param_cls
def _inject_new_class(module: Module) -> None: 'Sets up a module to be parametrized.\n\n This works by substituting the class of the module by a class\n that extends it to be able to inject a property\n\n Args:\n module (nn.Module): module into which to inject the property\n ' cls = module.__class__ def getstate(self): raise RuntimeError('Serialization of parametrized modules is only supported through state_dict(). See:\nhttps://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-a-general-checkpoint-for-inference-and-or-resuming-training') param_cls = type(f'Parametrized{cls.__name__}', (cls,), {'__getstate__': getstate}) module.__class__ = param_cls<|docstring|>Sets up a module to be parametrized. This works by substituting the class of the module by a class that extends it to be able to inject a property Args: module (nn.Module): module into which to inject the property<|endoftext|>
7a39a58d90beb36ee330a43b99c71246ff3c43ceb69956a1adacbb3c1d3dce79
def _inject_property(module: Module, tensor_name: str) -> None: 'Injects a property into module[tensor_name].\n\n It assumes that the class in the module has already been modified from its\n original one using _inject_new_class and that the tensor under :attr:`tensor_name`\n has already been moved out\n\n Args:\n module (nn.Module): module into which to inject the property\n tensor_name (str): name of the name of the property to create\n ' assert (not hasattr(module, tensor_name)) @torch.jit.unused def get_cached_parametrization(parametrization) -> Tensor: global _cache key = (id(module), tensor_name) tensor = _cache.get(key) if (tensor is None): tensor = parametrization() _cache[key] = tensor return tensor def get_parametrized(self) -> Tensor: parametrization = self.parametrizations[tensor_name] if _cache_enabled: if torch.jit.is_scripting(): raise RuntimeError('Caching is not implemented for scripting. Either disable caching or avoid scripting.') elif (torch._C._get_tracing_state() is not None): raise RuntimeError('Cannot trace a model while caching parametrizations.') else: return get_cached_parametrization(parametrization) else: return parametrization() def set_original(self, value: Tensor) -> None: self.parametrizations[tensor_name].right_inverse(value) setattr(module.__class__, tensor_name, property(get_parametrized, set_original))
Injects a property into module[tensor_name]. It assumes that the class in the module has already been modified from its original one using _inject_new_class and that the tensor under :attr:`tensor_name` has already been moved out Args: module (nn.Module): module into which to inject the property tensor_name (str): name of the name of the property to create
torch/nn/utils/parametrize.py
_inject_property
joker-eph/pytorch
60,067
python
def _inject_property(module: Module, tensor_name: str) -> None: 'Injects a property into module[tensor_name].\n\n It assumes that the class in the module has already been modified from its\n original one using _inject_new_class and that the tensor under :attr:`tensor_name`\n has already been moved out\n\n Args:\n module (nn.Module): module into which to inject the property\n tensor_name (str): name of the name of the property to create\n ' assert (not hasattr(module, tensor_name)) @torch.jit.unused def get_cached_parametrization(parametrization) -> Tensor: global _cache key = (id(module), tensor_name) tensor = _cache.get(key) if (tensor is None): tensor = parametrization() _cache[key] = tensor return tensor def get_parametrized(self) -> Tensor: parametrization = self.parametrizations[tensor_name] if _cache_enabled: if torch.jit.is_scripting(): raise RuntimeError('Caching is not implemented for scripting. Either disable caching or avoid scripting.') elif (torch._C._get_tracing_state() is not None): raise RuntimeError('Cannot trace a model while caching parametrizations.') else: return get_cached_parametrization(parametrization) else: return parametrization() def set_original(self, value: Tensor) -> None: self.parametrizations[tensor_name].right_inverse(value) setattr(module.__class__, tensor_name, property(get_parametrized, set_original))
def _inject_property(module: Module, tensor_name: str) -> None: 'Injects a property into module[tensor_name].\n\n It assumes that the class in the module has already been modified from its\n original one using _inject_new_class and that the tensor under :attr:`tensor_name`\n has already been moved out\n\n Args:\n module (nn.Module): module into which to inject the property\n tensor_name (str): name of the name of the property to create\n ' assert (not hasattr(module, tensor_name)) @torch.jit.unused def get_cached_parametrization(parametrization) -> Tensor: global _cache key = (id(module), tensor_name) tensor = _cache.get(key) if (tensor is None): tensor = parametrization() _cache[key] = tensor return tensor def get_parametrized(self) -> Tensor: parametrization = self.parametrizations[tensor_name] if _cache_enabled: if torch.jit.is_scripting(): raise RuntimeError('Caching is not implemented for scripting. Either disable caching or avoid scripting.') elif (torch._C._get_tracing_state() is not None): raise RuntimeError('Cannot trace a model while caching parametrizations.') else: return get_cached_parametrization(parametrization) else: return parametrization() def set_original(self, value: Tensor) -> None: self.parametrizations[tensor_name].right_inverse(value) setattr(module.__class__, tensor_name, property(get_parametrized, set_original))<|docstring|>Injects a property into module[tensor_name]. It assumes that the class in the module has already been modified from its original one using _inject_new_class and that the tensor under :attr:`tensor_name` has already been moved out Args: module (nn.Module): module into which to inject the property tensor_name (str): name of the name of the property to create<|endoftext|>
ddc7a99efa8c176d6a6e7edd6dd002c5f0a15c5a3909856a486810136e2f3097
def register_parametrization(module: Module, tensor_name: str, parametrization: Module, *, unsafe: bool=False) -> Module: 'Adds a parametrization to a tensor in a module.\n\n Assume that ``tensor_name="weight"`` for simplicity. When accessing ``module.weight``,\n the module will return the parametrized version ``parametrization(module.weight)``.\n If the original tensor requires a gradient, the backward pass will differentiate\n through :attr:`parametrization`, and the optimizer will update the tensor accordingly.\n\n The first time that a module registers a parametrization, this function will add an attribute\n ``parametrizations`` to the module of type :class:`~ParametrizationList`.\n\n The list of parametrizations on the tensor ``weight`` will be accessible under\n ``module.parametrizations.weight``.\n\n The original tensor will be accessible under\n ``module.parametrizations.weight.original``.\n\n Parametrizations may be concatenated by registering several parametrizations\n on the same attribute.\n\n The training mode of a registered parametrization is updated on registration\n to match the training mode of the host module\n\n Parametrized parameters and buffers have an inbuilt caching system that can be activated\n using the context manager :func:`cached`.\n\n A :attr:`parametrization` may optionally implement a method with signature\n\n .. code-block:: python\n\n def right_inverse(self, X: Tensor) -> Union[Tensor, Sequence[Tensor]]\n\n This method is called on the unparametrized tensor when the first parametrization\n is registered to compute the initial value of the original tensor.\n If this method is not implemented, the original tensor will be just the unparametrized tensor.\n\n If all the parametrizations registered on a tensor implement `right_inverse` it is possible\n to initialize a parametrized tensor by assigning to it, as shown in the example below.\n\n It is possible for the first parametrization to depend on several inputs.\n This may be implemented returning a tuple of tensors from ``right_inverse``\n (see the example implementation of a ``RankOne`` parametrization below).\n\n In this case, the unconstrained tensors are also located under ``module.parametrizations.weight``\n with names ``original0``, ``original1``,...\n\n .. note::\n\n If unsafe=False (default) both the forward and right_inverse methods will be called\n once to perform a number of consistency checks.\n If unsafe=True, then right_inverse will be called if the tensor is not parametrized,\n and nothing will be called otherwise.\n\n .. note::\n\n In most situations, ``right_inverse`` will be a function such that\n ``forward(right_inverse(X)) == X`` (see\n `right inverse <https://en.wikipedia.org/wiki/Inverse_function#Right_inverses>`_).\n Sometimes, when the parametrization is not surjective, it may be reasonable\n to relax this.\n\n .. warning::\n\n If a parametrization depends on several inputs, :func:`~register_parametrization`\n will register a number of new parameters. If such parametrization is registered\n after the optimizer is created, these new parameters will need to be added manually\n to the optimizer. See :meth:`torch.Optimizer.add_param_group`.\n\n Args:\n module (nn.Module): module on which to register the parametrization\n tensor_name (str): name of the parameter or buffer on which to register\n the parametrization\n parametrization (nn.Module): the parametrization to register\n Keyword args:\n unsafe (bool): a boolean flag that denotes whether the parametrization\n may change the dtype and shape of the tensor. Default: `False`\n Warning: the parametrization is not checked for consistency upon registration.\n Enable this flag at your own risk.\n\n Raises:\n ValueError: if the module does not have a parameter or a buffer named :attr:`tensor_name`\n\n Examples:\n >>> import torch\n >>> import torch.nn as nn\n >>> import torch.nn.utils.parametrize as P\n >>>\n >>> class Symmetric(nn.Module):\n >>> def forward(self, X):\n >>> return X.triu() + X.triu(1).T # Return a symmetric matrix\n >>>\n >>> def right_inverse(self, A):\n >>> return A.triu()\n >>>\n >>> m = nn.Linear(5, 5)\n >>> P.register_parametrization(m, "weight", Symmetric())\n >>> print(torch.allclose(m.weight, m.weight.T)) # m.weight is now symmetric\n True\n >>> A = torch.rand(5, 5)\n >>> A = A + A.T # A is now symmetric\n >>> m.weight = A # Initialize the weight to be the symmetric matrix A\n >>> print(torch.allclose(m.weight, A))\n True\n\n >>> class RankOne(nn.Module):\n >>> def forward(self, x, y):\n >>> # Form a rank 1 matrix multiplying two vectors\n >>> return x.unsqueeze(-1) @ y.unsqueeze(-2)\n >>>\n >>> def right_inverse(self, Z):\n >>> # Project Z onto the rank 1 matrices\n >>> U, S, Vh = torch.linalg.svd(Z, full_matrices=False)\n >>> # Return rescaled singular vectors\n >>> s0_sqrt = S[0].sqrt().unsqueeze(-1)\n >>> return U[..., :, 0] * s0_sqrt, Vh[..., 0, :] * s0_sqrt\n >>>\n >>> linear_rank_one = P.register_parametrization(nn.Linear(4, 4), "weight", RankOne())\n >>> print(torch.linalg.matrix_rank(linear_rank_one.weight).item())\n 1\n\n ' parametrization.train(module.training) if is_parametrized(module, tensor_name): if (not unsafe): Y = getattr(module, tensor_name) X = parametrization(Y) if (not isinstance(X, Tensor)): raise ValueError(f'A parametrization must return a tensor. Got {type(X).__name__}.') if (X.dtype != Y.dtype): raise ValueError(f'''Registering a parametrization may not change the dtype of the tensor, unless the `unsafe` flag is enabled. module.{tensor_name}.dtype: {Y.dtype} parametrization(module.{tensor_name}).dtype: {X.dtype}''') if (X.shape != Y.shape): raise ValueError(f'''Registering a parametrization may not change the shape of the tensor, unless the `unsafe` flag is enabled. module.{tensor_name}.shape: {Y.shape} parametrization(module.{tensor_name}).shape: {X.shape}''') if hasattr(parametrization, 'right_inverse'): try: Z = parametrization.right_inverse(X) except NotImplementedError: pass else: if (not isinstance(Z, Tensor)): raise ValueError(f'parametrization.right_inverse must return a tensor. Got: {type(Z).__name__}') if (Z.dtype != Y.dtype): raise ValueError(f'''The tensor returned by parametrization.right_inverse must have the same dtype as module.{tensor_name}, unless the `unsafe` flag is enabled. module.{tensor_name}.dtype: {Y.dtype} returned dtype: {Z.dtype}''') if (Z.shape != Y.shape): raise ValueError(f'''The tensor returned by parametrization.right_inverse must have the same shape as module.{tensor_name}, unless the `unsafe` flag is enabled. module.{tensor_name}.shape: {Y.shape} returned shape: {Z.shape}''') assert isinstance(module.parametrizations, ModuleDict) module.parametrizations[tensor_name].append(parametrization) module.parametrizations[tensor_name].unsafe |= unsafe elif ((tensor_name in module._buffers) or (tensor_name in module._parameters)): original = getattr(module, tensor_name) parametrizations = ParametrizationList([parametrization], original, unsafe=unsafe) delattr(module, tensor_name) if (not is_parametrized(module)): _inject_new_class(module) module.parametrizations = ModuleDict() _inject_property(module, tensor_name) assert isinstance(module.parametrizations, ModuleDict) module.parametrizations[tensor_name] = parametrizations else: raise ValueError(f"Module '{module}' does not have a parameter, a buffer, or a parametrized element with name '{tensor_name}'") return module
Adds a parametrization to a tensor in a module. Assume that ``tensor_name="weight"`` for simplicity. When accessing ``module.weight``, the module will return the parametrized version ``parametrization(module.weight)``. If the original tensor requires a gradient, the backward pass will differentiate through :attr:`parametrization`, and the optimizer will update the tensor accordingly. The first time that a module registers a parametrization, this function will add an attribute ``parametrizations`` to the module of type :class:`~ParametrizationList`. The list of parametrizations on the tensor ``weight`` will be accessible under ``module.parametrizations.weight``. The original tensor will be accessible under ``module.parametrizations.weight.original``. Parametrizations may be concatenated by registering several parametrizations on the same attribute. The training mode of a registered parametrization is updated on registration to match the training mode of the host module Parametrized parameters and buffers have an inbuilt caching system that can be activated using the context manager :func:`cached`. A :attr:`parametrization` may optionally implement a method with signature .. code-block:: python def right_inverse(self, X: Tensor) -> Union[Tensor, Sequence[Tensor]] This method is called on the unparametrized tensor when the first parametrization is registered to compute the initial value of the original tensor. If this method is not implemented, the original tensor will be just the unparametrized tensor. If all the parametrizations registered on a tensor implement `right_inverse` it is possible to initialize a parametrized tensor by assigning to it, as shown in the example below. It is possible for the first parametrization to depend on several inputs. This may be implemented returning a tuple of tensors from ``right_inverse`` (see the example implementation of a ``RankOne`` parametrization below). In this case, the unconstrained tensors are also located under ``module.parametrizations.weight`` with names ``original0``, ``original1``,... .. note:: If unsafe=False (default) both the forward and right_inverse methods will be called once to perform a number of consistency checks. If unsafe=True, then right_inverse will be called if the tensor is not parametrized, and nothing will be called otherwise. .. note:: In most situations, ``right_inverse`` will be a function such that ``forward(right_inverse(X)) == X`` (see `right inverse <https://en.wikipedia.org/wiki/Inverse_function#Right_inverses>`_). Sometimes, when the parametrization is not surjective, it may be reasonable to relax this. .. warning:: If a parametrization depends on several inputs, :func:`~register_parametrization` will register a number of new parameters. If such parametrization is registered after the optimizer is created, these new parameters will need to be added manually to the optimizer. See :meth:`torch.Optimizer.add_param_group`. Args: module (nn.Module): module on which to register the parametrization tensor_name (str): name of the parameter or buffer on which to register the parametrization parametrization (nn.Module): the parametrization to register Keyword args: unsafe (bool): a boolean flag that denotes whether the parametrization may change the dtype and shape of the tensor. Default: `False` Warning: the parametrization is not checked for consistency upon registration. Enable this flag at your own risk. Raises: ValueError: if the module does not have a parameter or a buffer named :attr:`tensor_name` Examples: >>> import torch >>> import torch.nn as nn >>> import torch.nn.utils.parametrize as P >>> >>> class Symmetric(nn.Module): >>> def forward(self, X): >>> return X.triu() + X.triu(1).T # Return a symmetric matrix >>> >>> def right_inverse(self, A): >>> return A.triu() >>> >>> m = nn.Linear(5, 5) >>> P.register_parametrization(m, "weight", Symmetric()) >>> print(torch.allclose(m.weight, m.weight.T)) # m.weight is now symmetric True >>> A = torch.rand(5, 5) >>> A = A + A.T # A is now symmetric >>> m.weight = A # Initialize the weight to be the symmetric matrix A >>> print(torch.allclose(m.weight, A)) True >>> class RankOne(nn.Module): >>> def forward(self, x, y): >>> # Form a rank 1 matrix multiplying two vectors >>> return x.unsqueeze(-1) @ y.unsqueeze(-2) >>> >>> def right_inverse(self, Z): >>> # Project Z onto the rank 1 matrices >>> U, S, Vh = torch.linalg.svd(Z, full_matrices=False) >>> # Return rescaled singular vectors >>> s0_sqrt = S[0].sqrt().unsqueeze(-1) >>> return U[..., :, 0] * s0_sqrt, Vh[..., 0, :] * s0_sqrt >>> >>> linear_rank_one = P.register_parametrization(nn.Linear(4, 4), "weight", RankOne()) >>> print(torch.linalg.matrix_rank(linear_rank_one.weight).item()) 1
torch/nn/utils/parametrize.py
register_parametrization
joker-eph/pytorch
60,067
python
def register_parametrization(module: Module, tensor_name: str, parametrization: Module, *, unsafe: bool=False) -> Module: 'Adds a parametrization to a tensor in a module.\n\n Assume that ``tensor_name="weight"`` for simplicity. When accessing ``module.weight``,\n the module will return the parametrized version ``parametrization(module.weight)``.\n If the original tensor requires a gradient, the backward pass will differentiate\n through :attr:`parametrization`, and the optimizer will update the tensor accordingly.\n\n The first time that a module registers a parametrization, this function will add an attribute\n ``parametrizations`` to the module of type :class:`~ParametrizationList`.\n\n The list of parametrizations on the tensor ``weight`` will be accessible under\n ``module.parametrizations.weight``.\n\n The original tensor will be accessible under\n ``module.parametrizations.weight.original``.\n\n Parametrizations may be concatenated by registering several parametrizations\n on the same attribute.\n\n The training mode of a registered parametrization is updated on registration\n to match the training mode of the host module\n\n Parametrized parameters and buffers have an inbuilt caching system that can be activated\n using the context manager :func:`cached`.\n\n A :attr:`parametrization` may optionally implement a method with signature\n\n .. code-block:: python\n\n def right_inverse(self, X: Tensor) -> Union[Tensor, Sequence[Tensor]]\n\n This method is called on the unparametrized tensor when the first parametrization\n is registered to compute the initial value of the original tensor.\n If this method is not implemented, the original tensor will be just the unparametrized tensor.\n\n If all the parametrizations registered on a tensor implement `right_inverse` it is possible\n to initialize a parametrized tensor by assigning to it, as shown in the example below.\n\n It is possible for the first parametrization to depend on several inputs.\n This may be implemented returning a tuple of tensors from ``right_inverse``\n (see the example implementation of a ``RankOne`` parametrization below).\n\n In this case, the unconstrained tensors are also located under ``module.parametrizations.weight``\n with names ``original0``, ``original1``,...\n\n .. note::\n\n If unsafe=False (default) both the forward and right_inverse methods will be called\n once to perform a number of consistency checks.\n If unsafe=True, then right_inverse will be called if the tensor is not parametrized,\n and nothing will be called otherwise.\n\n .. note::\n\n In most situations, ``right_inverse`` will be a function such that\n ``forward(right_inverse(X)) == X`` (see\n `right inverse <https://en.wikipedia.org/wiki/Inverse_function#Right_inverses>`_).\n Sometimes, when the parametrization is not surjective, it may be reasonable\n to relax this.\n\n .. warning::\n\n If a parametrization depends on several inputs, :func:`~register_parametrization`\n will register a number of new parameters. If such parametrization is registered\n after the optimizer is created, these new parameters will need to be added manually\n to the optimizer. See :meth:`torch.Optimizer.add_param_group`.\n\n Args:\n module (nn.Module): module on which to register the parametrization\n tensor_name (str): name of the parameter or buffer on which to register\n the parametrization\n parametrization (nn.Module): the parametrization to register\n Keyword args:\n unsafe (bool): a boolean flag that denotes whether the parametrization\n may change the dtype and shape of the tensor. Default: `False`\n Warning: the parametrization is not checked for consistency upon registration.\n Enable this flag at your own risk.\n\n Raises:\n ValueError: if the module does not have a parameter or a buffer named :attr:`tensor_name`\n\n Examples:\n >>> import torch\n >>> import torch.nn as nn\n >>> import torch.nn.utils.parametrize as P\n >>>\n >>> class Symmetric(nn.Module):\n >>> def forward(self, X):\n >>> return X.triu() + X.triu(1).T # Return a symmetric matrix\n >>>\n >>> def right_inverse(self, A):\n >>> return A.triu()\n >>>\n >>> m = nn.Linear(5, 5)\n >>> P.register_parametrization(m, "weight", Symmetric())\n >>> print(torch.allclose(m.weight, m.weight.T)) # m.weight is now symmetric\n True\n >>> A = torch.rand(5, 5)\n >>> A = A + A.T # A is now symmetric\n >>> m.weight = A # Initialize the weight to be the symmetric matrix A\n >>> print(torch.allclose(m.weight, A))\n True\n\n >>> class RankOne(nn.Module):\n >>> def forward(self, x, y):\n >>> # Form a rank 1 matrix multiplying two vectors\n >>> return x.unsqueeze(-1) @ y.unsqueeze(-2)\n >>>\n >>> def right_inverse(self, Z):\n >>> # Project Z onto the rank 1 matrices\n >>> U, S, Vh = torch.linalg.svd(Z, full_matrices=False)\n >>> # Return rescaled singular vectors\n >>> s0_sqrt = S[0].sqrt().unsqueeze(-1)\n >>> return U[..., :, 0] * s0_sqrt, Vh[..., 0, :] * s0_sqrt\n >>>\n >>> linear_rank_one = P.register_parametrization(nn.Linear(4, 4), "weight", RankOne())\n >>> print(torch.linalg.matrix_rank(linear_rank_one.weight).item())\n 1\n\n ' parametrization.train(module.training) if is_parametrized(module, tensor_name): if (not unsafe): Y = getattr(module, tensor_name) X = parametrization(Y) if (not isinstance(X, Tensor)): raise ValueError(f'A parametrization must return a tensor. Got {type(X).__name__}.') if (X.dtype != Y.dtype): raise ValueError(f'Registering a parametrization may not change the dtype of the tensor, unless the `unsafe` flag is enabled. module.{tensor_name}.dtype: {Y.dtype} parametrization(module.{tensor_name}).dtype: {X.dtype}') if (X.shape != Y.shape): raise ValueError(f'Registering a parametrization may not change the shape of the tensor, unless the `unsafe` flag is enabled. module.{tensor_name}.shape: {Y.shape} parametrization(module.{tensor_name}).shape: {X.shape}') if hasattr(parametrization, 'right_inverse'): try: Z = parametrization.right_inverse(X) except NotImplementedError: pass else: if (not isinstance(Z, Tensor)): raise ValueError(f'parametrization.right_inverse must return a tensor. Got: {type(Z).__name__}') if (Z.dtype != Y.dtype): raise ValueError(f'The tensor returned by parametrization.right_inverse must have the same dtype as module.{tensor_name}, unless the `unsafe` flag is enabled. module.{tensor_name}.dtype: {Y.dtype} returned dtype: {Z.dtype}') if (Z.shape != Y.shape): raise ValueError(f'The tensor returned by parametrization.right_inverse must have the same shape as module.{tensor_name}, unless the `unsafe` flag is enabled. module.{tensor_name}.shape: {Y.shape} returned shape: {Z.shape}') assert isinstance(module.parametrizations, ModuleDict) module.parametrizations[tensor_name].append(parametrization) module.parametrizations[tensor_name].unsafe |= unsafe elif ((tensor_name in module._buffers) or (tensor_name in module._parameters)): original = getattr(module, tensor_name) parametrizations = ParametrizationList([parametrization], original, unsafe=unsafe) delattr(module, tensor_name) if (not is_parametrized(module)): _inject_new_class(module) module.parametrizations = ModuleDict() _inject_property(module, tensor_name) assert isinstance(module.parametrizations, ModuleDict) module.parametrizations[tensor_name] = parametrizations else: raise ValueError(f"Module '{module}' does not have a parameter, a buffer, or a parametrized element with name '{tensor_name}'") return module
def register_parametrization(module: Module, tensor_name: str, parametrization: Module, *, unsafe: bool=False) -> Module: 'Adds a parametrization to a tensor in a module.\n\n Assume that ``tensor_name="weight"`` for simplicity. When accessing ``module.weight``,\n the module will return the parametrized version ``parametrization(module.weight)``.\n If the original tensor requires a gradient, the backward pass will differentiate\n through :attr:`parametrization`, and the optimizer will update the tensor accordingly.\n\n The first time that a module registers a parametrization, this function will add an attribute\n ``parametrizations`` to the module of type :class:`~ParametrizationList`.\n\n The list of parametrizations on the tensor ``weight`` will be accessible under\n ``module.parametrizations.weight``.\n\n The original tensor will be accessible under\n ``module.parametrizations.weight.original``.\n\n Parametrizations may be concatenated by registering several parametrizations\n on the same attribute.\n\n The training mode of a registered parametrization is updated on registration\n to match the training mode of the host module\n\n Parametrized parameters and buffers have an inbuilt caching system that can be activated\n using the context manager :func:`cached`.\n\n A :attr:`parametrization` may optionally implement a method with signature\n\n .. code-block:: python\n\n def right_inverse(self, X: Tensor) -> Union[Tensor, Sequence[Tensor]]\n\n This method is called on the unparametrized tensor when the first parametrization\n is registered to compute the initial value of the original tensor.\n If this method is not implemented, the original tensor will be just the unparametrized tensor.\n\n If all the parametrizations registered on a tensor implement `right_inverse` it is possible\n to initialize a parametrized tensor by assigning to it, as shown in the example below.\n\n It is possible for the first parametrization to depend on several inputs.\n This may be implemented returning a tuple of tensors from ``right_inverse``\n (see the example implementation of a ``RankOne`` parametrization below).\n\n In this case, the unconstrained tensors are also located under ``module.parametrizations.weight``\n with names ``original0``, ``original1``,...\n\n .. note::\n\n If unsafe=False (default) both the forward and right_inverse methods will be called\n once to perform a number of consistency checks.\n If unsafe=True, then right_inverse will be called if the tensor is not parametrized,\n and nothing will be called otherwise.\n\n .. note::\n\n In most situations, ``right_inverse`` will be a function such that\n ``forward(right_inverse(X)) == X`` (see\n `right inverse <https://en.wikipedia.org/wiki/Inverse_function#Right_inverses>`_).\n Sometimes, when the parametrization is not surjective, it may be reasonable\n to relax this.\n\n .. warning::\n\n If a parametrization depends on several inputs, :func:`~register_parametrization`\n will register a number of new parameters. If such parametrization is registered\n after the optimizer is created, these new parameters will need to be added manually\n to the optimizer. See :meth:`torch.Optimizer.add_param_group`.\n\n Args:\n module (nn.Module): module on which to register the parametrization\n tensor_name (str): name of the parameter or buffer on which to register\n the parametrization\n parametrization (nn.Module): the parametrization to register\n Keyword args:\n unsafe (bool): a boolean flag that denotes whether the parametrization\n may change the dtype and shape of the tensor. Default: `False`\n Warning: the parametrization is not checked for consistency upon registration.\n Enable this flag at your own risk.\n\n Raises:\n ValueError: if the module does not have a parameter or a buffer named :attr:`tensor_name`\n\n Examples:\n >>> import torch\n >>> import torch.nn as nn\n >>> import torch.nn.utils.parametrize as P\n >>>\n >>> class Symmetric(nn.Module):\n >>> def forward(self, X):\n >>> return X.triu() + X.triu(1).T # Return a symmetric matrix\n >>>\n >>> def right_inverse(self, A):\n >>> return A.triu()\n >>>\n >>> m = nn.Linear(5, 5)\n >>> P.register_parametrization(m, "weight", Symmetric())\n >>> print(torch.allclose(m.weight, m.weight.T)) # m.weight is now symmetric\n True\n >>> A = torch.rand(5, 5)\n >>> A = A + A.T # A is now symmetric\n >>> m.weight = A # Initialize the weight to be the symmetric matrix A\n >>> print(torch.allclose(m.weight, A))\n True\n\n >>> class RankOne(nn.Module):\n >>> def forward(self, x, y):\n >>> # Form a rank 1 matrix multiplying two vectors\n >>> return x.unsqueeze(-1) @ y.unsqueeze(-2)\n >>>\n >>> def right_inverse(self, Z):\n >>> # Project Z onto the rank 1 matrices\n >>> U, S, Vh = torch.linalg.svd(Z, full_matrices=False)\n >>> # Return rescaled singular vectors\n >>> s0_sqrt = S[0].sqrt().unsqueeze(-1)\n >>> return U[..., :, 0] * s0_sqrt, Vh[..., 0, :] * s0_sqrt\n >>>\n >>> linear_rank_one = P.register_parametrization(nn.Linear(4, 4), "weight", RankOne())\n >>> print(torch.linalg.matrix_rank(linear_rank_one.weight).item())\n 1\n\n ' parametrization.train(module.training) if is_parametrized(module, tensor_name): if (not unsafe): Y = getattr(module, tensor_name) X = parametrization(Y) if (not isinstance(X, Tensor)): raise ValueError(f'A parametrization must return a tensor. Got {type(X).__name__}.') if (X.dtype != Y.dtype): raise ValueError(f'Registering a parametrization may not change the dtype of the tensor, unless the `unsafe` flag is enabled. module.{tensor_name}.dtype: {Y.dtype} parametrization(module.{tensor_name}).dtype: {X.dtype}') if (X.shape != Y.shape): raise ValueError(f'Registering a parametrization may not change the shape of the tensor, unless the `unsafe` flag is enabled. module.{tensor_name}.shape: {Y.shape} parametrization(module.{tensor_name}).shape: {X.shape}') if hasattr(parametrization, 'right_inverse'): try: Z = parametrization.right_inverse(X) except NotImplementedError: pass else: if (not isinstance(Z, Tensor)): raise ValueError(f'parametrization.right_inverse must return a tensor. Got: {type(Z).__name__}') if (Z.dtype != Y.dtype): raise ValueError(f'The tensor returned by parametrization.right_inverse must have the same dtype as module.{tensor_name}, unless the `unsafe` flag is enabled. module.{tensor_name}.dtype: {Y.dtype} returned dtype: {Z.dtype}') if (Z.shape != Y.shape): raise ValueError(f'The tensor returned by parametrization.right_inverse must have the same shape as module.{tensor_name}, unless the `unsafe` flag is enabled. module.{tensor_name}.shape: {Y.shape} returned shape: {Z.shape}') assert isinstance(module.parametrizations, ModuleDict) module.parametrizations[tensor_name].append(parametrization) module.parametrizations[tensor_name].unsafe |= unsafe elif ((tensor_name in module._buffers) or (tensor_name in module._parameters)): original = getattr(module, tensor_name) parametrizations = ParametrizationList([parametrization], original, unsafe=unsafe) delattr(module, tensor_name) if (not is_parametrized(module)): _inject_new_class(module) module.parametrizations = ModuleDict() _inject_property(module, tensor_name) assert isinstance(module.parametrizations, ModuleDict) module.parametrizations[tensor_name] = parametrizations else: raise ValueError(f"Module '{module}' does not have a parameter, a buffer, or a parametrized element with name '{tensor_name}'") return module<|docstring|>Adds a parametrization to a tensor in a module. Assume that ``tensor_name="weight"`` for simplicity. When accessing ``module.weight``, the module will return the parametrized version ``parametrization(module.weight)``. If the original tensor requires a gradient, the backward pass will differentiate through :attr:`parametrization`, and the optimizer will update the tensor accordingly. The first time that a module registers a parametrization, this function will add an attribute ``parametrizations`` to the module of type :class:`~ParametrizationList`. The list of parametrizations on the tensor ``weight`` will be accessible under ``module.parametrizations.weight``. The original tensor will be accessible under ``module.parametrizations.weight.original``. Parametrizations may be concatenated by registering several parametrizations on the same attribute. The training mode of a registered parametrization is updated on registration to match the training mode of the host module Parametrized parameters and buffers have an inbuilt caching system that can be activated using the context manager :func:`cached`. A :attr:`parametrization` may optionally implement a method with signature .. code-block:: python def right_inverse(self, X: Tensor) -> Union[Tensor, Sequence[Tensor]] This method is called on the unparametrized tensor when the first parametrization is registered to compute the initial value of the original tensor. If this method is not implemented, the original tensor will be just the unparametrized tensor. If all the parametrizations registered on a tensor implement `right_inverse` it is possible to initialize a parametrized tensor by assigning to it, as shown in the example below. It is possible for the first parametrization to depend on several inputs. This may be implemented returning a tuple of tensors from ``right_inverse`` (see the example implementation of a ``RankOne`` parametrization below). In this case, the unconstrained tensors are also located under ``module.parametrizations.weight`` with names ``original0``, ``original1``,... .. note:: If unsafe=False (default) both the forward and right_inverse methods will be called once to perform a number of consistency checks. If unsafe=True, then right_inverse will be called if the tensor is not parametrized, and nothing will be called otherwise. .. note:: In most situations, ``right_inverse`` will be a function such that ``forward(right_inverse(X)) == X`` (see `right inverse <https://en.wikipedia.org/wiki/Inverse_function#Right_inverses>`_). Sometimes, when the parametrization is not surjective, it may be reasonable to relax this. .. warning:: If a parametrization depends on several inputs, :func:`~register_parametrization` will register a number of new parameters. If such parametrization is registered after the optimizer is created, these new parameters will need to be added manually to the optimizer. See :meth:`torch.Optimizer.add_param_group`. Args: module (nn.Module): module on which to register the parametrization tensor_name (str): name of the parameter or buffer on which to register the parametrization parametrization (nn.Module): the parametrization to register Keyword args: unsafe (bool): a boolean flag that denotes whether the parametrization may change the dtype and shape of the tensor. Default: `False` Warning: the parametrization is not checked for consistency upon registration. Enable this flag at your own risk. Raises: ValueError: if the module does not have a parameter or a buffer named :attr:`tensor_name` Examples: >>> import torch >>> import torch.nn as nn >>> import torch.nn.utils.parametrize as P >>> >>> class Symmetric(nn.Module): >>> def forward(self, X): >>> return X.triu() + X.triu(1).T # Return a symmetric matrix >>> >>> def right_inverse(self, A): >>> return A.triu() >>> >>> m = nn.Linear(5, 5) >>> P.register_parametrization(m, "weight", Symmetric()) >>> print(torch.allclose(m.weight, m.weight.T)) # m.weight is now symmetric True >>> A = torch.rand(5, 5) >>> A = A + A.T # A is now symmetric >>> m.weight = A # Initialize the weight to be the symmetric matrix A >>> print(torch.allclose(m.weight, A)) True >>> class RankOne(nn.Module): >>> def forward(self, x, y): >>> # Form a rank 1 matrix multiplying two vectors >>> return x.unsqueeze(-1) @ y.unsqueeze(-2) >>> >>> def right_inverse(self, Z): >>> # Project Z onto the rank 1 matrices >>> U, S, Vh = torch.linalg.svd(Z, full_matrices=False) >>> # Return rescaled singular vectors >>> s0_sqrt = S[0].sqrt().unsqueeze(-1) >>> return U[..., :, 0] * s0_sqrt, Vh[..., 0, :] * s0_sqrt >>> >>> linear_rank_one = P.register_parametrization(nn.Linear(4, 4), "weight", RankOne()) >>> print(torch.linalg.matrix_rank(linear_rank_one.weight).item()) 1<|endoftext|>
fdff9622be9221f938618f7dacb4da17e2852b1e5de82d45d404999a1732ae04
def is_parametrized(module: Module, tensor_name: Optional[str]=None) -> bool: 'Returns ``True`` if module has an active parametrization.\n\n If the argument :attr:`tensor_name` is specified, returns ``True`` if\n ``module[tensor_name]`` is parametrized.\n\n Args:\n module (nn.Module): module to query\n name (str, optional): attribute in the module to query\n Default: ``None``\n ' parametrizations = getattr(module, 'parametrizations', None) if ((parametrizations is None) or (not isinstance(parametrizations, ModuleDict))): return False if (tensor_name is None): return (len(parametrizations) > 0) else: return (tensor_name in parametrizations)
Returns ``True`` if module has an active parametrization. If the argument :attr:`tensor_name` is specified, returns ``True`` if ``module[tensor_name]`` is parametrized. Args: module (nn.Module): module to query name (str, optional): attribute in the module to query Default: ``None``
torch/nn/utils/parametrize.py
is_parametrized
joker-eph/pytorch
60,067
python
def is_parametrized(module: Module, tensor_name: Optional[str]=None) -> bool: 'Returns ``True`` if module has an active parametrization.\n\n If the argument :attr:`tensor_name` is specified, returns ``True`` if\n ``module[tensor_name]`` is parametrized.\n\n Args:\n module (nn.Module): module to query\n name (str, optional): attribute in the module to query\n Default: ``None``\n ' parametrizations = getattr(module, 'parametrizations', None) if ((parametrizations is None) or (not isinstance(parametrizations, ModuleDict))): return False if (tensor_name is None): return (len(parametrizations) > 0) else: return (tensor_name in parametrizations)
def is_parametrized(module: Module, tensor_name: Optional[str]=None) -> bool: 'Returns ``True`` if module has an active parametrization.\n\n If the argument :attr:`tensor_name` is specified, returns ``True`` if\n ``module[tensor_name]`` is parametrized.\n\n Args:\n module (nn.Module): module to query\n name (str, optional): attribute in the module to query\n Default: ``None``\n ' parametrizations = getattr(module, 'parametrizations', None) if ((parametrizations is None) or (not isinstance(parametrizations, ModuleDict))): return False if (tensor_name is None): return (len(parametrizations) > 0) else: return (tensor_name in parametrizations)<|docstring|>Returns ``True`` if module has an active parametrization. If the argument :attr:`tensor_name` is specified, returns ``True`` if ``module[tensor_name]`` is parametrized. Args: module (nn.Module): module to query name (str, optional): attribute in the module to query Default: ``None``<|endoftext|>
f3db34c7fb586e0a221851f3482b1ac1681999571a7be33f4965650c421d59eb
def remove_parametrizations(module: Module, tensor_name: str, leave_parametrized: bool=True) -> Module: 'Removes the parametrizations on a tensor in a module.\n\n - If ``leave_parametrized=True``, ``module[tensor_name]`` will be set to\n its current output. In this case, the parametrization shall not change the ``dtype``\n of the tensor.\n - If ``leave_parametrized=False``, ``module[tensor_name]`` will be set to\n the unparametrised tensor in ``module.parametrizations[tensor_name].original``.\n This is only possible when the parametrization depends on just one tensor.\n\n Args:\n module (nn.Module): module from which remove the parametrization\n tensor_name (str): name of the parametrization to be removed\n leave_parametrized (bool, optional): leave the attribute :attr:`tensor_name` parametrized.\n Default: ``True``\n\n Returns:\n Module: module\n\n Raises:\n ValueError: if ``module[tensor_name]`` is not parametrized\n ValueError: if ``leave_parametrized=False`` and the parametrization depends on several tensors\n ' if (not is_parametrized(module, tensor_name)): raise ValueError(f'Module {module} does not have a parametrization on {tensor_name}') assert isinstance(module.parametrizations, ModuleDict) parametrizations = module.parametrizations[tensor_name] if parametrizations.is_tensor: original = parametrizations.original if leave_parametrized: with torch.no_grad(): t = getattr(module, tensor_name) with torch.no_grad(): original.set_(t) elif leave_parametrized: t = getattr(module, tensor_name) original = (Parameter(t) if t.requires_grad else t) else: raise ValueError('Cannot leave unparametrized (`leave_parametrized=False`) a tensor that is parametrized in terms of a sequence of tensors.') delattr(module.__class__, tensor_name) del module.parametrizations[tensor_name] _register_parameter_or_buffer(module, tensor_name, original) if (not is_parametrized(module)): delattr(module, 'parametrizations') orig_cls = module.__class__.__bases__[0] module.__class__ = orig_cls return module
Removes the parametrizations on a tensor in a module. - If ``leave_parametrized=True``, ``module[tensor_name]`` will be set to its current output. In this case, the parametrization shall not change the ``dtype`` of the tensor. - If ``leave_parametrized=False``, ``module[tensor_name]`` will be set to the unparametrised tensor in ``module.parametrizations[tensor_name].original``. This is only possible when the parametrization depends on just one tensor. Args: module (nn.Module): module from which remove the parametrization tensor_name (str): name of the parametrization to be removed leave_parametrized (bool, optional): leave the attribute :attr:`tensor_name` parametrized. Default: ``True`` Returns: Module: module Raises: ValueError: if ``module[tensor_name]`` is not parametrized ValueError: if ``leave_parametrized=False`` and the parametrization depends on several tensors
torch/nn/utils/parametrize.py
remove_parametrizations
joker-eph/pytorch
60,067
python
def remove_parametrizations(module: Module, tensor_name: str, leave_parametrized: bool=True) -> Module: 'Removes the parametrizations on a tensor in a module.\n\n - If ``leave_parametrized=True``, ``module[tensor_name]`` will be set to\n its current output. In this case, the parametrization shall not change the ``dtype``\n of the tensor.\n - If ``leave_parametrized=False``, ``module[tensor_name]`` will be set to\n the unparametrised tensor in ``module.parametrizations[tensor_name].original``.\n This is only possible when the parametrization depends on just one tensor.\n\n Args:\n module (nn.Module): module from which remove the parametrization\n tensor_name (str): name of the parametrization to be removed\n leave_parametrized (bool, optional): leave the attribute :attr:`tensor_name` parametrized.\n Default: ``True``\n\n Returns:\n Module: module\n\n Raises:\n ValueError: if ``module[tensor_name]`` is not parametrized\n ValueError: if ``leave_parametrized=False`` and the parametrization depends on several tensors\n ' if (not is_parametrized(module, tensor_name)): raise ValueError(f'Module {module} does not have a parametrization on {tensor_name}') assert isinstance(module.parametrizations, ModuleDict) parametrizations = module.parametrizations[tensor_name] if parametrizations.is_tensor: original = parametrizations.original if leave_parametrized: with torch.no_grad(): t = getattr(module, tensor_name) with torch.no_grad(): original.set_(t) elif leave_parametrized: t = getattr(module, tensor_name) original = (Parameter(t) if t.requires_grad else t) else: raise ValueError('Cannot leave unparametrized (`leave_parametrized=False`) a tensor that is parametrized in terms of a sequence of tensors.') delattr(module.__class__, tensor_name) del module.parametrizations[tensor_name] _register_parameter_or_buffer(module, tensor_name, original) if (not is_parametrized(module)): delattr(module, 'parametrizations') orig_cls = module.__class__.__bases__[0] module.__class__ = orig_cls return module
def remove_parametrizations(module: Module, tensor_name: str, leave_parametrized: bool=True) -> Module: 'Removes the parametrizations on a tensor in a module.\n\n - If ``leave_parametrized=True``, ``module[tensor_name]`` will be set to\n its current output. In this case, the parametrization shall not change the ``dtype``\n of the tensor.\n - If ``leave_parametrized=False``, ``module[tensor_name]`` will be set to\n the unparametrised tensor in ``module.parametrizations[tensor_name].original``.\n This is only possible when the parametrization depends on just one tensor.\n\n Args:\n module (nn.Module): module from which remove the parametrization\n tensor_name (str): name of the parametrization to be removed\n leave_parametrized (bool, optional): leave the attribute :attr:`tensor_name` parametrized.\n Default: ``True``\n\n Returns:\n Module: module\n\n Raises:\n ValueError: if ``module[tensor_name]`` is not parametrized\n ValueError: if ``leave_parametrized=False`` and the parametrization depends on several tensors\n ' if (not is_parametrized(module, tensor_name)): raise ValueError(f'Module {module} does not have a parametrization on {tensor_name}') assert isinstance(module.parametrizations, ModuleDict) parametrizations = module.parametrizations[tensor_name] if parametrizations.is_tensor: original = parametrizations.original if leave_parametrized: with torch.no_grad(): t = getattr(module, tensor_name) with torch.no_grad(): original.set_(t) elif leave_parametrized: t = getattr(module, tensor_name) original = (Parameter(t) if t.requires_grad else t) else: raise ValueError('Cannot leave unparametrized (`leave_parametrized=False`) a tensor that is parametrized in terms of a sequence of tensors.') delattr(module.__class__, tensor_name) del module.parametrizations[tensor_name] _register_parameter_or_buffer(module, tensor_name, original) if (not is_parametrized(module)): delattr(module, 'parametrizations') orig_cls = module.__class__.__bases__[0] module.__class__ = orig_cls return module<|docstring|>Removes the parametrizations on a tensor in a module. - If ``leave_parametrized=True``, ``module[tensor_name]`` will be set to its current output. In this case, the parametrization shall not change the ``dtype`` of the tensor. - If ``leave_parametrized=False``, ``module[tensor_name]`` will be set to the unparametrised tensor in ``module.parametrizations[tensor_name].original``. This is only possible when the parametrization depends on just one tensor. Args: module (nn.Module): module from which remove the parametrization tensor_name (str): name of the parametrization to be removed leave_parametrized (bool, optional): leave the attribute :attr:`tensor_name` parametrized. Default: ``True`` Returns: Module: module Raises: ValueError: if ``module[tensor_name]`` is not parametrized ValueError: if ``leave_parametrized=False`` and the parametrization depends on several tensors<|endoftext|>
e515300f7b1b9bddba890a1fb03018a733bc99bcc44669318b0156b6aada77ea
def right_inverse(self, value: Tensor) -> None: 'Calls the methods ``right_inverse`` (see :func:`register_parametrization`)\n of the parametrizations in the inverse order they were registered in.\n Then, it stores the result in ``self.original`` if ``right_inverse`` outputs one tensor\n or in ``self.original0``, ``self.original1``, ... if it outputs several.\n\n Args:\n value (Tensor): Value to which initialize the module\n ' with torch.no_grad(): for module in reversed(self): if hasattr(module, 'right_inverse'): value = module.right_inverse(value) else: raise RuntimeError(f'parametrization {type(module).__name__} does not implement right_inverse.') if self.is_tensor: if (not isinstance(value, Tensor)): raise ValueError(f'`right_inverse` should return a tensor. Got {type(value).__name__}') if (value.dtype != self.original.dtype): raise ValueError(f'The tensor returned by `right_inverse` has dtype {value.dtype} while `original` has dtype {self.original.dtype}') self.original.set_(value) else: if (not isinstance(value, collections.abc.Sequence)): raise ValueError(f"'right_inverse' must return a sequence of tensors. Got {type(value).__name__}.") if (len(value) != self.ntensors): raise ValueError(f"'right_inverse' must return a sequence of tensors of length {self.ntensors}. Got a sequence of lenght {len(value)}.") for (i, tensor) in enumerate(value): original_i = getattr(self, f'original{i}') if (not isinstance(tensor, Tensor)): raise ValueError(f'`right_inverse` must return a sequence of tensors. Got element {i} of type {type(tensor).__name__}') if (original_i.dtype != tensor.dtype): raise ValueError(f'Tensor {i} returned by `right_inverse` has dtype {tensor.dtype} while `original{i}` has dtype {original_i.dtype}') original_i.set_(tensor)
Calls the methods ``right_inverse`` (see :func:`register_parametrization`) of the parametrizations in the inverse order they were registered in. Then, it stores the result in ``self.original`` if ``right_inverse`` outputs one tensor or in ``self.original0``, ``self.original1``, ... if it outputs several. Args: value (Tensor): Value to which initialize the module
torch/nn/utils/parametrize.py
right_inverse
joker-eph/pytorch
60,067
python
def right_inverse(self, value: Tensor) -> None: 'Calls the methods ``right_inverse`` (see :func:`register_parametrization`)\n of the parametrizations in the inverse order they were registered in.\n Then, it stores the result in ``self.original`` if ``right_inverse`` outputs one tensor\n or in ``self.original0``, ``self.original1``, ... if it outputs several.\n\n Args:\n value (Tensor): Value to which initialize the module\n ' with torch.no_grad(): for module in reversed(self): if hasattr(module, 'right_inverse'): value = module.right_inverse(value) else: raise RuntimeError(f'parametrization {type(module).__name__} does not implement right_inverse.') if self.is_tensor: if (not isinstance(value, Tensor)): raise ValueError(f'`right_inverse` should return a tensor. Got {type(value).__name__}') if (value.dtype != self.original.dtype): raise ValueError(f'The tensor returned by `right_inverse` has dtype {value.dtype} while `original` has dtype {self.original.dtype}') self.original.set_(value) else: if (not isinstance(value, collections.abc.Sequence)): raise ValueError(f"'right_inverse' must return a sequence of tensors. Got {type(value).__name__}.") if (len(value) != self.ntensors): raise ValueError(f"'right_inverse' must return a sequence of tensors of length {self.ntensors}. Got a sequence of lenght {len(value)}.") for (i, tensor) in enumerate(value): original_i = getattr(self, f'original{i}') if (not isinstance(tensor, Tensor)): raise ValueError(f'`right_inverse` must return a sequence of tensors. Got element {i} of type {type(tensor).__name__}') if (original_i.dtype != tensor.dtype): raise ValueError(f'Tensor {i} returned by `right_inverse` has dtype {tensor.dtype} while `original{i}` has dtype {original_i.dtype}') original_i.set_(tensor)
def right_inverse(self, value: Tensor) -> None: 'Calls the methods ``right_inverse`` (see :func:`register_parametrization`)\n of the parametrizations in the inverse order they were registered in.\n Then, it stores the result in ``self.original`` if ``right_inverse`` outputs one tensor\n or in ``self.original0``, ``self.original1``, ... if it outputs several.\n\n Args:\n value (Tensor): Value to which initialize the module\n ' with torch.no_grad(): for module in reversed(self): if hasattr(module, 'right_inverse'): value = module.right_inverse(value) else: raise RuntimeError(f'parametrization {type(module).__name__} does not implement right_inverse.') if self.is_tensor: if (not isinstance(value, Tensor)): raise ValueError(f'`right_inverse` should return a tensor. Got {type(value).__name__}') if (value.dtype != self.original.dtype): raise ValueError(f'The tensor returned by `right_inverse` has dtype {value.dtype} while `original` has dtype {self.original.dtype}') self.original.set_(value) else: if (not isinstance(value, collections.abc.Sequence)): raise ValueError(f"'right_inverse' must return a sequence of tensors. Got {type(value).__name__}.") if (len(value) != self.ntensors): raise ValueError(f"'right_inverse' must return a sequence of tensors of length {self.ntensors}. Got a sequence of lenght {len(value)}.") for (i, tensor) in enumerate(value): original_i = getattr(self, f'original{i}') if (not isinstance(tensor, Tensor)): raise ValueError(f'`right_inverse` must return a sequence of tensors. Got element {i} of type {type(tensor).__name__}') if (original_i.dtype != tensor.dtype): raise ValueError(f'Tensor {i} returned by `right_inverse` has dtype {tensor.dtype} while `original{i}` has dtype {original_i.dtype}') original_i.set_(tensor)<|docstring|>Calls the methods ``right_inverse`` (see :func:`register_parametrization`) of the parametrizations in the inverse order they were registered in. Then, it stores the result in ``self.original`` if ``right_inverse`` outputs one tensor or in ``self.original0``, ``self.original1``, ... if it outputs several. Args: value (Tensor): Value to which initialize the module<|endoftext|>
00eb85dc9797ea90cb99e73ee1fdd2764d9236bcfbdf9d2d30e553d55e40bcfc
def hasPathSum(self, root, sum): '\n :type root: TreeNode\n :type sum: int\n :rtype: bool\n ' if (not root): return False elif ((not root.left) and (not root.right)): return (root.val == sum) return (self.hasPathSum(root.left, (sum - root.val)) or self.hasPathSum(root.right, (sum - root.val)))
:type root: TreeNode :type sum: int :rtype: bool
100-199/112-path-sum.py
hasPathSum
bcongdon/leetcode
4
python
def hasPathSum(self, root, sum): '\n :type root: TreeNode\n :type sum: int\n :rtype: bool\n ' if (not root): return False elif ((not root.left) and (not root.right)): return (root.val == sum) return (self.hasPathSum(root.left, (sum - root.val)) or self.hasPathSum(root.right, (sum - root.val)))
def hasPathSum(self, root, sum): '\n :type root: TreeNode\n :type sum: int\n :rtype: bool\n ' if (not root): return False elif ((not root.left) and (not root.right)): return (root.val == sum) return (self.hasPathSum(root.left, (sum - root.val)) or self.hasPathSum(root.right, (sum - root.val)))<|docstring|>:type root: TreeNode :type sum: int :rtype: bool<|endoftext|>
4481db6634b935e149ff85b9c99161ee2ee2dd4bcc225d38d045c25bcd21afc0
def mock_add_paths(self, path): 'Adds a path and all of its parents to the set of existing paths.' self._mock_path_exists.add(path)
Adds a path and all of its parents to the set of existing paths.
recipe_modules/path/api.py
mock_add_paths
Acidburn0zzz/luci
1
python
def mock_add_paths(self, path): self._mock_path_exists.add(path)
def mock_add_paths(self, path): self._mock_path_exists.add(path)<|docstring|>Adds a path and all of its parents to the set of existing paths.<|endoftext|>
78411f81cb3c1e220f3af2471d59daf45ff1ccca09cbaa1baf361f97fa4c14b5
def mock_copy_paths(self, source, dest): 'Duplicates a path and all of its children to another path.' self._mock_path_exists.copy(source, dest)
Duplicates a path and all of its children to another path.
recipe_modules/path/api.py
mock_copy_paths
Acidburn0zzz/luci
1
python
def mock_copy_paths(self, source, dest): self._mock_path_exists.copy(source, dest)
def mock_copy_paths(self, source, dest): self._mock_path_exists.copy(source, dest)<|docstring|>Duplicates a path and all of its children to another path.<|endoftext|>
36240cefcbafaa2c63c7963aa62c0dd062dcad4c696e9c002d7a3c49cac39200
def mock_remove_paths(self, path, filt): 'Removes a path and all of its children from the set of existing paths.' self._mock_path_exists.remove(path, filt)
Removes a path and all of its children from the set of existing paths.
recipe_modules/path/api.py
mock_remove_paths
Acidburn0zzz/luci
1
python
def mock_remove_paths(self, path, filt): self._mock_path_exists.remove(path, filt)
def mock_remove_paths(self, path, filt): self._mock_path_exists.remove(path, filt)<|docstring|>Removes a path and all of its children from the set of existing paths.<|endoftext|>