repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ethereum/web3.py | web3/iban.py | mod9710 | def mod9710(iban):
"""
Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064.
@method mod9710
@param {String} iban
@returns {Number}
"""
remainder = iban
block = None
while len(remainder) > 2:
block = remainder[:9]
remainder = str(int(block) % 97) + remainder[len(block):]
return int(remainder) % 97 | python | def mod9710(iban):
"""
Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064.
@method mod9710
@param {String} iban
@returns {Number}
"""
remainder = iban
block = None
while len(remainder) > 2:
block = remainder[:9]
remainder = str(int(block) % 97) + remainder[len(block):]
return int(remainder) % 97 | [
"def",
"mod9710",
"(",
"iban",
")",
":",
"remainder",
"=",
"iban",
"block",
"=",
"None",
"while",
"len",
"(",
"remainder",
")",
">",
"2",
":",
"block",
"=",
"remainder",
"[",
":",
"9",
"]",
"remainder",
"=",
"str",
"(",
"int",
"(",
"block",
")",
... | Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064.
@method mod9710
@param {String} iban
@returns {Number} | [
"Calculates",
"the",
"MOD",
"97",
"10",
"of",
"the",
"passed",
"IBAN",
"as",
"specified",
"in",
"ISO7064",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/iban.py#L44-L59 | train | 220,300 |
ethereum/web3.py | web3/iban.py | baseN | def baseN(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
"""
This prototype should be used to create
an iban object from iban correct string
@param {String} iban
"""
return ((num == 0) and numerals[0]) or \
(baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b]) | python | def baseN(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
"""
This prototype should be used to create
an iban object from iban correct string
@param {String} iban
"""
return ((num == 0) and numerals[0]) or \
(baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b]) | [
"def",
"baseN",
"(",
"num",
",",
"b",
",",
"numerals",
"=",
"\"0123456789abcdefghijklmnopqrstuvwxyz\"",
")",
":",
"return",
"(",
"(",
"num",
"==",
"0",
")",
"and",
"numerals",
"[",
"0",
"]",
")",
"or",
"(",
"baseN",
"(",
"num",
"//",
"b",
",",
"b",
... | This prototype should be used to create
an iban object from iban correct string
@param {String} iban | [
"This",
"prototype",
"should",
"be",
"used",
"to",
"create",
"an",
"iban",
"object",
"from",
"iban",
"correct",
"string"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/iban.py#L62-L70 | train | 220,301 |
ethereum/web3.py | web3/iban.py | Iban.fromAddress | def fromAddress(address):
"""
This method should be used to create
an iban object from ethereum address
@method fromAddress
@param {String} address
@return {Iban} the IBAN object
"""
validate_address(address)
address_as_integer = int(address, 16)
address_as_base36 = baseN(address_as_integer, 36)
padded = pad_left_hex(address_as_base36, 15)
return Iban.fromBban(padded.upper()) | python | def fromAddress(address):
"""
This method should be used to create
an iban object from ethereum address
@method fromAddress
@param {String} address
@return {Iban} the IBAN object
"""
validate_address(address)
address_as_integer = int(address, 16)
address_as_base36 = baseN(address_as_integer, 36)
padded = pad_left_hex(address_as_base36, 15)
return Iban.fromBban(padded.upper()) | [
"def",
"fromAddress",
"(",
"address",
")",
":",
"validate_address",
"(",
"address",
")",
"address_as_integer",
"=",
"int",
"(",
"address",
",",
"16",
")",
"address_as_base36",
"=",
"baseN",
"(",
"address_as_integer",
",",
"36",
")",
"padded",
"=",
"pad_left_he... | This method should be used to create
an iban object from ethereum address
@method fromAddress
@param {String} address
@return {Iban} the IBAN object | [
"This",
"method",
"should",
"be",
"used",
"to",
"create",
"an",
"iban",
"object",
"from",
"ethereum",
"address"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/iban.py#L105-L118 | train | 220,302 |
ethereum/web3.py | web3/iban.py | Iban.address | def address(self):
"""
Should be called to get client direct address
@method address
@returns {String} client direct address
"""
if self.isDirect():
base36 = self._iban[4:]
asInt = int(base36, 36)
return to_checksum_address(pad_left_hex(baseN(asInt, 16), 20))
return "" | python | def address(self):
"""
Should be called to get client direct address
@method address
@returns {String} client direct address
"""
if self.isDirect():
base36 = self._iban[4:]
asInt = int(base36, 36)
return to_checksum_address(pad_left_hex(baseN(asInt, 16), 20))
return "" | [
"def",
"address",
"(",
"self",
")",
":",
"if",
"self",
".",
"isDirect",
"(",
")",
":",
"base36",
"=",
"self",
".",
"_iban",
"[",
"4",
":",
"]",
"asInt",
"=",
"int",
"(",
"base36",
",",
"36",
")",
"return",
"to_checksum_address",
"(",
"pad_left_hex",
... | Should be called to get client direct address
@method address
@returns {String} client direct address | [
"Should",
"be",
"called",
"to",
"get",
"client",
"direct",
"address"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/iban.py#L207-L219 | train | 220,303 |
ethereum/web3.py | web3/middleware/filter.py | block_ranges | def block_ranges(start_block, last_block, step=5):
"""Returns 2-tuple ranges describing ranges of block from start_block to last_block
Ranges do not overlap to facilitate use as ``toBlock``, ``fromBlock``
json-rpc arguments, which are both inclusive.
"""
if last_block is not None and start_block > last_block:
raise TypeError(
"Incompatible start and stop arguments.",
"Start must be less than or equal to stop.")
return (
(from_block, to_block - 1)
for from_block, to_block
in segment_count(start_block, last_block + 1, step)
) | python | def block_ranges(start_block, last_block, step=5):
"""Returns 2-tuple ranges describing ranges of block from start_block to last_block
Ranges do not overlap to facilitate use as ``toBlock``, ``fromBlock``
json-rpc arguments, which are both inclusive.
"""
if last_block is not None and start_block > last_block:
raise TypeError(
"Incompatible start and stop arguments.",
"Start must be less than or equal to stop.")
return (
(from_block, to_block - 1)
for from_block, to_block
in segment_count(start_block, last_block + 1, step)
) | [
"def",
"block_ranges",
"(",
"start_block",
",",
"last_block",
",",
"step",
"=",
"5",
")",
":",
"if",
"last_block",
"is",
"not",
"None",
"and",
"start_block",
">",
"last_block",
":",
"raise",
"TypeError",
"(",
"\"Incompatible start and stop arguments.\"",
",",
"\... | Returns 2-tuple ranges describing ranges of block from start_block to last_block
Ranges do not overlap to facilitate use as ``toBlock``, ``fromBlock``
json-rpc arguments, which are both inclusive. | [
"Returns",
"2",
"-",
"tuple",
"ranges",
"describing",
"ranges",
"of",
"block",
"from",
"start_block",
"to",
"last_block"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/filter.py#L68-L84 | train | 220,304 |
ethereum/web3.py | web3/middleware/filter.py | get_logs_multipart | def get_logs_multipart(
w3,
startBlock,
stopBlock,
address,
topics,
max_blocks):
"""Used to break up requests to ``eth_getLogs``
The getLog request is partitioned into multiple calls of the max number of blocks
``max_blocks``.
"""
_block_ranges = block_ranges(startBlock, stopBlock, max_blocks)
for from_block, to_block in _block_ranges:
params = {
'fromBlock': from_block,
'toBlock': to_block,
'address': address,
'topics': topics
}
yield w3.eth.getLogs(
drop_items_with_none_value(params)) | python | def get_logs_multipart(
w3,
startBlock,
stopBlock,
address,
topics,
max_blocks):
"""Used to break up requests to ``eth_getLogs``
The getLog request is partitioned into multiple calls of the max number of blocks
``max_blocks``.
"""
_block_ranges = block_ranges(startBlock, stopBlock, max_blocks)
for from_block, to_block in _block_ranges:
params = {
'fromBlock': from_block,
'toBlock': to_block,
'address': address,
'topics': topics
}
yield w3.eth.getLogs(
drop_items_with_none_value(params)) | [
"def",
"get_logs_multipart",
"(",
"w3",
",",
"startBlock",
",",
"stopBlock",
",",
"address",
",",
"topics",
",",
"max_blocks",
")",
":",
"_block_ranges",
"=",
"block_ranges",
"(",
"startBlock",
",",
"stopBlock",
",",
"max_blocks",
")",
"for",
"from_block",
","... | Used to break up requests to ``eth_getLogs``
The getLog request is partitioned into multiple calls of the max number of blocks
``max_blocks``. | [
"Used",
"to",
"break",
"up",
"requests",
"to",
"eth_getLogs"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/filter.py#L158-L179 | train | 220,305 |
ethereum/web3.py | web3/method.py | Method.method_selector_fn | def method_selector_fn(self):
"""Gets the method selector from the config.
"""
if callable(self.json_rpc_method):
return self.json_rpc_method
elif isinstance(self.json_rpc_method, (str,)):
return lambda *_: self.json_rpc_method
raise ValueError("``json_rpc_method`` config invalid. May be a string or function") | python | def method_selector_fn(self):
"""Gets the method selector from the config.
"""
if callable(self.json_rpc_method):
return self.json_rpc_method
elif isinstance(self.json_rpc_method, (str,)):
return lambda *_: self.json_rpc_method
raise ValueError("``json_rpc_method`` config invalid. May be a string or function") | [
"def",
"method_selector_fn",
"(",
"self",
")",
":",
"if",
"callable",
"(",
"self",
".",
"json_rpc_method",
")",
":",
"return",
"self",
".",
"json_rpc_method",
"elif",
"isinstance",
"(",
"self",
".",
"json_rpc_method",
",",
"(",
"str",
",",
")",
")",
":",
... | Gets the method selector from the config. | [
"Gets",
"the",
"method",
"selector",
"from",
"the",
"config",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/method.py#L97-L104 | train | 220,306 |
ethereum/web3.py | web3/_utils/encoding.py | hex_encode_abi_type | def hex_encode_abi_type(abi_type, value, force_size=None):
"""
Encodes value into a hex string in format of abi_type
"""
validate_abi_type(abi_type)
validate_abi_value(abi_type, value)
data_size = force_size or size_of_type(abi_type)
if is_array_type(abi_type):
sub_type = sub_type_of_array_type(abi_type)
return "".join([remove_0x_prefix(hex_encode_abi_type(sub_type, v, 256)) for v in value])
elif is_bool_type(abi_type):
return to_hex_with_size(value, data_size)
elif is_uint_type(abi_type):
return to_hex_with_size(value, data_size)
elif is_int_type(abi_type):
return to_hex_twos_compliment(value, data_size)
elif is_address_type(abi_type):
return pad_hex(value, data_size)
elif is_bytes_type(abi_type):
if is_bytes(value):
return encode_hex(value)
else:
return value
elif is_string_type(abi_type):
return to_hex(text=value)
else:
raise ValueError(
"Unsupported ABI type: {0}".format(abi_type)
) | python | def hex_encode_abi_type(abi_type, value, force_size=None):
"""
Encodes value into a hex string in format of abi_type
"""
validate_abi_type(abi_type)
validate_abi_value(abi_type, value)
data_size = force_size or size_of_type(abi_type)
if is_array_type(abi_type):
sub_type = sub_type_of_array_type(abi_type)
return "".join([remove_0x_prefix(hex_encode_abi_type(sub_type, v, 256)) for v in value])
elif is_bool_type(abi_type):
return to_hex_with_size(value, data_size)
elif is_uint_type(abi_type):
return to_hex_with_size(value, data_size)
elif is_int_type(abi_type):
return to_hex_twos_compliment(value, data_size)
elif is_address_type(abi_type):
return pad_hex(value, data_size)
elif is_bytes_type(abi_type):
if is_bytes(value):
return encode_hex(value)
else:
return value
elif is_string_type(abi_type):
return to_hex(text=value)
else:
raise ValueError(
"Unsupported ABI type: {0}".format(abi_type)
) | [
"def",
"hex_encode_abi_type",
"(",
"abi_type",
",",
"value",
",",
"force_size",
"=",
"None",
")",
":",
"validate_abi_type",
"(",
"abi_type",
")",
"validate_abi_value",
"(",
"abi_type",
",",
"value",
")",
"data_size",
"=",
"force_size",
"or",
"size_of_type",
"(",... | Encodes value into a hex string in format of abi_type | [
"Encodes",
"value",
"into",
"a",
"hex",
"string",
"in",
"format",
"of",
"abi_type"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/encoding.py#L50-L79 | train | 220,307 |
ethereum/web3.py | web3/_utils/encoding.py | to_hex_twos_compliment | def to_hex_twos_compliment(value, bit_size):
"""
Converts integer value to twos compliment hex representation with given bit_size
"""
if value >= 0:
return to_hex_with_size(value, bit_size)
value = (1 << bit_size) + value
hex_value = hex(value)
hex_value = hex_value.rstrip("L")
return hex_value | python | def to_hex_twos_compliment(value, bit_size):
"""
Converts integer value to twos compliment hex representation with given bit_size
"""
if value >= 0:
return to_hex_with_size(value, bit_size)
value = (1 << bit_size) + value
hex_value = hex(value)
hex_value = hex_value.rstrip("L")
return hex_value | [
"def",
"to_hex_twos_compliment",
"(",
"value",
",",
"bit_size",
")",
":",
"if",
"value",
">=",
"0",
":",
"return",
"to_hex_with_size",
"(",
"value",
",",
"bit_size",
")",
"value",
"=",
"(",
"1",
"<<",
"bit_size",
")",
"+",
"value",
"hex_value",
"=",
"hex... | Converts integer value to twos compliment hex representation with given bit_size | [
"Converts",
"integer",
"value",
"to",
"twos",
"compliment",
"hex",
"representation",
"with",
"given",
"bit_size"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/encoding.py#L82-L92 | train | 220,308 |
ethereum/web3.py | web3/_utils/encoding.py | pad_hex | def pad_hex(value, bit_size):
"""
Pads a hex string up to the given bit_size
"""
value = remove_0x_prefix(value)
return add_0x_prefix(value.zfill(int(bit_size / 4))) | python | def pad_hex(value, bit_size):
"""
Pads a hex string up to the given bit_size
"""
value = remove_0x_prefix(value)
return add_0x_prefix(value.zfill(int(bit_size / 4))) | [
"def",
"pad_hex",
"(",
"value",
",",
"bit_size",
")",
":",
"value",
"=",
"remove_0x_prefix",
"(",
"value",
")",
"return",
"add_0x_prefix",
"(",
"value",
".",
"zfill",
"(",
"int",
"(",
"bit_size",
"/",
"4",
")",
")",
")"
] | Pads a hex string up to the given bit_size | [
"Pads",
"a",
"hex",
"string",
"up",
"to",
"the",
"given",
"bit_size"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/encoding.py#L102-L107 | train | 220,309 |
ethereum/web3.py | web3/_utils/encoding.py | to_int | def to_int(value=None, hexstr=None, text=None):
"""
Converts value to it's integer representation.
Values are converted this way:
* value:
* bytes: big-endian integer
* bool: True => 1, False => 0
* hexstr: interpret hex as integer
* text: interpret as string of digits, like '12' => 12
"""
assert_one_val(value, hexstr=hexstr, text=text)
if hexstr is not None:
return int(hexstr, 16)
elif text is not None:
return int(text)
elif isinstance(value, bytes):
return big_endian_to_int(value)
elif isinstance(value, str):
raise TypeError("Pass in strings with keyword hexstr or text")
else:
return int(value) | python | def to_int(value=None, hexstr=None, text=None):
"""
Converts value to it's integer representation.
Values are converted this way:
* value:
* bytes: big-endian integer
* bool: True => 1, False => 0
* hexstr: interpret hex as integer
* text: interpret as string of digits, like '12' => 12
"""
assert_one_val(value, hexstr=hexstr, text=text)
if hexstr is not None:
return int(hexstr, 16)
elif text is not None:
return int(text)
elif isinstance(value, bytes):
return big_endian_to_int(value)
elif isinstance(value, str):
raise TypeError("Pass in strings with keyword hexstr or text")
else:
return int(value) | [
"def",
"to_int",
"(",
"value",
"=",
"None",
",",
"hexstr",
"=",
"None",
",",
"text",
"=",
"None",
")",
":",
"assert_one_val",
"(",
"value",
",",
"hexstr",
"=",
"hexstr",
",",
"text",
"=",
"text",
")",
"if",
"hexstr",
"is",
"not",
"None",
":",
"retu... | Converts value to it's integer representation.
Values are converted this way:
* value:
* bytes: big-endian integer
* bool: True => 1, False => 0
* hexstr: interpret hex as integer
* text: interpret as string of digits, like '12' => 12 | [
"Converts",
"value",
"to",
"it",
"s",
"integer",
"representation",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/encoding.py#L118-L141 | train | 220,310 |
ethereum/web3.py | web3/pm.py | VyperReferenceRegistry.deploy_new_instance | def deploy_new_instance(cls, w3: Web3) -> "VyperReferenceRegistry":
"""
Returns a new instance of ```VyperReferenceRegistry`` representing a freshly deployed
instance on the given ``web3`` instance of the Vyper Reference Registry implementation.
"""
manifest = get_vyper_registry_manifest()
registry_package = Package(manifest, w3)
registry_factory = registry_package.get_contract_factory("registry")
tx_hash = registry_factory.constructor().transact()
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
registry_address = to_canonical_address(tx_receipt.contractAddress)
return cls(registry_address, w3) | python | def deploy_new_instance(cls, w3: Web3) -> "VyperReferenceRegistry":
"""
Returns a new instance of ```VyperReferenceRegistry`` representing a freshly deployed
instance on the given ``web3`` instance of the Vyper Reference Registry implementation.
"""
manifest = get_vyper_registry_manifest()
registry_package = Package(manifest, w3)
registry_factory = registry_package.get_contract_factory("registry")
tx_hash = registry_factory.constructor().transact()
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
registry_address = to_canonical_address(tx_receipt.contractAddress)
return cls(registry_address, w3) | [
"def",
"deploy_new_instance",
"(",
"cls",
",",
"w3",
":",
"Web3",
")",
"->",
"\"VyperReferenceRegistry\"",
":",
"manifest",
"=",
"get_vyper_registry_manifest",
"(",
")",
"registry_package",
"=",
"Package",
"(",
"manifest",
",",
"w3",
")",
"registry_factory",
"=",
... | Returns a new instance of ```VyperReferenceRegistry`` representing a freshly deployed
instance on the given ``web3`` instance of the Vyper Reference Registry implementation. | [
"Returns",
"a",
"new",
"instance",
"of",
"VyperReferenceRegistry",
"representing",
"a",
"freshly",
"deployed",
"instance",
"on",
"the",
"given",
"web3",
"instance",
"of",
"the",
"Vyper",
"Reference",
"Registry",
"implementation",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L230-L241 | train | 220,311 |
ethereum/web3.py | web3/pm.py | VyperReferenceRegistry.transfer_owner | def transfer_owner(self, new_owner: Address) -> TxReceipt:
"""
Transfers ownership of this registry instance to the given ``new_owner``. Only the
``owner`` is allowed to transfer ownership.
* Parameters:
* ``new_owner``: The address of the new owner.
"""
tx_hash = self.registry.functions.transferOwner(new_owner).transact()
return self.w3.eth.waitForTransactionReceipt(tx_hash) | python | def transfer_owner(self, new_owner: Address) -> TxReceipt:
"""
Transfers ownership of this registry instance to the given ``new_owner``. Only the
``owner`` is allowed to transfer ownership.
* Parameters:
* ``new_owner``: The address of the new owner.
"""
tx_hash = self.registry.functions.transferOwner(new_owner).transact()
return self.w3.eth.waitForTransactionReceipt(tx_hash) | [
"def",
"transfer_owner",
"(",
"self",
",",
"new_owner",
":",
"Address",
")",
"->",
"TxReceipt",
":",
"tx_hash",
"=",
"self",
".",
"registry",
".",
"functions",
".",
"transferOwner",
"(",
"new_owner",
")",
".",
"transact",
"(",
")",
"return",
"self",
".",
... | Transfers ownership of this registry instance to the given ``new_owner``. Only the
``owner`` is allowed to transfer ownership.
* Parameters:
* ``new_owner``: The address of the new owner. | [
"Transfers",
"ownership",
"of",
"this",
"registry",
"instance",
"to",
"the",
"given",
"new_owner",
".",
"Only",
"the",
"owner",
"is",
"allowed",
"to",
"transfer",
"ownership",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L311-L320 | train | 220,312 |
ethereum/web3.py | web3/pm.py | PM.release_package | def release_package(
self, package_name: str, version: str, manifest_uri: str
) -> bytes:
"""
Returns the release id generated by releasing a package on the current registry.
Requires ``web3.PM`` to have a registry set. Requires ``web3.eth.defaultAccount``
to be the registry owner.
* Parameters:
* ``package_name``: Must be a valid package name, matching the given manifest.
* ``version``: Must be a valid package version, matching the given manifest.
* ``manifest_uri``: Must be a valid content-addressed URI. Currently, only IPFS
and Github content-addressed URIs are supported.
"""
validate_is_supported_manifest_uri(manifest_uri)
raw_manifest = to_text(resolve_uri_contents(manifest_uri))
validate_raw_manifest_format(raw_manifest)
manifest = json.loads(raw_manifest)
validate_manifest_against_schema(manifest)
if package_name != manifest['package_name']:
raise ManifestValidationError(
f"Provided package name: {package_name} does not match the package name "
f"found in the manifest: {manifest['package_name']}."
)
if version != manifest['version']:
raise ManifestValidationError(
f"Provided package version: {version} does not match the package version "
f"found in the manifest: {manifest['version']}."
)
self._validate_set_registry()
return self.registry._release(package_name, version, manifest_uri) | python | def release_package(
self, package_name: str, version: str, manifest_uri: str
) -> bytes:
"""
Returns the release id generated by releasing a package on the current registry.
Requires ``web3.PM`` to have a registry set. Requires ``web3.eth.defaultAccount``
to be the registry owner.
* Parameters:
* ``package_name``: Must be a valid package name, matching the given manifest.
* ``version``: Must be a valid package version, matching the given manifest.
* ``manifest_uri``: Must be a valid content-addressed URI. Currently, only IPFS
and Github content-addressed URIs are supported.
"""
validate_is_supported_manifest_uri(manifest_uri)
raw_manifest = to_text(resolve_uri_contents(manifest_uri))
validate_raw_manifest_format(raw_manifest)
manifest = json.loads(raw_manifest)
validate_manifest_against_schema(manifest)
if package_name != manifest['package_name']:
raise ManifestValidationError(
f"Provided package name: {package_name} does not match the package name "
f"found in the manifest: {manifest['package_name']}."
)
if version != manifest['version']:
raise ManifestValidationError(
f"Provided package version: {version} does not match the package version "
f"found in the manifest: {manifest['version']}."
)
self._validate_set_registry()
return self.registry._release(package_name, version, manifest_uri) | [
"def",
"release_package",
"(",
"self",
",",
"package_name",
":",
"str",
",",
"version",
":",
"str",
",",
"manifest_uri",
":",
"str",
")",
"->",
"bytes",
":",
"validate_is_supported_manifest_uri",
"(",
"manifest_uri",
")",
"raw_manifest",
"=",
"to_text",
"(",
"... | Returns the release id generated by releasing a package on the current registry.
Requires ``web3.PM`` to have a registry set. Requires ``web3.eth.defaultAccount``
to be the registry owner.
* Parameters:
* ``package_name``: Must be a valid package name, matching the given manifest.
* ``version``: Must be a valid package version, matching the given manifest.
* ``manifest_uri``: Must be a valid content-addressed URI. Currently, only IPFS
and Github content-addressed URIs are supported. | [
"Returns",
"the",
"release",
"id",
"generated",
"by",
"releasing",
"a",
"package",
"on",
"the",
"current",
"registry",
".",
"Requires",
"web3",
".",
"PM",
"to",
"have",
"a",
"registry",
"set",
".",
"Requires",
"web3",
".",
"eth",
".",
"defaultAccount",
"to... | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L471-L504 | train | 220,313 |
ethereum/web3.py | web3/pm.py | PM.get_all_package_names | def get_all_package_names(self) -> Iterable[str]:
"""
Returns a tuple containing all the package names available on the current registry.
"""
self._validate_set_registry()
package_ids = self.registry._get_all_package_ids()
for package_id in package_ids:
yield self.registry._get_package_name(package_id) | python | def get_all_package_names(self) -> Iterable[str]:
"""
Returns a tuple containing all the package names available on the current registry.
"""
self._validate_set_registry()
package_ids = self.registry._get_all_package_ids()
for package_id in package_ids:
yield self.registry._get_package_name(package_id) | [
"def",
"get_all_package_names",
"(",
"self",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"self",
".",
"_validate_set_registry",
"(",
")",
"package_ids",
"=",
"self",
".",
"registry",
".",
"_get_all_package_ids",
"(",
")",
"for",
"package_id",
"in",
"package_i... | Returns a tuple containing all the package names available on the current registry. | [
"Returns",
"a",
"tuple",
"containing",
"all",
"the",
"package",
"names",
"available",
"on",
"the",
"current",
"registry",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L507-L514 | train | 220,314 |
ethereum/web3.py | web3/pm.py | PM.get_release_count | def get_release_count(self, package_name: str) -> int:
"""
Returns the number of releases of the given package name available on the current registry.
"""
validate_package_name(package_name)
self._validate_set_registry()
return self.registry._num_release_ids(package_name) | python | def get_release_count(self, package_name: str) -> int:
"""
Returns the number of releases of the given package name available on the current registry.
"""
validate_package_name(package_name)
self._validate_set_registry()
return self.registry._num_release_ids(package_name) | [
"def",
"get_release_count",
"(",
"self",
",",
"package_name",
":",
"str",
")",
"->",
"int",
":",
"validate_package_name",
"(",
"package_name",
")",
"self",
".",
"_validate_set_registry",
"(",
")",
"return",
"self",
".",
"registry",
".",
"_num_release_ids",
"(",
... | Returns the number of releases of the given package name available on the current registry. | [
"Returns",
"the",
"number",
"of",
"releases",
"of",
"the",
"given",
"package",
"name",
"available",
"on",
"the",
"current",
"registry",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L523-L529 | train | 220,315 |
ethereum/web3.py | web3/pm.py | PM.get_release_id | def get_release_id(self, package_name: str, version: str) -> bytes:
"""
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
"""
validate_package_name(package_name)
validate_package_version(version)
self._validate_set_registry()
return self.registry._get_release_id(package_name, version) | python | def get_release_id(self, package_name: str, version: str) -> bytes:
"""
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
"""
validate_package_name(package_name)
validate_package_version(version)
self._validate_set_registry()
return self.registry._get_release_id(package_name, version) | [
"def",
"get_release_id",
"(",
"self",
",",
"package_name",
":",
"str",
",",
"version",
":",
"str",
")",
"->",
"bytes",
":",
"validate_package_name",
"(",
"package_name",
")",
"validate_package_version",
"(",
"version",
")",
"self",
".",
"_validate_set_registry",
... | Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry. | [
"Returns",
"the",
"32",
"byte",
"identifier",
"of",
"a",
"release",
"for",
"the",
"given",
"package",
"name",
"and",
"version",
"if",
"they",
"are",
"available",
"on",
"the",
"current",
"registry",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L531-L539 | train | 220,316 |
ethereum/web3.py | web3/pm.py | PM.get_package | def get_package(self, package_name: str, version: str) -> Package:
"""
Returns a ``Package`` instance, generated by the ``manifest_uri`` associated with the
given package name and version, if they are published to the currently set registry.
* Parameters:
* ``name``: Must be a valid package name.
* ``version``: Must be a valid package version.
"""
validate_package_name(package_name)
validate_package_version(version)
self._validate_set_registry()
_, _, release_uri = self.get_release_data(package_name, version)
return self.get_package_from_uri(release_uri) | python | def get_package(self, package_name: str, version: str) -> Package:
"""
Returns a ``Package`` instance, generated by the ``manifest_uri`` associated with the
given package name and version, if they are published to the currently set registry.
* Parameters:
* ``name``: Must be a valid package name.
* ``version``: Must be a valid package version.
"""
validate_package_name(package_name)
validate_package_version(version)
self._validate_set_registry()
_, _, release_uri = self.get_release_data(package_name, version)
return self.get_package_from_uri(release_uri) | [
"def",
"get_package",
"(",
"self",
",",
"package_name",
":",
"str",
",",
"version",
":",
"str",
")",
"->",
"Package",
":",
"validate_package_name",
"(",
"package_name",
")",
"validate_package_version",
"(",
"version",
")",
"self",
".",
"_validate_set_registry",
... | Returns a ``Package`` instance, generated by the ``manifest_uri`` associated with the
given package name and version, if they are published to the currently set registry.
* Parameters:
* ``name``: Must be a valid package name.
* ``version``: Must be a valid package version. | [
"Returns",
"a",
"Package",
"instance",
"generated",
"by",
"the",
"manifest_uri",
"associated",
"with",
"the",
"given",
"package",
"name",
"and",
"version",
"if",
"they",
"are",
"published",
"to",
"the",
"currently",
"set",
"registry",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L580-L593 | train | 220,317 |
ethereum/web3.py | web3/_utils/filters.py | normalize_data_values | def normalize_data_values(type_string, data_value):
"""Decodes utf-8 bytes to strings for abi string values.
eth-abi v1 returns utf-8 bytes for string values.
This can be removed once eth-abi v2 is required.
"""
_type = parse_type_string(type_string)
if _type.base == "string":
if _type.arrlist is not None:
return tuple((normalize_to_text(value) for value in data_value))
else:
return normalize_to_text(data_value)
return data_value | python | def normalize_data_values(type_string, data_value):
"""Decodes utf-8 bytes to strings for abi string values.
eth-abi v1 returns utf-8 bytes for string values.
This can be removed once eth-abi v2 is required.
"""
_type = parse_type_string(type_string)
if _type.base == "string":
if _type.arrlist is not None:
return tuple((normalize_to_text(value) for value in data_value))
else:
return normalize_to_text(data_value)
return data_value | [
"def",
"normalize_data_values",
"(",
"type_string",
",",
"data_value",
")",
":",
"_type",
"=",
"parse_type_string",
"(",
"type_string",
")",
"if",
"_type",
".",
"base",
"==",
"\"string\"",
":",
"if",
"_type",
".",
"arrlist",
"is",
"not",
"None",
":",
"return... | Decodes utf-8 bytes to strings for abi string values.
eth-abi v1 returns utf-8 bytes for string values.
This can be removed once eth-abi v2 is required. | [
"Decodes",
"utf",
"-",
"8",
"bytes",
"to",
"strings",
"for",
"abi",
"string",
"values",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/filters.py#L192-L204 | train | 220,318 |
ethereum/web3.py | web3/_utils/filters.py | match_fn | def match_fn(match_values_and_abi, data):
"""Match function used for filtering non-indexed event arguments.
Values provided through the match_values_and_abi parameter are
compared to the abi decoded log data.
"""
abi_types, all_match_values = zip(*match_values_and_abi)
decoded_values = decode_abi(abi_types, HexBytes(data))
for data_value, match_values, abi_type in zip(decoded_values, all_match_values, abi_types):
if match_values is None:
continue
normalized_data = normalize_data_values(abi_type, data_value)
for value in match_values:
if not is_encodable(abi_type, value):
raise ValueError(
"Value {0} is of the wrong abi type. "
"Expected {1} typed value.".format(value, abi_type))
if value == normalized_data:
break
else:
return False
return True | python | def match_fn(match_values_and_abi, data):
"""Match function used for filtering non-indexed event arguments.
Values provided through the match_values_and_abi parameter are
compared to the abi decoded log data.
"""
abi_types, all_match_values = zip(*match_values_and_abi)
decoded_values = decode_abi(abi_types, HexBytes(data))
for data_value, match_values, abi_type in zip(decoded_values, all_match_values, abi_types):
if match_values is None:
continue
normalized_data = normalize_data_values(abi_type, data_value)
for value in match_values:
if not is_encodable(abi_type, value):
raise ValueError(
"Value {0} is of the wrong abi type. "
"Expected {1} typed value.".format(value, abi_type))
if value == normalized_data:
break
else:
return False
return True | [
"def",
"match_fn",
"(",
"match_values_and_abi",
",",
"data",
")",
":",
"abi_types",
",",
"all_match_values",
"=",
"zip",
"(",
"*",
"match_values_and_abi",
")",
"decoded_values",
"=",
"decode_abi",
"(",
"abi_types",
",",
"HexBytes",
"(",
"data",
")",
")",
"for"... | Match function used for filtering non-indexed event arguments.
Values provided through the match_values_and_abi parameter are
compared to the abi decoded log data. | [
"Match",
"function",
"used",
"for",
"filtering",
"non",
"-",
"indexed",
"event",
"arguments",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/filters.py#L208-L230 | train | 220,319 |
ethereum/web3.py | web3/middleware/attrdict.py | attrdict_middleware | def attrdict_middleware(make_request, web3):
"""
Converts any result which is a dictionary into an a
"""
def middleware(method, params):
response = make_request(method, params)
if 'result' in response:
result = response['result']
if is_dict(result) and not isinstance(result, AttributeDict):
return assoc(response, 'result', AttributeDict.recursive(result))
else:
return response
else:
return response
return middleware | python | def attrdict_middleware(make_request, web3):
"""
Converts any result which is a dictionary into an a
"""
def middleware(method, params):
response = make_request(method, params)
if 'result' in response:
result = response['result']
if is_dict(result) and not isinstance(result, AttributeDict):
return assoc(response, 'result', AttributeDict.recursive(result))
else:
return response
else:
return response
return middleware | [
"def",
"attrdict_middleware",
"(",
"make_request",
",",
"web3",
")",
":",
"def",
"middleware",
"(",
"method",
",",
"params",
")",
":",
"response",
"=",
"make_request",
"(",
"method",
",",
"params",
")",
"if",
"'result'",
"in",
"response",
":",
"result",
"=... | Converts any result which is a dictionary into an a | [
"Converts",
"any",
"result",
"which",
"is",
"a",
"dictionary",
"into",
"an",
"a"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/attrdict.py#L13-L28 | train | 220,320 |
ethereum/web3.py | ens/main.py | ENS.fromWeb3 | def fromWeb3(cls, web3, addr=None):
"""
Generate an ENS instance with web3
:param `web3.Web3` web3: to infer connection information
:param hex-string addr: the address of the ENS registry on-chain. If not provided,
ENS.py will default to the mainnet ENS registry address.
"""
return cls(web3.manager.provider, addr=addr) | python | def fromWeb3(cls, web3, addr=None):
"""
Generate an ENS instance with web3
:param `web3.Web3` web3: to infer connection information
:param hex-string addr: the address of the ENS registry on-chain. If not provided,
ENS.py will default to the mainnet ENS registry address.
"""
return cls(web3.manager.provider, addr=addr) | [
"def",
"fromWeb3",
"(",
"cls",
",",
"web3",
",",
"addr",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"web3",
".",
"manager",
".",
"provider",
",",
"addr",
"=",
"addr",
")"
] | Generate an ENS instance with web3
:param `web3.Web3` web3: to infer connection information
:param hex-string addr: the address of the ENS registry on-chain. If not provided,
ENS.py will default to the mainnet ENS registry address. | [
"Generate",
"an",
"ENS",
"instance",
"with",
"web3"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/main.py#L65-L73 | train | 220,321 |
ethereum/web3.py | ens/main.py | ENS.name | def name(self, address):
"""
Look up the name that the address points to, using a
reverse lookup. Reverse lookup is opt-in for name owners.
:param address:
:type address: hex-string
"""
reversed_domain = address_to_reverse_domain(address)
return self.resolve(reversed_domain, get='name') | python | def name(self, address):
"""
Look up the name that the address points to, using a
reverse lookup. Reverse lookup is opt-in for name owners.
:param address:
:type address: hex-string
"""
reversed_domain = address_to_reverse_domain(address)
return self.resolve(reversed_domain, get='name') | [
"def",
"name",
"(",
"self",
",",
"address",
")",
":",
"reversed_domain",
"=",
"address_to_reverse_domain",
"(",
"address",
")",
"return",
"self",
".",
"resolve",
"(",
"reversed_domain",
",",
"get",
"=",
"'name'",
")"
] | Look up the name that the address points to, using a
reverse lookup. Reverse lookup is opt-in for name owners.
:param address:
:type address: hex-string | [
"Look",
"up",
"the",
"name",
"that",
"the",
"address",
"points",
"to",
"using",
"a",
"reverse",
"lookup",
".",
"Reverse",
"lookup",
"is",
"opt",
"-",
"in",
"for",
"name",
"owners",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/main.py#L84-L93 | train | 220,322 |
ethereum/web3.py | ens/main.py | ENS.setup_address | def setup_address(self, name, address=default, transact={}):
"""
Set up the name to point to the supplied address.
The sender of the transaction must own the name, or
its parent name.
Example: If the caller owns ``parentname.eth`` with no subdomains
and calls this method with ``sub.parentname.eth``,
then ``sub`` will be created as part of this call.
:param str name: ENS name to set up
:param str address: name will point to this address, in checksum format. If ``None``,
erase the record. If not specified, name will point to the owner's address.
:param dict transact: the transaction configuration, like in
:meth:`~web3.eth.Eth.sendTransaction`
:raises InvalidName: if ``name`` has invalid syntax
:raises UnauthorizedError: if ``'from'`` in `transact` does not own `name`
"""
owner = self.setup_owner(name, transact=transact)
self._assert_control(owner, name)
if is_none_or_zero_address(address):
address = None
elif address is default:
address = owner
elif is_binary_address(address):
address = to_checksum_address(address)
elif not is_checksum_address(address):
raise ValueError("You must supply the address in checksum format")
if self.address(name) == address:
return None
if address is None:
address = EMPTY_ADDR_HEX
transact['from'] = owner
resolver = self._set_resolver(name, transact=transact)
return resolver.functions.setAddr(raw_name_to_hash(name), address).transact(transact) | python | def setup_address(self, name, address=default, transact={}):
"""
Set up the name to point to the supplied address.
The sender of the transaction must own the name, or
its parent name.
Example: If the caller owns ``parentname.eth`` with no subdomains
and calls this method with ``sub.parentname.eth``,
then ``sub`` will be created as part of this call.
:param str name: ENS name to set up
:param str address: name will point to this address, in checksum format. If ``None``,
erase the record. If not specified, name will point to the owner's address.
:param dict transact: the transaction configuration, like in
:meth:`~web3.eth.Eth.sendTransaction`
:raises InvalidName: if ``name`` has invalid syntax
:raises UnauthorizedError: if ``'from'`` in `transact` does not own `name`
"""
owner = self.setup_owner(name, transact=transact)
self._assert_control(owner, name)
if is_none_or_zero_address(address):
address = None
elif address is default:
address = owner
elif is_binary_address(address):
address = to_checksum_address(address)
elif not is_checksum_address(address):
raise ValueError("You must supply the address in checksum format")
if self.address(name) == address:
return None
if address is None:
address = EMPTY_ADDR_HEX
transact['from'] = owner
resolver = self._set_resolver(name, transact=transact)
return resolver.functions.setAddr(raw_name_to_hash(name), address).transact(transact) | [
"def",
"setup_address",
"(",
"self",
",",
"name",
",",
"address",
"=",
"default",
",",
"transact",
"=",
"{",
"}",
")",
":",
"owner",
"=",
"self",
".",
"setup_owner",
"(",
"name",
",",
"transact",
"=",
"transact",
")",
"self",
".",
"_assert_control",
"(... | Set up the name to point to the supplied address.
The sender of the transaction must own the name, or
its parent name.
Example: If the caller owns ``parentname.eth`` with no subdomains
and calls this method with ``sub.parentname.eth``,
then ``sub`` will be created as part of this call.
:param str name: ENS name to set up
:param str address: name will point to this address, in checksum format. If ``None``,
erase the record. If not specified, name will point to the owner's address.
:param dict transact: the transaction configuration, like in
:meth:`~web3.eth.Eth.sendTransaction`
:raises InvalidName: if ``name`` has invalid syntax
:raises UnauthorizedError: if ``'from'`` in `transact` does not own `name` | [
"Set",
"up",
"the",
"name",
"to",
"point",
"to",
"the",
"supplied",
"address",
".",
"The",
"sender",
"of",
"the",
"transaction",
"must",
"own",
"the",
"name",
"or",
"its",
"parent",
"name",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/main.py#L96-L130 | train | 220,323 |
ethereum/web3.py | ens/main.py | ENS.setup_owner | def setup_owner(self, name, new_owner=default, transact={}):
"""
Set the owner of the supplied name to `new_owner`.
For typical scenarios, you'll never need to call this method directly,
simply call :meth:`setup_name` or :meth:`setup_address`. This method does *not*
set up the name to point to an address.
If `new_owner` is not supplied, then this will assume you
want the same owner as the parent domain.
If the caller owns ``parentname.eth`` with no subdomains
and calls this method with ``sub.parentname.eth``,
then ``sub`` will be created as part of this call.
:param str name: ENS name to set up
:param new_owner: account that will own `name`. If ``None``, set owner to empty addr.
If not specified, name will point to the parent domain owner's address.
:param dict transact: the transaction configuration, like in
:meth:`~web3.eth.Eth.sendTransaction`
:raises InvalidName: if `name` has invalid syntax
:raises UnauthorizedError: if ``'from'`` in `transact` does not own `name`
:returns: the new owner's address
"""
(super_owner, unowned, owned) = self._first_owner(name)
if new_owner is default:
new_owner = super_owner
elif not new_owner:
new_owner = EMPTY_ADDR_HEX
else:
new_owner = to_checksum_address(new_owner)
current_owner = self.owner(name)
if new_owner == EMPTY_ADDR_HEX and not current_owner:
return None
elif current_owner == new_owner:
return current_owner
else:
self._assert_control(super_owner, name, owned)
self._claim_ownership(new_owner, unowned, owned, super_owner, transact=transact)
return new_owner | python | def setup_owner(self, name, new_owner=default, transact={}):
"""
Set the owner of the supplied name to `new_owner`.
For typical scenarios, you'll never need to call this method directly,
simply call :meth:`setup_name` or :meth:`setup_address`. This method does *not*
set up the name to point to an address.
If `new_owner` is not supplied, then this will assume you
want the same owner as the parent domain.
If the caller owns ``parentname.eth`` with no subdomains
and calls this method with ``sub.parentname.eth``,
then ``sub`` will be created as part of this call.
:param str name: ENS name to set up
:param new_owner: account that will own `name`. If ``None``, set owner to empty addr.
If not specified, name will point to the parent domain owner's address.
:param dict transact: the transaction configuration, like in
:meth:`~web3.eth.Eth.sendTransaction`
:raises InvalidName: if `name` has invalid syntax
:raises UnauthorizedError: if ``'from'`` in `transact` does not own `name`
:returns: the new owner's address
"""
(super_owner, unowned, owned) = self._first_owner(name)
if new_owner is default:
new_owner = super_owner
elif not new_owner:
new_owner = EMPTY_ADDR_HEX
else:
new_owner = to_checksum_address(new_owner)
current_owner = self.owner(name)
if new_owner == EMPTY_ADDR_HEX and not current_owner:
return None
elif current_owner == new_owner:
return current_owner
else:
self._assert_control(super_owner, name, owned)
self._claim_ownership(new_owner, unowned, owned, super_owner, transact=transact)
return new_owner | [
"def",
"setup_owner",
"(",
"self",
",",
"name",
",",
"new_owner",
"=",
"default",
",",
"transact",
"=",
"{",
"}",
")",
":",
"(",
"super_owner",
",",
"unowned",
",",
"owned",
")",
"=",
"self",
".",
"_first_owner",
"(",
"name",
")",
"if",
"new_owner",
... | Set the owner of the supplied name to `new_owner`.
For typical scenarios, you'll never need to call this method directly,
simply call :meth:`setup_name` or :meth:`setup_address`. This method does *not*
set up the name to point to an address.
If `new_owner` is not supplied, then this will assume you
want the same owner as the parent domain.
If the caller owns ``parentname.eth`` with no subdomains
and calls this method with ``sub.parentname.eth``,
then ``sub`` will be created as part of this call.
:param str name: ENS name to set up
:param new_owner: account that will own `name`. If ``None``, set owner to empty addr.
If not specified, name will point to the parent domain owner's address.
:param dict transact: the transaction configuration, like in
:meth:`~web3.eth.Eth.sendTransaction`
:raises InvalidName: if `name` has invalid syntax
:raises UnauthorizedError: if ``'from'`` in `transact` does not own `name`
:returns: the new owner's address | [
"Set",
"the",
"owner",
"of",
"the",
"supplied",
"name",
"to",
"new_owner",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/main.py#L213-L252 | train | 220,324 |
ethereum/web3.py | ens/main.py | ENS._first_owner | def _first_owner(self, name):
"""
Takes a name, and returns the owner of the deepest subdomain that has an owner
:returns: (owner or None, list(unowned_subdomain_labels), first_owned_domain)
"""
owner = None
unowned = []
pieces = normalize_name(name).split('.')
while pieces and is_none_or_zero_address(owner):
name = '.'.join(pieces)
owner = self.owner(name)
if is_none_or_zero_address(owner):
unowned.append(pieces.pop(0))
return (owner, unowned, name) | python | def _first_owner(self, name):
"""
Takes a name, and returns the owner of the deepest subdomain that has an owner
:returns: (owner or None, list(unowned_subdomain_labels), first_owned_domain)
"""
owner = None
unowned = []
pieces = normalize_name(name).split('.')
while pieces and is_none_or_zero_address(owner):
name = '.'.join(pieces)
owner = self.owner(name)
if is_none_or_zero_address(owner):
unowned.append(pieces.pop(0))
return (owner, unowned, name) | [
"def",
"_first_owner",
"(",
"self",
",",
"name",
")",
":",
"owner",
"=",
"None",
"unowned",
"=",
"[",
"]",
"pieces",
"=",
"normalize_name",
"(",
"name",
")",
".",
"split",
"(",
"'.'",
")",
"while",
"pieces",
"and",
"is_none_or_zero_address",
"(",
"owner"... | Takes a name, and returns the owner of the deepest subdomain that has an owner
:returns: (owner or None, list(unowned_subdomain_labels), first_owned_domain) | [
"Takes",
"a",
"name",
"and",
"returns",
"the",
"owner",
"of",
"the",
"deepest",
"subdomain",
"that",
"has",
"an",
"owner"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/main.py#L262-L276 | train | 220,325 |
ethereum/web3.py | web3/contract.py | call_contract_function | def call_contract_function(
web3,
address,
normalizers,
function_identifier,
transaction,
block_id=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""
Helper function for interacting with a contract function using the
`eth_call` API.
"""
call_transaction = prepare_transaction(
address,
web3,
fn_identifier=function_identifier,
contract_abi=contract_abi,
fn_abi=fn_abi,
transaction=transaction,
fn_args=args,
fn_kwargs=kwargs,
)
if block_id is None:
return_data = web3.eth.call(call_transaction)
else:
return_data = web3.eth.call(call_transaction, block_identifier=block_id)
if fn_abi is None:
fn_abi = find_matching_fn_abi(contract_abi, function_identifier, args, kwargs)
output_types = get_abi_output_types(fn_abi)
try:
output_data = decode_abi(output_types, return_data)
except DecodingError as e:
# Provide a more helpful error message than the one provided by
# eth-abi-utils
is_missing_code_error = (
return_data in ACCEPTABLE_EMPTY_STRINGS and
web3.eth.getCode(address) in ACCEPTABLE_EMPTY_STRINGS
)
if is_missing_code_error:
msg = (
"Could not transact with/call contract function, is contract "
"deployed correctly and chain synced?"
)
else:
msg = (
"Could not decode contract function call {} return data {} for "
"output_types {}".format(
function_identifier,
return_data,
output_types
)
)
raise BadFunctionCallOutput(msg) from e
_normalizers = itertools.chain(
BASE_RETURN_NORMALIZERS,
normalizers,
)
normalized_data = map_abi_data(_normalizers, output_types, output_data)
if len(normalized_data) == 1:
return normalized_data[0]
else:
return normalized_data | python | def call_contract_function(
web3,
address,
normalizers,
function_identifier,
transaction,
block_id=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""
Helper function for interacting with a contract function using the
`eth_call` API.
"""
call_transaction = prepare_transaction(
address,
web3,
fn_identifier=function_identifier,
contract_abi=contract_abi,
fn_abi=fn_abi,
transaction=transaction,
fn_args=args,
fn_kwargs=kwargs,
)
if block_id is None:
return_data = web3.eth.call(call_transaction)
else:
return_data = web3.eth.call(call_transaction, block_identifier=block_id)
if fn_abi is None:
fn_abi = find_matching_fn_abi(contract_abi, function_identifier, args, kwargs)
output_types = get_abi_output_types(fn_abi)
try:
output_data = decode_abi(output_types, return_data)
except DecodingError as e:
# Provide a more helpful error message than the one provided by
# eth-abi-utils
is_missing_code_error = (
return_data in ACCEPTABLE_EMPTY_STRINGS and
web3.eth.getCode(address) in ACCEPTABLE_EMPTY_STRINGS
)
if is_missing_code_error:
msg = (
"Could not transact with/call contract function, is contract "
"deployed correctly and chain synced?"
)
else:
msg = (
"Could not decode contract function call {} return data {} for "
"output_types {}".format(
function_identifier,
return_data,
output_types
)
)
raise BadFunctionCallOutput(msg) from e
_normalizers = itertools.chain(
BASE_RETURN_NORMALIZERS,
normalizers,
)
normalized_data = map_abi_data(_normalizers, output_types, output_data)
if len(normalized_data) == 1:
return normalized_data[0]
else:
return normalized_data | [
"def",
"call_contract_function",
"(",
"web3",
",",
"address",
",",
"normalizers",
",",
"function_identifier",
",",
"transaction",
",",
"block_id",
"=",
"None",
",",
"contract_abi",
"=",
"None",
",",
"fn_abi",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"... | Helper function for interacting with a contract function using the
`eth_call` API. | [
"Helper",
"function",
"for",
"interacting",
"with",
"a",
"contract",
"function",
"using",
"the",
"eth_call",
"API",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L1275-L1345 | train | 220,326 |
ethereum/web3.py | web3/contract.py | transact_with_contract_function | def transact_with_contract_function(
address,
web3,
function_name=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""
Helper function for interacting with a contract function by sending a
transaction.
"""
transact_transaction = prepare_transaction(
address,
web3,
fn_identifier=function_name,
contract_abi=contract_abi,
transaction=transaction,
fn_abi=fn_abi,
fn_args=args,
fn_kwargs=kwargs,
)
txn_hash = web3.eth.sendTransaction(transact_transaction)
return txn_hash | python | def transact_with_contract_function(
address,
web3,
function_name=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""
Helper function for interacting with a contract function by sending a
transaction.
"""
transact_transaction = prepare_transaction(
address,
web3,
fn_identifier=function_name,
contract_abi=contract_abi,
transaction=transaction,
fn_abi=fn_abi,
fn_args=args,
fn_kwargs=kwargs,
)
txn_hash = web3.eth.sendTransaction(transact_transaction)
return txn_hash | [
"def",
"transact_with_contract_function",
"(",
"address",
",",
"web3",
",",
"function_name",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"contract_abi",
"=",
"None",
",",
"fn_abi",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
... | Helper function for interacting with a contract function by sending a
transaction. | [
"Helper",
"function",
"for",
"interacting",
"with",
"a",
"contract",
"function",
"by",
"sending",
"a",
"transaction",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L1370-L1395 | train | 220,327 |
ethereum/web3.py | web3/contract.py | estimate_gas_for_function | def estimate_gas_for_function(
address,
web3,
fn_identifier=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""Estimates gas cost a function call would take.
Don't call this directly, instead use :meth:`Contract.estimateGas`
on your contract instance.
"""
estimate_transaction = prepare_transaction(
address,
web3,
fn_identifier=fn_identifier,
contract_abi=contract_abi,
fn_abi=fn_abi,
transaction=transaction,
fn_args=args,
fn_kwargs=kwargs,
)
gas_estimate = web3.eth.estimateGas(estimate_transaction)
return gas_estimate | python | def estimate_gas_for_function(
address,
web3,
fn_identifier=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""Estimates gas cost a function call would take.
Don't call this directly, instead use :meth:`Contract.estimateGas`
on your contract instance.
"""
estimate_transaction = prepare_transaction(
address,
web3,
fn_identifier=fn_identifier,
contract_abi=contract_abi,
fn_abi=fn_abi,
transaction=transaction,
fn_args=args,
fn_kwargs=kwargs,
)
gas_estimate = web3.eth.estimateGas(estimate_transaction)
return gas_estimate | [
"def",
"estimate_gas_for_function",
"(",
"address",
",",
"web3",
",",
"fn_identifier",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"contract_abi",
"=",
"None",
",",
"fn_abi",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"estim... | Estimates gas cost a function call would take.
Don't call this directly, instead use :meth:`Contract.estimateGas`
on your contract instance. | [
"Estimates",
"gas",
"cost",
"a",
"function",
"call",
"would",
"take",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L1398-L1424 | train | 220,328 |
ethereum/web3.py | web3/contract.py | build_transaction_for_function | def build_transaction_for_function(
address,
web3,
function_name=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""Builds a dictionary with the fields required to make the given transaction
Don't call this directly, instead use :meth:`Contract.buildTransaction`
on your contract instance.
"""
prepared_transaction = prepare_transaction(
address,
web3,
fn_identifier=function_name,
contract_abi=contract_abi,
fn_abi=fn_abi,
transaction=transaction,
fn_args=args,
fn_kwargs=kwargs,
)
prepared_transaction = fill_transaction_defaults(web3, prepared_transaction)
return prepared_transaction | python | def build_transaction_for_function(
address,
web3,
function_name=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""Builds a dictionary with the fields required to make the given transaction
Don't call this directly, instead use :meth:`Contract.buildTransaction`
on your contract instance.
"""
prepared_transaction = prepare_transaction(
address,
web3,
fn_identifier=function_name,
contract_abi=contract_abi,
fn_abi=fn_abi,
transaction=transaction,
fn_args=args,
fn_kwargs=kwargs,
)
prepared_transaction = fill_transaction_defaults(web3, prepared_transaction)
return prepared_transaction | [
"def",
"build_transaction_for_function",
"(",
"address",
",",
"web3",
",",
"function_name",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"contract_abi",
"=",
"None",
",",
"fn_abi",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"... | Builds a dictionary with the fields required to make the given transaction
Don't call this directly, instead use :meth:`Contract.buildTransaction`
on your contract instance. | [
"Builds",
"a",
"dictionary",
"with",
"the",
"fields",
"required",
"to",
"make",
"the",
"given",
"transaction"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L1427-L1454 | train | 220,329 |
ethereum/web3.py | web3/contract.py | Contract.encodeABI | def encodeABI(cls, fn_name, args=None, kwargs=None, data=None):
"""
Encodes the arguments using the Ethereum ABI for the contract function
that matches the given name and arguments..
:param data: defaults to function selector
"""
fn_abi, fn_selector, fn_arguments = get_function_info(
fn_name, contract_abi=cls.abi, args=args, kwargs=kwargs,
)
if data is None:
data = fn_selector
return encode_abi(cls.web3, fn_abi, fn_arguments, data) | python | def encodeABI(cls, fn_name, args=None, kwargs=None, data=None):
"""
Encodes the arguments using the Ethereum ABI for the contract function
that matches the given name and arguments..
:param data: defaults to function selector
"""
fn_abi, fn_selector, fn_arguments = get_function_info(
fn_name, contract_abi=cls.abi, args=args, kwargs=kwargs,
)
if data is None:
data = fn_selector
return encode_abi(cls.web3, fn_abi, fn_arguments, data) | [
"def",
"encodeABI",
"(",
"cls",
",",
"fn_name",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"fn_abi",
",",
"fn_selector",
",",
"fn_arguments",
"=",
"get_function_info",
"(",
"fn_name",
",",
"contract_abi",
"=... | Encodes the arguments using the Ethereum ABI for the contract function
that matches the given name and arguments..
:param data: defaults to function selector | [
"Encodes",
"the",
"arguments",
"using",
"the",
"Ethereum",
"ABI",
"for",
"the",
"contract",
"function",
"that",
"matches",
"the",
"given",
"name",
"and",
"arguments",
".."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L330-L344 | train | 220,330 |
ethereum/web3.py | web3/contract.py | ContractFunction.call | def call(self, transaction=None, block_identifier='latest'):
"""
Execute a contract function call using the `eth_call` interface.
This method prepares a ``Caller`` object that exposes the contract
functions and public variables as callable Python functions.
Reading a public ``owner`` address variable example:
.. code-block:: python
ContractFactory = w3.eth.contract(
abi=wallet_contract_definition["abi"]
)
# Not a real contract address
contract = ContractFactory("0x2f70d3d26829e412A602E83FE8EeBF80255AEeA5")
# Read "owner" public variable
addr = contract.functions.owner().call()
:param transaction: Dictionary of transaction info for web3 interface
:return: ``Caller`` object that has contract public functions
and variables exposed as Python methods
"""
if transaction is None:
call_transaction = {}
else:
call_transaction = dict(**transaction)
if 'data' in call_transaction:
raise ValueError("Cannot set data in call transaction")
if self.address:
call_transaction.setdefault('to', self.address)
if self.web3.eth.defaultAccount is not empty:
call_transaction.setdefault('from', self.web3.eth.defaultAccount)
if 'to' not in call_transaction:
if isinstance(self, type):
raise ValueError(
"When using `Contract.[methodtype].[method].call()` from"
" a contract factory you "
"must provide a `to` address with the transaction"
)
else:
raise ValueError(
"Please ensure that this contract instance has an address."
)
block_id = parse_block_identifier(self.web3, block_identifier)
return call_contract_function(
self.web3,
self.address,
self._return_data_normalizers,
self.function_identifier,
call_transaction,
block_id,
self.contract_abi,
self.abi,
*self.args,
**self.kwargs
) | python | def call(self, transaction=None, block_identifier='latest'):
"""
Execute a contract function call using the `eth_call` interface.
This method prepares a ``Caller`` object that exposes the contract
functions and public variables as callable Python functions.
Reading a public ``owner`` address variable example:
.. code-block:: python
ContractFactory = w3.eth.contract(
abi=wallet_contract_definition["abi"]
)
# Not a real contract address
contract = ContractFactory("0x2f70d3d26829e412A602E83FE8EeBF80255AEeA5")
# Read "owner" public variable
addr = contract.functions.owner().call()
:param transaction: Dictionary of transaction info for web3 interface
:return: ``Caller`` object that has contract public functions
and variables exposed as Python methods
"""
if transaction is None:
call_transaction = {}
else:
call_transaction = dict(**transaction)
if 'data' in call_transaction:
raise ValueError("Cannot set data in call transaction")
if self.address:
call_transaction.setdefault('to', self.address)
if self.web3.eth.defaultAccount is not empty:
call_transaction.setdefault('from', self.web3.eth.defaultAccount)
if 'to' not in call_transaction:
if isinstance(self, type):
raise ValueError(
"When using `Contract.[methodtype].[method].call()` from"
" a contract factory you "
"must provide a `to` address with the transaction"
)
else:
raise ValueError(
"Please ensure that this contract instance has an address."
)
block_id = parse_block_identifier(self.web3, block_identifier)
return call_contract_function(
self.web3,
self.address,
self._return_data_normalizers,
self.function_identifier,
call_transaction,
block_id,
self.contract_abi,
self.abi,
*self.args,
**self.kwargs
) | [
"def",
"call",
"(",
"self",
",",
"transaction",
"=",
"None",
",",
"block_identifier",
"=",
"'latest'",
")",
":",
"if",
"transaction",
"is",
"None",
":",
"call_transaction",
"=",
"{",
"}",
"else",
":",
"call_transaction",
"=",
"dict",
"(",
"*",
"*",
"tran... | Execute a contract function call using the `eth_call` interface.
This method prepares a ``Caller`` object that exposes the contract
functions and public variables as callable Python functions.
Reading a public ``owner`` address variable example:
.. code-block:: python
ContractFactory = w3.eth.contract(
abi=wallet_contract_definition["abi"]
)
# Not a real contract address
contract = ContractFactory("0x2f70d3d26829e412A602E83FE8EeBF80255AEeA5")
# Read "owner" public variable
addr = contract.functions.owner().call()
:param transaction: Dictionary of transaction info for web3 interface
:return: ``Caller`` object that has contract public functions
and variables exposed as Python methods | [
"Execute",
"a",
"contract",
"function",
"call",
"using",
"the",
"eth_call",
"interface",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L761-L824 | train | 220,331 |
ethereum/web3.py | web3/contract.py | ContractEvent.getLogs | def getLogs(self,
argument_filters=None,
fromBlock=None,
toBlock=None,
blockHash=None):
"""Get events for this contract instance using eth_getLogs API.
This is a stateless method, as opposed to createFilter.
It can be safely called against nodes which do not provide
eth_newFilter API, like Infura nodes.
If there are many events,
like ``Transfer`` events for a popular token,
the Ethereum node might be overloaded and timeout
on the underlying JSON-RPC call.
Example - how to get all ERC-20 token transactions
for the latest 10 blocks:
.. code-block:: python
from = max(mycontract.web3.eth.blockNumber - 10, 1)
to = mycontract.web3.eth.blockNumber
events = mycontract.events.Transfer.getLogs(fromBlock=from, toBlock=to)
for e in events:
print(e["args"]["from"],
e["args"]["to"],
e["args"]["value"])
The returned processed log values will look like:
.. code-block:: python
(
AttributeDict({
'args': AttributeDict({}),
'event': 'LogNoArguments',
'logIndex': 0,
'transactionIndex': 0,
'transactionHash': HexBytes('...'),
'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',
'blockHash': HexBytes('...'),
'blockNumber': 3
}),
AttributeDict(...),
...
)
See also: :func:`web3.middleware.filter.local_filter_middleware`.
:param argument_filters:
:param fromBlock: block number or "latest", defaults to "latest"
:param toBlock: block number or "latest". Defaults to "latest"
:param blockHash: block hash. blockHash cannot be set at the
same time as fromBlock or toBlock
:yield: Tuple of :class:`AttributeDict` instances
"""
if not self.address:
raise TypeError("This method can be only called on "
"an instated contract with an address")
abi = self._get_event_abi()
if argument_filters is None:
argument_filters = dict()
_filters = dict(**argument_filters)
blkhash_set = blockHash is not None
blknum_set = fromBlock is not None or toBlock is not None
if blkhash_set and blknum_set:
raise ValidationError(
'blockHash cannot be set at the same'
' time as fromBlock or toBlock')
# Construct JSON-RPC raw filter presentation based on human readable Python descriptions
# Namely, convert event names to their keccak signatures
data_filter_set, event_filter_params = construct_event_filter_params(
abi,
contract_address=self.address,
argument_filters=_filters,
fromBlock=fromBlock,
toBlock=toBlock,
address=self.address,
)
if blockHash is not None:
event_filter_params['blockHash'] = blockHash
# Call JSON-RPC API
logs = self.web3.eth.getLogs(event_filter_params)
# Convert raw binary data to Python proxy objects as described by ABI
return tuple(get_event_data(abi, entry) for entry in logs) | python | def getLogs(self,
argument_filters=None,
fromBlock=None,
toBlock=None,
blockHash=None):
"""Get events for this contract instance using eth_getLogs API.
This is a stateless method, as opposed to createFilter.
It can be safely called against nodes which do not provide
eth_newFilter API, like Infura nodes.
If there are many events,
like ``Transfer`` events for a popular token,
the Ethereum node might be overloaded and timeout
on the underlying JSON-RPC call.
Example - how to get all ERC-20 token transactions
for the latest 10 blocks:
.. code-block:: python
from = max(mycontract.web3.eth.blockNumber - 10, 1)
to = mycontract.web3.eth.blockNumber
events = mycontract.events.Transfer.getLogs(fromBlock=from, toBlock=to)
for e in events:
print(e["args"]["from"],
e["args"]["to"],
e["args"]["value"])
The returned processed log values will look like:
.. code-block:: python
(
AttributeDict({
'args': AttributeDict({}),
'event': 'LogNoArguments',
'logIndex': 0,
'transactionIndex': 0,
'transactionHash': HexBytes('...'),
'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',
'blockHash': HexBytes('...'),
'blockNumber': 3
}),
AttributeDict(...),
...
)
See also: :func:`web3.middleware.filter.local_filter_middleware`.
:param argument_filters:
:param fromBlock: block number or "latest", defaults to "latest"
:param toBlock: block number or "latest". Defaults to "latest"
:param blockHash: block hash. blockHash cannot be set at the
same time as fromBlock or toBlock
:yield: Tuple of :class:`AttributeDict` instances
"""
if not self.address:
raise TypeError("This method can be only called on "
"an instated contract with an address")
abi = self._get_event_abi()
if argument_filters is None:
argument_filters = dict()
_filters = dict(**argument_filters)
blkhash_set = blockHash is not None
blknum_set = fromBlock is not None or toBlock is not None
if blkhash_set and blknum_set:
raise ValidationError(
'blockHash cannot be set at the same'
' time as fromBlock or toBlock')
# Construct JSON-RPC raw filter presentation based on human readable Python descriptions
# Namely, convert event names to their keccak signatures
data_filter_set, event_filter_params = construct_event_filter_params(
abi,
contract_address=self.address,
argument_filters=_filters,
fromBlock=fromBlock,
toBlock=toBlock,
address=self.address,
)
if blockHash is not None:
event_filter_params['blockHash'] = blockHash
# Call JSON-RPC API
logs = self.web3.eth.getLogs(event_filter_params)
# Convert raw binary data to Python proxy objects as described by ABI
return tuple(get_event_data(abi, entry) for entry in logs) | [
"def",
"getLogs",
"(",
"self",
",",
"argument_filters",
"=",
"None",
",",
"fromBlock",
"=",
"None",
",",
"toBlock",
"=",
"None",
",",
"blockHash",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"address",
":",
"raise",
"TypeError",
"(",
"\"This method ... | Get events for this contract instance using eth_getLogs API.
This is a stateless method, as opposed to createFilter.
It can be safely called against nodes which do not provide
eth_newFilter API, like Infura nodes.
If there are many events,
like ``Transfer`` events for a popular token,
the Ethereum node might be overloaded and timeout
on the underlying JSON-RPC call.
Example - how to get all ERC-20 token transactions
for the latest 10 blocks:
.. code-block:: python
from = max(mycontract.web3.eth.blockNumber - 10, 1)
to = mycontract.web3.eth.blockNumber
events = mycontract.events.Transfer.getLogs(fromBlock=from, toBlock=to)
for e in events:
print(e["args"]["from"],
e["args"]["to"],
e["args"]["value"])
The returned processed log values will look like:
.. code-block:: python
(
AttributeDict({
'args': AttributeDict({}),
'event': 'LogNoArguments',
'logIndex': 0,
'transactionIndex': 0,
'transactionHash': HexBytes('...'),
'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',
'blockHash': HexBytes('...'),
'blockNumber': 3
}),
AttributeDict(...),
...
)
See also: :func:`web3.middleware.filter.local_filter_middleware`.
:param argument_filters:
:param fromBlock: block number or "latest", defaults to "latest"
:param toBlock: block number or "latest". Defaults to "latest"
:param blockHash: block hash. blockHash cannot be set at the
same time as fromBlock or toBlock
:yield: Tuple of :class:`AttributeDict` instances | [
"Get",
"events",
"for",
"this",
"contract",
"instance",
"using",
"eth_getLogs",
"API",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L1065-L1161 | train | 220,332 |
ethereum/web3.py | ens/utils.py | dict_copy | def dict_copy(func):
"copy dict keyword args, to avoid modifying caller's copy"
@functools.wraps(func)
def wrapper(*args, **kwargs):
copied_kwargs = copy.deepcopy(kwargs)
return func(*args, **copied_kwargs)
return wrapper | python | def dict_copy(func):
"copy dict keyword args, to avoid modifying caller's copy"
@functools.wraps(func)
def wrapper(*args, **kwargs):
copied_kwargs = copy.deepcopy(kwargs)
return func(*args, **copied_kwargs)
return wrapper | [
"def",
"dict_copy",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"copied_kwargs",
"=",
"copy",
".",
"deepcopy",
"(",
"kwargs",
")",
"return",
"func",
... | copy dict keyword args, to avoid modifying caller's copy | [
"copy",
"dict",
"keyword",
"args",
"to",
"avoid",
"modifying",
"caller",
"s",
"copy"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/utils.py#L33-L39 | train | 220,333 |
ethereum/web3.py | ens/utils.py | dot_eth_label | def dot_eth_label(name):
"""
Convert from a name, like 'ethfinex.eth', to a label, like 'ethfinex'
If name is already a label, this should be a noop, except for converting to a string
and validating the name syntax.
"""
label = name_to_label(name, registrar='eth')
if len(label) < MIN_ETH_LABEL_LENGTH:
raise InvalidLabel('name %r is too short' % label)
else:
return label | python | def dot_eth_label(name):
"""
Convert from a name, like 'ethfinex.eth', to a label, like 'ethfinex'
If name is already a label, this should be a noop, except for converting to a string
and validating the name syntax.
"""
label = name_to_label(name, registrar='eth')
if len(label) < MIN_ETH_LABEL_LENGTH:
raise InvalidLabel('name %r is too short' % label)
else:
return label | [
"def",
"dot_eth_label",
"(",
"name",
")",
":",
"label",
"=",
"name_to_label",
"(",
"name",
",",
"registrar",
"=",
"'eth'",
")",
"if",
"len",
"(",
"label",
")",
"<",
"MIN_ETH_LABEL_LENGTH",
":",
"raise",
"InvalidLabel",
"(",
"'name %r is too short'",
"%",
"la... | Convert from a name, like 'ethfinex.eth', to a label, like 'ethfinex'
If name is already a label, this should be a noop, except for converting to a string
and validating the name syntax. | [
"Convert",
"from",
"a",
"name",
"like",
"ethfinex",
".",
"eth",
"to",
"a",
"label",
"like",
"ethfinex",
"If",
"name",
"is",
"already",
"a",
"label",
"this",
"should",
"be",
"a",
"noop",
"except",
"for",
"converting",
"to",
"a",
"string",
"and",
"validati... | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/utils.py#L125-L135 | train | 220,334 |
ethereum/web3.py | web3/_utils/formatters.py | map_collection | def map_collection(func, collection):
"""
Apply func to each element of a collection, or value of a dictionary.
If the value is not a collection, return it unmodified
"""
datatype = type(collection)
if isinstance(collection, Mapping):
return datatype((key, func(val)) for key, val in collection.items())
if is_string(collection):
return collection
elif isinstance(collection, Iterable):
return datatype(map(func, collection))
else:
return collection | python | def map_collection(func, collection):
"""
Apply func to each element of a collection, or value of a dictionary.
If the value is not a collection, return it unmodified
"""
datatype = type(collection)
if isinstance(collection, Mapping):
return datatype((key, func(val)) for key, val in collection.items())
if is_string(collection):
return collection
elif isinstance(collection, Iterable):
return datatype(map(func, collection))
else:
return collection | [
"def",
"map_collection",
"(",
"func",
",",
"collection",
")",
":",
"datatype",
"=",
"type",
"(",
"collection",
")",
"if",
"isinstance",
"(",
"collection",
",",
"Mapping",
")",
":",
"return",
"datatype",
"(",
"(",
"key",
",",
"func",
"(",
"val",
")",
")... | Apply func to each element of a collection, or value of a dictionary.
If the value is not a collection, return it unmodified | [
"Apply",
"func",
"to",
"each",
"element",
"of",
"a",
"collection",
"or",
"value",
"of",
"a",
"dictionary",
".",
"If",
"the",
"value",
"is",
"not",
"a",
"collection",
"return",
"it",
"unmodified"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/formatters.py#L91-L104 | train | 220,335 |
ethereum/web3.py | web3/_utils/math.py | percentile | def percentile(values=None, percentile=None):
"""Calculates a simplified weighted average percentile
"""
if values in [None, tuple(), []] or len(values) < 1:
raise InsufficientData(
"Expected a sequence of at least 1 integers, got {0!r}".format(values))
if percentile is None:
raise ValueError("Expected a percentile choice, got {0}".format(percentile))
sorted_values = sorted(values)
rank = len(values) * percentile / 100
if rank > 0:
index = rank - 1
if index < 0:
return sorted_values[0]
else:
index = rank
if index % 1 == 0:
return sorted_values[int(index)]
else:
fractional = index % 1
integer = int(index - fractional)
lower = sorted_values[integer]
higher = sorted_values[integer + 1]
return lower + fractional * (higher - lower) | python | def percentile(values=None, percentile=None):
"""Calculates a simplified weighted average percentile
"""
if values in [None, tuple(), []] or len(values) < 1:
raise InsufficientData(
"Expected a sequence of at least 1 integers, got {0!r}".format(values))
if percentile is None:
raise ValueError("Expected a percentile choice, got {0}".format(percentile))
sorted_values = sorted(values)
rank = len(values) * percentile / 100
if rank > 0:
index = rank - 1
if index < 0:
return sorted_values[0]
else:
index = rank
if index % 1 == 0:
return sorted_values[int(index)]
else:
fractional = index % 1
integer = int(index - fractional)
lower = sorted_values[integer]
higher = sorted_values[integer + 1]
return lower + fractional * (higher - lower) | [
"def",
"percentile",
"(",
"values",
"=",
"None",
",",
"percentile",
"=",
"None",
")",
":",
"if",
"values",
"in",
"[",
"None",
",",
"tuple",
"(",
")",
",",
"[",
"]",
"]",
"or",
"len",
"(",
"values",
")",
"<",
"1",
":",
"raise",
"InsufficientData",
... | Calculates a simplified weighted average percentile | [
"Calculates",
"a",
"simplified",
"weighted",
"average",
"percentile"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/math.py#L6-L32 | train | 220,336 |
ethereum/web3.py | web3/datastructures.py | ReadableAttributeDict._repr_pretty_ | def _repr_pretty_(self, builder, cycle):
"""
Custom pretty output for the IPython console
"""
builder.text(self.__class__.__name__ + "(")
if cycle:
builder.text("<cycle>")
else:
builder.pretty(self.__dict__)
builder.text(")") | python | def _repr_pretty_(self, builder, cycle):
"""
Custom pretty output for the IPython console
"""
builder.text(self.__class__.__name__ + "(")
if cycle:
builder.text("<cycle>")
else:
builder.pretty(self.__dict__)
builder.text(")") | [
"def",
"_repr_pretty_",
"(",
"self",
",",
"builder",
",",
"cycle",
")",
":",
"builder",
".",
"text",
"(",
"self",
".",
"__class__",
".",
"__name__",
"+",
"\"(\"",
")",
"if",
"cycle",
":",
"builder",
".",
"text",
"(",
"\"<cycle>\"",
")",
"else",
":",
... | Custom pretty output for the IPython console | [
"Custom",
"pretty",
"output",
"for",
"the",
"IPython",
"console"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/datastructures.py#L45-L54 | train | 220,337 |
ethereum/web3.py | web3/datastructures.py | NamedElementOnion.inject | def inject(self, element, name=None, layer=None):
"""
Inject a named element to an arbitrary layer in the onion.
The current implementation only supports insertion at the innermost layer,
or at the outermost layer. Note that inserting to the outermost is equivalent
to calling :meth:`add` .
"""
if not is_integer(layer):
raise TypeError("The layer for insertion must be an int.")
elif layer != 0 and layer != len(self._queue):
raise NotImplementedError(
"You can only insert to the beginning or end of a %s, currently. "
"You tried to insert to %d, but only 0 and %d are permitted. " % (
type(self),
layer,
len(self._queue),
)
)
self.add(element, name=name)
if layer == 0:
if name is None:
name = element
self._queue.move_to_end(name, last=False)
elif layer == len(self._queue):
return
else:
raise AssertionError("Impossible to reach: earlier validation raises an error") | python | def inject(self, element, name=None, layer=None):
"""
Inject a named element to an arbitrary layer in the onion.
The current implementation only supports insertion at the innermost layer,
or at the outermost layer. Note that inserting to the outermost is equivalent
to calling :meth:`add` .
"""
if not is_integer(layer):
raise TypeError("The layer for insertion must be an int.")
elif layer != 0 and layer != len(self._queue):
raise NotImplementedError(
"You can only insert to the beginning or end of a %s, currently. "
"You tried to insert to %d, but only 0 and %d are permitted. " % (
type(self),
layer,
len(self._queue),
)
)
self.add(element, name=name)
if layer == 0:
if name is None:
name = element
self._queue.move_to_end(name, last=False)
elif layer == len(self._queue):
return
else:
raise AssertionError("Impossible to reach: earlier validation raises an error") | [
"def",
"inject",
"(",
"self",
",",
"element",
",",
"name",
"=",
"None",
",",
"layer",
"=",
"None",
")",
":",
"if",
"not",
"is_integer",
"(",
"layer",
")",
":",
"raise",
"TypeError",
"(",
"\"The layer for insertion must be an int.\"",
")",
"elif",
"layer",
... | Inject a named element to an arbitrary layer in the onion.
The current implementation only supports insertion at the innermost layer,
or at the outermost layer. Note that inserting to the outermost is equivalent
to calling :meth:`add` . | [
"Inject",
"a",
"named",
"element",
"to",
"an",
"arbitrary",
"layer",
"in",
"the",
"onion",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/datastructures.py#L127-L156 | train | 220,338 |
ethereum/web3.py | web3/middleware/signing.py | construct_sign_and_send_raw_middleware | def construct_sign_and_send_raw_middleware(private_key_or_account):
"""Capture transactions sign and send as raw transactions
Keyword arguments:
private_key_or_account -- A single private key or a tuple,
list or set of private keys. Keys can be any of the following formats:
- An eth_account.LocalAccount object
- An eth_keys.PrivateKey object
- A raw private key as a hex string or byte string
"""
accounts = gen_normalized_accounts(private_key_or_account)
def sign_and_send_raw_middleware(make_request, w3):
format_and_fill_tx = compose(
format_transaction,
fill_transaction_defaults(w3),
fill_nonce(w3))
def middleware(method, params):
if method != "eth_sendTransaction":
return make_request(method, params)
else:
transaction = format_and_fill_tx(params[0])
if 'from' not in transaction:
return make_request(method, params)
elif transaction.get('from') not in accounts:
return make_request(method, params)
account = accounts[transaction['from']]
raw_tx = account.signTransaction(transaction).rawTransaction
return make_request(
"eth_sendRawTransaction",
[raw_tx])
return middleware
return sign_and_send_raw_middleware | python | def construct_sign_and_send_raw_middleware(private_key_or_account):
"""Capture transactions sign and send as raw transactions
Keyword arguments:
private_key_or_account -- A single private key or a tuple,
list or set of private keys. Keys can be any of the following formats:
- An eth_account.LocalAccount object
- An eth_keys.PrivateKey object
- A raw private key as a hex string or byte string
"""
accounts = gen_normalized_accounts(private_key_or_account)
def sign_and_send_raw_middleware(make_request, w3):
format_and_fill_tx = compose(
format_transaction,
fill_transaction_defaults(w3),
fill_nonce(w3))
def middleware(method, params):
if method != "eth_sendTransaction":
return make_request(method, params)
else:
transaction = format_and_fill_tx(params[0])
if 'from' not in transaction:
return make_request(method, params)
elif transaction.get('from') not in accounts:
return make_request(method, params)
account = accounts[transaction['from']]
raw_tx = account.signTransaction(transaction).rawTransaction
return make_request(
"eth_sendRawTransaction",
[raw_tx])
return middleware
return sign_and_send_raw_middleware | [
"def",
"construct_sign_and_send_raw_middleware",
"(",
"private_key_or_account",
")",
":",
"accounts",
"=",
"gen_normalized_accounts",
"(",
"private_key_or_account",
")",
"def",
"sign_and_send_raw_middleware",
"(",
"make_request",
",",
"w3",
")",
":",
"format_and_fill_tx",
"... | Capture transactions sign and send as raw transactions
Keyword arguments:
private_key_or_account -- A single private key or a tuple,
list or set of private keys. Keys can be any of the following formats:
- An eth_account.LocalAccount object
- An eth_keys.PrivateKey object
- A raw private key as a hex string or byte string | [
"Capture",
"transactions",
"sign",
"and",
"send",
"as",
"raw",
"transactions"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/signing.py#L95-L136 | train | 220,339 |
ethereum/web3.py | web3/_utils/validation.py | validate_abi | def validate_abi(abi):
"""
Helper function for validating an ABI
"""
if not is_list_like(abi):
raise ValueError("'abi' is not a list")
if not all(is_dict(e) for e in abi):
raise ValueError("'abi' is not a list of dictionaries")
functions = filter_by_type('function', abi)
selectors = groupby(
compose(encode_hex, function_abi_to_4byte_selector),
functions
)
duplicates = valfilter(lambda funcs: len(funcs) > 1, selectors)
if duplicates:
raise ValueError(
'Abi contains functions with colliding selectors. '
'Functions {0}'.format(_prepare_selector_collision_msg(duplicates))
) | python | def validate_abi(abi):
"""
Helper function for validating an ABI
"""
if not is_list_like(abi):
raise ValueError("'abi' is not a list")
if not all(is_dict(e) for e in abi):
raise ValueError("'abi' is not a list of dictionaries")
functions = filter_by_type('function', abi)
selectors = groupby(
compose(encode_hex, function_abi_to_4byte_selector),
functions
)
duplicates = valfilter(lambda funcs: len(funcs) > 1, selectors)
if duplicates:
raise ValueError(
'Abi contains functions with colliding selectors. '
'Functions {0}'.format(_prepare_selector_collision_msg(duplicates))
) | [
"def",
"validate_abi",
"(",
"abi",
")",
":",
"if",
"not",
"is_list_like",
"(",
"abi",
")",
":",
"raise",
"ValueError",
"(",
"\"'abi' is not a list\"",
")",
"if",
"not",
"all",
"(",
"is_dict",
"(",
"e",
")",
"for",
"e",
"in",
"abi",
")",
":",
"raise",
... | Helper function for validating an ABI | [
"Helper",
"function",
"for",
"validating",
"an",
"ABI"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/validation.py#L55-L75 | train | 220,340 |
ethereum/web3.py | web3/_utils/validation.py | validate_address | def validate_address(value):
"""
Helper function for validating an address
"""
if is_bytes(value):
if not is_binary_address(value):
raise InvalidAddress("Address must be 20 bytes when input type is bytes", value)
return
if not isinstance(value, str):
raise TypeError('Address {} must be provided as a string'.format(value))
if not is_hex_address(value):
raise InvalidAddress("Address must be 20 bytes, as a hex string with a 0x prefix", value)
if not is_checksum_address(value):
if value == value.lower():
raise InvalidAddress(
"Web3.py only accepts checksum addresses. "
"The software that gave you this non-checksum address should be considered unsafe, "
"please file it as a bug on their platform. "
"Try using an ENS name instead. Or, if you must accept lower safety, "
"use Web3.toChecksumAddress(lower_case_address).",
value,
)
else:
raise InvalidAddress(
"Address has an invalid EIP-55 checksum. "
"After looking up the address from the original source, try again.",
value,
) | python | def validate_address(value):
"""
Helper function for validating an address
"""
if is_bytes(value):
if not is_binary_address(value):
raise InvalidAddress("Address must be 20 bytes when input type is bytes", value)
return
if not isinstance(value, str):
raise TypeError('Address {} must be provided as a string'.format(value))
if not is_hex_address(value):
raise InvalidAddress("Address must be 20 bytes, as a hex string with a 0x prefix", value)
if not is_checksum_address(value):
if value == value.lower():
raise InvalidAddress(
"Web3.py only accepts checksum addresses. "
"The software that gave you this non-checksum address should be considered unsafe, "
"please file it as a bug on their platform. "
"Try using an ENS name instead. Or, if you must accept lower safety, "
"use Web3.toChecksumAddress(lower_case_address).",
value,
)
else:
raise InvalidAddress(
"Address has an invalid EIP-55 checksum. "
"After looking up the address from the original source, try again.",
value,
) | [
"def",
"validate_address",
"(",
"value",
")",
":",
"if",
"is_bytes",
"(",
"value",
")",
":",
"if",
"not",
"is_binary_address",
"(",
"value",
")",
":",
"raise",
"InvalidAddress",
"(",
"\"Address must be 20 bytes when input type is bytes\"",
",",
"value",
")",
"retu... | Helper function for validating an address | [
"Helper",
"function",
"for",
"validating",
"an",
"address"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/validation.py#L142-L170 | train | 220,341 |
ethereum/web3.py | web3/middleware/cache.py | construct_simple_cache_middleware | def construct_simple_cache_middleware(
cache_class,
rpc_whitelist=SIMPLE_CACHE_RPC_WHITELIST,
should_cache_fn=_should_cache):
"""
Constructs a middleware which caches responses based on the request
``method`` and ``params``
:param cache: Any dictionary-like object
:param rpc_whitelist: A set of RPC methods which may have their responses cached.
:param should_cache_fn: A callable which accepts ``method`` ``params`` and
``response`` and returns a boolean as to whether the response should be
cached.
"""
def simple_cache_middleware(make_request, web3):
cache = cache_class()
lock = threading.Lock()
def middleware(method, params):
lock_acquired = lock.acquire(blocking=False)
try:
if lock_acquired and method in rpc_whitelist:
cache_key = generate_cache_key((method, params))
if cache_key not in cache:
response = make_request(method, params)
if should_cache_fn(method, params, response):
cache[cache_key] = response
return response
return cache[cache_key]
else:
return make_request(method, params)
finally:
if lock_acquired:
lock.release()
return middleware
return simple_cache_middleware | python | def construct_simple_cache_middleware(
cache_class,
rpc_whitelist=SIMPLE_CACHE_RPC_WHITELIST,
should_cache_fn=_should_cache):
"""
Constructs a middleware which caches responses based on the request
``method`` and ``params``
:param cache: Any dictionary-like object
:param rpc_whitelist: A set of RPC methods which may have their responses cached.
:param should_cache_fn: A callable which accepts ``method`` ``params`` and
``response`` and returns a boolean as to whether the response should be
cached.
"""
def simple_cache_middleware(make_request, web3):
cache = cache_class()
lock = threading.Lock()
def middleware(method, params):
lock_acquired = lock.acquire(blocking=False)
try:
if lock_acquired and method in rpc_whitelist:
cache_key = generate_cache_key((method, params))
if cache_key not in cache:
response = make_request(method, params)
if should_cache_fn(method, params, response):
cache[cache_key] = response
return response
return cache[cache_key]
else:
return make_request(method, params)
finally:
if lock_acquired:
lock.release()
return middleware
return simple_cache_middleware | [
"def",
"construct_simple_cache_middleware",
"(",
"cache_class",
",",
"rpc_whitelist",
"=",
"SIMPLE_CACHE_RPC_WHITELIST",
",",
"should_cache_fn",
"=",
"_should_cache",
")",
":",
"def",
"simple_cache_middleware",
"(",
"make_request",
",",
"web3",
")",
":",
"cache",
"=",
... | Constructs a middleware which caches responses based on the request
``method`` and ``params``
:param cache: Any dictionary-like object
:param rpc_whitelist: A set of RPC methods which may have their responses cached.
:param should_cache_fn: A callable which accepts ``method`` ``params`` and
``response`` and returns a boolean as to whether the response should be
cached. | [
"Constructs",
"a",
"middleware",
"which",
"caches",
"responses",
"based",
"on",
"the",
"request",
"method",
"and",
"params"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/cache.py#L74-L110 | train | 220,342 |
ethereum/web3.py | web3/middleware/cache.py | construct_time_based_cache_middleware | def construct_time_based_cache_middleware(
cache_class,
cache_expire_seconds=15,
rpc_whitelist=TIME_BASED_CACHE_RPC_WHITELIST,
should_cache_fn=_should_cache):
"""
Constructs a middleware which caches responses based on the request
``method`` and ``params`` for a maximum amount of time as specified
:param cache: Any dictionary-like object
:param cache_expire_seconds: The number of seconds an item may be cached
before it should expire.
:param rpc_whitelist: A set of RPC methods which may have their responses cached.
:param should_cache_fn: A callable which accepts ``method`` ``params`` and
``response`` and returns a boolean as to whether the response should be
cached.
"""
def time_based_cache_middleware(make_request, web3):
cache = cache_class()
lock = threading.Lock()
def middleware(method, params):
lock_acquired = lock.acquire(blocking=False)
try:
if lock_acquired and method in rpc_whitelist:
cache_key = generate_cache_key((method, params))
if cache_key in cache:
# check that the cached response is not expired.
cached_at, cached_response = cache[cache_key]
cached_for = time.time() - cached_at
if cached_for <= cache_expire_seconds:
return cached_response
else:
del cache[cache_key]
# cache either missed or expired so make the request.
response = make_request(method, params)
if should_cache_fn(method, params, response):
cache[cache_key] = (time.time(), response)
return response
else:
return make_request(method, params)
finally:
if lock_acquired:
lock.release()
return middleware
return time_based_cache_middleware | python | def construct_time_based_cache_middleware(
cache_class,
cache_expire_seconds=15,
rpc_whitelist=TIME_BASED_CACHE_RPC_WHITELIST,
should_cache_fn=_should_cache):
"""
Constructs a middleware which caches responses based on the request
``method`` and ``params`` for a maximum amount of time as specified
:param cache: Any dictionary-like object
:param cache_expire_seconds: The number of seconds an item may be cached
before it should expire.
:param rpc_whitelist: A set of RPC methods which may have their responses cached.
:param should_cache_fn: A callable which accepts ``method`` ``params`` and
``response`` and returns a boolean as to whether the response should be
cached.
"""
def time_based_cache_middleware(make_request, web3):
cache = cache_class()
lock = threading.Lock()
def middleware(method, params):
lock_acquired = lock.acquire(blocking=False)
try:
if lock_acquired and method in rpc_whitelist:
cache_key = generate_cache_key((method, params))
if cache_key in cache:
# check that the cached response is not expired.
cached_at, cached_response = cache[cache_key]
cached_for = time.time() - cached_at
if cached_for <= cache_expire_seconds:
return cached_response
else:
del cache[cache_key]
# cache either missed or expired so make the request.
response = make_request(method, params)
if should_cache_fn(method, params, response):
cache[cache_key] = (time.time(), response)
return response
else:
return make_request(method, params)
finally:
if lock_acquired:
lock.release()
return middleware
return time_based_cache_middleware | [
"def",
"construct_time_based_cache_middleware",
"(",
"cache_class",
",",
"cache_expire_seconds",
"=",
"15",
",",
"rpc_whitelist",
"=",
"TIME_BASED_CACHE_RPC_WHITELIST",
",",
"should_cache_fn",
"=",
"_should_cache",
")",
":",
"def",
"time_based_cache_middleware",
"(",
"make_... | Constructs a middleware which caches responses based on the request
``method`` and ``params`` for a maximum amount of time as specified
:param cache: Any dictionary-like object
:param cache_expire_seconds: The number of seconds an item may be cached
before it should expire.
:param rpc_whitelist: A set of RPC methods which may have their responses cached.
:param should_cache_fn: A callable which accepts ``method`` ``params`` and
``response`` and returns a boolean as to whether the response should be
cached. | [
"Constructs",
"a",
"middleware",
"which",
"caches",
"responses",
"based",
"on",
"the",
"request",
"method",
"and",
"params",
"for",
"a",
"maximum",
"amount",
"of",
"time",
"as",
"specified"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/cache.py#L170-L220 | train | 220,343 |
ethereum/web3.py | web3/_utils/decorators.py | reject_recursive_repeats | def reject_recursive_repeats(to_wrap):
"""
Prevent simple cycles by returning None when called recursively with same instance
"""
to_wrap.__already_called = {}
@functools.wraps(to_wrap)
def wrapped(*args):
arg_instances = tuple(map(id, args))
thread_id = threading.get_ident()
thread_local_args = (thread_id,) + arg_instances
if thread_local_args in to_wrap.__already_called:
raise ValueError('Recursively called %s with %r' % (to_wrap, args))
to_wrap.__already_called[thread_local_args] = True
try:
wrapped_val = to_wrap(*args)
finally:
del to_wrap.__already_called[thread_local_args]
return wrapped_val
return wrapped | python | def reject_recursive_repeats(to_wrap):
"""
Prevent simple cycles by returning None when called recursively with same instance
"""
to_wrap.__already_called = {}
@functools.wraps(to_wrap)
def wrapped(*args):
arg_instances = tuple(map(id, args))
thread_id = threading.get_ident()
thread_local_args = (thread_id,) + arg_instances
if thread_local_args in to_wrap.__already_called:
raise ValueError('Recursively called %s with %r' % (to_wrap, args))
to_wrap.__already_called[thread_local_args] = True
try:
wrapped_val = to_wrap(*args)
finally:
del to_wrap.__already_called[thread_local_args]
return wrapped_val
return wrapped | [
"def",
"reject_recursive_repeats",
"(",
"to_wrap",
")",
":",
"to_wrap",
".",
"__already_called",
"=",
"{",
"}",
"@",
"functools",
".",
"wraps",
"(",
"to_wrap",
")",
"def",
"wrapped",
"(",
"*",
"args",
")",
":",
"arg_instances",
"=",
"tuple",
"(",
"map",
... | Prevent simple cycles by returning None when called recursively with same instance | [
"Prevent",
"simple",
"cycles",
"by",
"returning",
"None",
"when",
"called",
"recursively",
"with",
"same",
"instance"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/decorators.py#L20-L39 | train | 220,344 |
ethereum/web3.py | web3/_utils/abi.py | get_tuple_type_str_parts | def get_tuple_type_str_parts(s: str) -> Optional[Tuple[str, Optional[str]]]:
"""
Takes a JSON ABI type string. For tuple type strings, returns the separated
prefix and array dimension parts. For all other strings, returns ``None``.
"""
match = TUPLE_TYPE_STR_RE.match(s)
if match is not None:
tuple_prefix = match.group(1)
tuple_dims = match.group(2)
return tuple_prefix, tuple_dims
return None | python | def get_tuple_type_str_parts(s: str) -> Optional[Tuple[str, Optional[str]]]:
"""
Takes a JSON ABI type string. For tuple type strings, returns the separated
prefix and array dimension parts. For all other strings, returns ``None``.
"""
match = TUPLE_TYPE_STR_RE.match(s)
if match is not None:
tuple_prefix = match.group(1)
tuple_dims = match.group(2)
return tuple_prefix, tuple_dims
return None | [
"def",
"get_tuple_type_str_parts",
"(",
"s",
":",
"str",
")",
"->",
"Optional",
"[",
"Tuple",
"[",
"str",
",",
"Optional",
"[",
"str",
"]",
"]",
"]",
":",
"match",
"=",
"TUPLE_TYPE_STR_RE",
".",
"match",
"(",
"s",
")",
"if",
"match",
"is",
"not",
"No... | Takes a JSON ABI type string. For tuple type strings, returns the separated
prefix and array dimension parts. For all other strings, returns ``None``. | [
"Takes",
"a",
"JSON",
"ABI",
"type",
"string",
".",
"For",
"tuple",
"type",
"strings",
"returns",
"the",
"separated",
"prefix",
"and",
"array",
"dimension",
"parts",
".",
"For",
"all",
"other",
"strings",
"returns",
"None",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/abi.py#L319-L332 | train | 220,345 |
ethereum/web3.py | web3/_utils/abi.py | _align_abi_input | def _align_abi_input(arg_abi, arg):
"""
Aligns the values of any mapping at any level of nesting in ``arg``
according to the layout of the corresponding abi spec.
"""
tuple_parts = get_tuple_type_str_parts(arg_abi['type'])
if tuple_parts is None:
# Arg is non-tuple. Just return value.
return arg
tuple_prefix, tuple_dims = tuple_parts
if tuple_dims is None:
# Arg is non-list tuple. Each sub arg in `arg` will be aligned
# according to its corresponding abi.
sub_abis = arg_abi['components']
else:
# Arg is list tuple. A non-list version of its abi will be used to
# align each element in `arg`.
new_abi = copy.copy(arg_abi)
new_abi['type'] = tuple_prefix
sub_abis = itertools.repeat(new_abi)
if isinstance(arg, abc.Mapping):
# Arg is mapping. Align values according to abi order.
aligned_arg = tuple(arg[abi['name']] for abi in sub_abis)
else:
aligned_arg = arg
if not is_list_like(aligned_arg):
raise TypeError(
'Expected non-string sequence for "{}" component type: got {}'.format(
arg_abi['type'],
aligned_arg,
),
)
return type(aligned_arg)(
_align_abi_input(sub_abi, sub_arg)
for sub_abi, sub_arg in zip(sub_abis, aligned_arg)
) | python | def _align_abi_input(arg_abi, arg):
"""
Aligns the values of any mapping at any level of nesting in ``arg``
according to the layout of the corresponding abi spec.
"""
tuple_parts = get_tuple_type_str_parts(arg_abi['type'])
if tuple_parts is None:
# Arg is non-tuple. Just return value.
return arg
tuple_prefix, tuple_dims = tuple_parts
if tuple_dims is None:
# Arg is non-list tuple. Each sub arg in `arg` will be aligned
# according to its corresponding abi.
sub_abis = arg_abi['components']
else:
# Arg is list tuple. A non-list version of its abi will be used to
# align each element in `arg`.
new_abi = copy.copy(arg_abi)
new_abi['type'] = tuple_prefix
sub_abis = itertools.repeat(new_abi)
if isinstance(arg, abc.Mapping):
# Arg is mapping. Align values according to abi order.
aligned_arg = tuple(arg[abi['name']] for abi in sub_abis)
else:
aligned_arg = arg
if not is_list_like(aligned_arg):
raise TypeError(
'Expected non-string sequence for "{}" component type: got {}'.format(
arg_abi['type'],
aligned_arg,
),
)
return type(aligned_arg)(
_align_abi_input(sub_abi, sub_arg)
for sub_abi, sub_arg in zip(sub_abis, aligned_arg)
) | [
"def",
"_align_abi_input",
"(",
"arg_abi",
",",
"arg",
")",
":",
"tuple_parts",
"=",
"get_tuple_type_str_parts",
"(",
"arg_abi",
"[",
"'type'",
"]",
")",
"if",
"tuple_parts",
"is",
"None",
":",
"# Arg is non-tuple. Just return value.",
"return",
"arg",
"tuple_prefi... | Aligns the values of any mapping at any level of nesting in ``arg``
according to the layout of the corresponding abi spec. | [
"Aligns",
"the",
"values",
"of",
"any",
"mapping",
"at",
"any",
"level",
"of",
"nesting",
"in",
"arg",
"according",
"to",
"the",
"layout",
"of",
"the",
"corresponding",
"abi",
"spec",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/abi.py#L335-L376 | train | 220,346 |
ethereum/web3.py | web3/_utils/abi.py | size_of_type | def size_of_type(abi_type):
"""
Returns size in bits of abi_type
"""
if 'string' in abi_type:
return None
if 'byte' in abi_type:
return None
if '[' in abi_type:
return None
if abi_type == 'bool':
return 8
if abi_type == 'address':
return 160
return int(re.sub(r"\D", "", abi_type)) | python | def size_of_type(abi_type):
"""
Returns size in bits of abi_type
"""
if 'string' in abi_type:
return None
if 'byte' in abi_type:
return None
if '[' in abi_type:
return None
if abi_type == 'bool':
return 8
if abi_type == 'address':
return 160
return int(re.sub(r"\D", "", abi_type)) | [
"def",
"size_of_type",
"(",
"abi_type",
")",
":",
"if",
"'string'",
"in",
"abi_type",
":",
"return",
"None",
"if",
"'byte'",
"in",
"abi_type",
":",
"return",
"None",
"if",
"'['",
"in",
"abi_type",
":",
"return",
"None",
"if",
"abi_type",
"==",
"'bool'",
... | Returns size in bits of abi_type | [
"Returns",
"size",
"in",
"bits",
"of",
"abi_type"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/abi.py#L485-L499 | train | 220,347 |
danielfrg/word2vec | word2vec/wordclusters.py | WordClusters.ix | def ix(self, word):
"""
Returns the index on self.vocab and self.clusters for 'word'
"""
temp = np.where(self.vocab == word)[0]
if temp.size == 0:
raise KeyError("Word not in vocabulary")
else:
return temp[0] | python | def ix(self, word):
"""
Returns the index on self.vocab and self.clusters for 'word'
"""
temp = np.where(self.vocab == word)[0]
if temp.size == 0:
raise KeyError("Word not in vocabulary")
else:
return temp[0] | [
"def",
"ix",
"(",
"self",
",",
"word",
")",
":",
"temp",
"=",
"np",
".",
"where",
"(",
"self",
".",
"vocab",
"==",
"word",
")",
"[",
"0",
"]",
"if",
"temp",
".",
"size",
"==",
"0",
":",
"raise",
"KeyError",
"(",
"\"Word not in vocabulary\"",
")",
... | Returns the index on self.vocab and self.clusters for 'word' | [
"Returns",
"the",
"index",
"on",
"self",
".",
"vocab",
"and",
"self",
".",
"clusters",
"for",
"word"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordclusters.py#L10-L18 | train | 220,348 |
danielfrg/word2vec | word2vec/wordclusters.py | WordClusters.get_cluster | def get_cluster(self, word):
"""
Returns the cluster number for a word in the vocabulary
"""
idx = self.ix(word)
return self.clusters[idx] | python | def get_cluster(self, word):
"""
Returns the cluster number for a word in the vocabulary
"""
idx = self.ix(word)
return self.clusters[idx] | [
"def",
"get_cluster",
"(",
"self",
",",
"word",
")",
":",
"idx",
"=",
"self",
".",
"ix",
"(",
"word",
")",
"return",
"self",
".",
"clusters",
"[",
"idx",
"]"
] | Returns the cluster number for a word in the vocabulary | [
"Returns",
"the",
"cluster",
"number",
"for",
"a",
"word",
"in",
"the",
"vocabulary"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordclusters.py#L23-L28 | train | 220,349 |
danielfrg/word2vec | word2vec/wordvectors.py | WordVectors.closest | def closest(self, vector, n=10, metric="cosine"):
"""Returns the closest n words to a vector
Parameters
-------
vector : numpy.array
n : int (default 10)
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity
"""
distances = distance(self.vectors, vector, metric=metric)
best = np.argsort(distances)[::-1][1:n + 1]
best_metrics = distances[best]
return best, best_metrics | python | def closest(self, vector, n=10, metric="cosine"):
"""Returns the closest n words to a vector
Parameters
-------
vector : numpy.array
n : int (default 10)
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity
"""
distances = distance(self.vectors, vector, metric=metric)
best = np.argsort(distances)[::-1][1:n + 1]
best_metrics = distances[best]
return best, best_metrics | [
"def",
"closest",
"(",
"self",
",",
"vector",
",",
"n",
"=",
"10",
",",
"metric",
"=",
"\"cosine\"",
")",
":",
"distances",
"=",
"distance",
"(",
"self",
".",
"vectors",
",",
"vector",
",",
"metric",
"=",
"metric",
")",
"best",
"=",
"np",
".",
"arg... | Returns the closest n words to a vector
Parameters
-------
vector : numpy.array
n : int (default 10)
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity | [
"Returns",
"the",
"closest",
"n",
"words",
"to",
"a",
"vector"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordvectors.py#L90-L107 | train | 220,350 |
danielfrg/word2vec | word2vec/wordvectors.py | WordVectors.similar | def similar(self, word, n=10, metric="cosine"):
"""
Return similar words based on a metric
Parameters
----------
word : string
n : int (default 10)
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity
"""
return self.closest(self[word], n=n, metric=metric) | python | def similar(self, word, n=10, metric="cosine"):
"""
Return similar words based on a metric
Parameters
----------
word : string
n : int (default 10)
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity
"""
return self.closest(self[word], n=n, metric=metric) | [
"def",
"similar",
"(",
"self",
",",
"word",
",",
"n",
"=",
"10",
",",
"metric",
"=",
"\"cosine\"",
")",
":",
"return",
"self",
".",
"closest",
"(",
"self",
"[",
"word",
"]",
",",
"n",
"=",
"n",
",",
"metric",
"=",
"metric",
")"
] | Return similar words based on a metric
Parameters
----------
word : string
n : int (default 10)
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity | [
"Return",
"similar",
"words",
"based",
"on",
"a",
"metric"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordvectors.py#L109-L124 | train | 220,351 |
danielfrg/word2vec | word2vec/wordvectors.py | WordVectors.analogy | def analogy(self, pos, neg, n=10, metric="cosine"):
"""
Analogy similarity.
Parameters
----------
pos : list
neg : list
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity
Example
-------
`king - man + woman = queen` will be: `pos=['king', 'woman'], neg=['man']`
"""
exclude = pos + neg
pos = [(word, 1.0) for word in pos]
neg = [(word, -1.0) for word in neg]
mean = []
for word, direction in pos + neg:
mean.append(direction * self[word])
mean = np.array(mean).mean(axis=0)
metrics = distance(self.vectors, mean, metric=metric)
best = metrics.argsort()[::-1][:n + len(exclude)]
exclude_idx = [np.where(best == self.ix(word)) for word in exclude if self.ix(word) in best]
new_best = np.delete(best, exclude_idx)
best_metrics = metrics[new_best]
return new_best[:n], best_metrics[:n] | python | def analogy(self, pos, neg, n=10, metric="cosine"):
"""
Analogy similarity.
Parameters
----------
pos : list
neg : list
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity
Example
-------
`king - man + woman = queen` will be: `pos=['king', 'woman'], neg=['man']`
"""
exclude = pos + neg
pos = [(word, 1.0) for word in pos]
neg = [(word, -1.0) for word in neg]
mean = []
for word, direction in pos + neg:
mean.append(direction * self[word])
mean = np.array(mean).mean(axis=0)
metrics = distance(self.vectors, mean, metric=metric)
best = metrics.argsort()[::-1][:n + len(exclude)]
exclude_idx = [np.where(best == self.ix(word)) for word in exclude if self.ix(word) in best]
new_best = np.delete(best, exclude_idx)
best_metrics = metrics[new_best]
return new_best[:n], best_metrics[:n] | [
"def",
"analogy",
"(",
"self",
",",
"pos",
",",
"neg",
",",
"n",
"=",
"10",
",",
"metric",
"=",
"\"cosine\"",
")",
":",
"exclude",
"=",
"pos",
"+",
"neg",
"pos",
"=",
"[",
"(",
"word",
",",
"1.0",
")",
"for",
"word",
"in",
"pos",
"]",
"neg",
... | Analogy similarity.
Parameters
----------
pos : list
neg : list
Returns
-------
Tuple of 2 numpy.array:
1. position in self.vocab
2. cosine similarity
Example
-------
`king - man + woman = queen` will be: `pos=['king', 'woman'], neg=['man']` | [
"Analogy",
"similarity",
"."
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordvectors.py#L126-L160 | train | 220,352 |
danielfrg/word2vec | word2vec/wordvectors.py | WordVectors.from_binary | def from_binary(
cls,
fname,
vocab_unicode_size=78,
desired_vocab=None,
encoding="utf-8",
new_lines=True,
):
"""
Create a WordVectors class based on a word2vec binary file
Parameters
----------
fname : path to file
vocabUnicodeSize: the maximum string length (78, by default)
desired_vocab: if set any words that don't fall into this vocab will be droped
Returns
-------
WordVectors instance
"""
with open(fname, "rb") as fin:
# The first line has the vocab_size and the vector_size as text
header = fin.readline()
vocab_size, vector_size = list(map(int, header.split()))
vocab = np.empty(vocab_size, dtype="<U%s" % vocab_unicode_size)
vectors = np.empty((vocab_size, vector_size), dtype=np.float)
binary_len = np.dtype(np.float32).itemsize * vector_size
for i in range(vocab_size):
# read word
word = b""
while True:
ch = fin.read(1)
if ch == b" ":
break
word += ch
include = desired_vocab is None or word in desired_vocab
if include:
vocab[i] = word.decode(encoding)
# read vector
vector = np.fromstring(fin.read(binary_len), dtype=np.float32)
if include:
vectors[i] = unitvec(vector)
if new_lines:
fin.read(1) # newline char
if desired_vocab is not None:
vectors = vectors[vocab != "", :]
vocab = vocab[vocab != ""]
return cls(vocab=vocab, vectors=vectors) | python | def from_binary(
cls,
fname,
vocab_unicode_size=78,
desired_vocab=None,
encoding="utf-8",
new_lines=True,
):
"""
Create a WordVectors class based on a word2vec binary file
Parameters
----------
fname : path to file
vocabUnicodeSize: the maximum string length (78, by default)
desired_vocab: if set any words that don't fall into this vocab will be droped
Returns
-------
WordVectors instance
"""
with open(fname, "rb") as fin:
# The first line has the vocab_size and the vector_size as text
header = fin.readline()
vocab_size, vector_size = list(map(int, header.split()))
vocab = np.empty(vocab_size, dtype="<U%s" % vocab_unicode_size)
vectors = np.empty((vocab_size, vector_size), dtype=np.float)
binary_len = np.dtype(np.float32).itemsize * vector_size
for i in range(vocab_size):
# read word
word = b""
while True:
ch = fin.read(1)
if ch == b" ":
break
word += ch
include = desired_vocab is None or word in desired_vocab
if include:
vocab[i] = word.decode(encoding)
# read vector
vector = np.fromstring(fin.read(binary_len), dtype=np.float32)
if include:
vectors[i] = unitvec(vector)
if new_lines:
fin.read(1) # newline char
if desired_vocab is not None:
vectors = vectors[vocab != "", :]
vocab = vocab[vocab != ""]
return cls(vocab=vocab, vectors=vectors) | [
"def",
"from_binary",
"(",
"cls",
",",
"fname",
",",
"vocab_unicode_size",
"=",
"78",
",",
"desired_vocab",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"new_lines",
"=",
"True",
",",
")",
":",
"with",
"open",
"(",
"fname",
",",
"\"rb\"",
")",
... | Create a WordVectors class based on a word2vec binary file
Parameters
----------
fname : path to file
vocabUnicodeSize: the maximum string length (78, by default)
desired_vocab: if set any words that don't fall into this vocab will be droped
Returns
-------
WordVectors instance | [
"Create",
"a",
"WordVectors",
"class",
"based",
"on",
"a",
"word2vec",
"binary",
"file"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordvectors.py#L179-L230 | train | 220,353 |
danielfrg/word2vec | word2vec/wordvectors.py | WordVectors.from_text | def from_text(cls, fname, vocabUnicodeSize=78, desired_vocab=None, encoding="utf-8"):
"""
Create a WordVectors class based on a word2vec text file
Parameters
----------
fname : path to file
vocabUnicodeSize: the maximum string length (78, by default)
desired_vocab: if set, this will ignore any word and vector that
doesn't fall inside desired_vocab.
Returns
-------
WordVectors instance
"""
with open(fname, "rb") as fin:
header = fin.readline()
vocab_size, vector_size = list(map(int, header.split()))
vocab = np.empty(vocab_size, dtype="<U%s" % vocabUnicodeSize)
vectors = np.empty((vocab_size, vector_size), dtype=np.float)
for i, line in enumerate(fin):
line = line.decode(encoding).rstrip()
parts = line.split(" ")
word = parts[0]
include = desired_vocab is None or word in desired_vocab
if include:
vector = np.array(parts[1:], dtype=np.float)
vocab[i] = word
vectors[i] = unitvec(vector)
if desired_vocab is not None:
vectors = vectors[vocab != "", :]
vocab = vocab[vocab != ""]
return cls(vocab=vocab, vectors=vectors) | python | def from_text(cls, fname, vocabUnicodeSize=78, desired_vocab=None, encoding="utf-8"):
"""
Create a WordVectors class based on a word2vec text file
Parameters
----------
fname : path to file
vocabUnicodeSize: the maximum string length (78, by default)
desired_vocab: if set, this will ignore any word and vector that
doesn't fall inside desired_vocab.
Returns
-------
WordVectors instance
"""
with open(fname, "rb") as fin:
header = fin.readline()
vocab_size, vector_size = list(map(int, header.split()))
vocab = np.empty(vocab_size, dtype="<U%s" % vocabUnicodeSize)
vectors = np.empty((vocab_size, vector_size), dtype=np.float)
for i, line in enumerate(fin):
line = line.decode(encoding).rstrip()
parts = line.split(" ")
word = parts[0]
include = desired_vocab is None or word in desired_vocab
if include:
vector = np.array(parts[1:], dtype=np.float)
vocab[i] = word
vectors[i] = unitvec(vector)
if desired_vocab is not None:
vectors = vectors[vocab != "", :]
vocab = vocab[vocab != ""]
return cls(vocab=vocab, vectors=vectors) | [
"def",
"from_text",
"(",
"cls",
",",
"fname",
",",
"vocabUnicodeSize",
"=",
"78",
",",
"desired_vocab",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"with",
"open",
"(",
"fname",
",",
"\"rb\"",
")",
"as",
"fin",
":",
"header",
"=",
"fin",
... | Create a WordVectors class based on a word2vec text file
Parameters
----------
fname : path to file
vocabUnicodeSize: the maximum string length (78, by default)
desired_vocab: if set, this will ignore any word and vector that
doesn't fall inside desired_vocab.
Returns
-------
WordVectors instance | [
"Create",
"a",
"WordVectors",
"class",
"based",
"on",
"a",
"word2vec",
"text",
"file"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordvectors.py#L233-L267 | train | 220,354 |
danielfrg/word2vec | word2vec/wordvectors.py | WordVectors.from_mmap | def from_mmap(cls, fname):
"""
Create a WordVectors class from a memory map
Parameters
----------
fname : path to file
Returns
-------
WordVectors instance
"""
memmaped = joblib.load(fname, mmap_mode="r+")
return cls(vocab=memmaped.vocab, vectors=memmaped.vectors) | python | def from_mmap(cls, fname):
"""
Create a WordVectors class from a memory map
Parameters
----------
fname : path to file
Returns
-------
WordVectors instance
"""
memmaped = joblib.load(fname, mmap_mode="r+")
return cls(vocab=memmaped.vocab, vectors=memmaped.vectors) | [
"def",
"from_mmap",
"(",
"cls",
",",
"fname",
")",
":",
"memmaped",
"=",
"joblib",
".",
"load",
"(",
"fname",
",",
"mmap_mode",
"=",
"\"r+\"",
")",
"return",
"cls",
"(",
"vocab",
"=",
"memmaped",
".",
"vocab",
",",
"vectors",
"=",
"memmaped",
".",
"v... | Create a WordVectors class from a memory map
Parameters
----------
fname : path to file
Returns
-------
WordVectors instance | [
"Create",
"a",
"WordVectors",
"class",
"from",
"a",
"memory",
"map"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/wordvectors.py#L270-L283 | train | 220,355 |
danielfrg/word2vec | word2vec/utils.py | distance | def distance(a, b, metric="cosine"):
"""
Calculate distance between two vectors based on a Metric
Metrics:
1. cosine distance. Note that in word2vec all the norms are 1 so the dot product is the same as cosine distance
"""
if metric == "cosine":
return np.dot(a, b.T)
raise Exception("Unknown metric '{metric}'".format(metric=metric)) | python | def distance(a, b, metric="cosine"):
"""
Calculate distance between two vectors based on a Metric
Metrics:
1. cosine distance. Note that in word2vec all the norms are 1 so the dot product is the same as cosine distance
"""
if metric == "cosine":
return np.dot(a, b.T)
raise Exception("Unknown metric '{metric}'".format(metric=metric)) | [
"def",
"distance",
"(",
"a",
",",
"b",
",",
"metric",
"=",
"\"cosine\"",
")",
":",
"if",
"metric",
"==",
"\"cosine\"",
":",
"return",
"np",
".",
"dot",
"(",
"a",
",",
"b",
".",
"T",
")",
"raise",
"Exception",
"(",
"\"Unknown metric '{metric}'\"",
".",
... | Calculate distance between two vectors based on a Metric
Metrics:
1. cosine distance. Note that in word2vec all the norms are 1 so the dot product is the same as cosine distance | [
"Calculate",
"distance",
"between",
"two",
"vectors",
"based",
"on",
"a",
"Metric"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/utils.py#L8-L17 | train | 220,356 |
danielfrg/word2vec | word2vec/io.py | load | def load(fname, kind="auto", *args, **kwargs):
"""
Loads a word vectors file
"""
if kind == "auto":
if fname.endswith(".bin"):
kind = "bin"
elif fname.endswith(".txt"):
kind = "txt"
else:
raise Exception("Could not identify kind")
if kind == "bin":
return word2vec.WordVectors.from_binary(fname, *args, **kwargs)
elif kind == "txt":
return word2vec.WordVectors.from_text(fname, *args, **kwargs)
elif kind == "mmap":
return word2vec.WordVectors.from_mmap(fname, *args, **kwargs)
else:
raise Exception("Unknown kind") | python | def load(fname, kind="auto", *args, **kwargs):
"""
Loads a word vectors file
"""
if kind == "auto":
if fname.endswith(".bin"):
kind = "bin"
elif fname.endswith(".txt"):
kind = "txt"
else:
raise Exception("Could not identify kind")
if kind == "bin":
return word2vec.WordVectors.from_binary(fname, *args, **kwargs)
elif kind == "txt":
return word2vec.WordVectors.from_text(fname, *args, **kwargs)
elif kind == "mmap":
return word2vec.WordVectors.from_mmap(fname, *args, **kwargs)
else:
raise Exception("Unknown kind") | [
"def",
"load",
"(",
"fname",
",",
"kind",
"=",
"\"auto\"",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kind",
"==",
"\"auto\"",
":",
"if",
"fname",
".",
"endswith",
"(",
"\".bin\"",
")",
":",
"kind",
"=",
"\"bin\"",
"elif",
"fname",... | Loads a word vectors file | [
"Loads",
"a",
"word",
"vectors",
"file"
] | 762200acec2941a030abed69e946838af35eb2ae | https://github.com/danielfrg/word2vec/blob/762200acec2941a030abed69e946838af35eb2ae/word2vec/io.py#L4-L22 | train | 220,357 |
django-crispy-forms/django-crispy-forms | crispy_forms/templatetags/crispy_forms_tags.py | ForLoopSimulator.iterate | def iterate(self):
"""
Updates values as if we had iterated over the for
"""
self.counter += 1
self.counter0 += 1
self.revcounter -= 1
self.revcounter0 -= 1
self.first = False
self.last = (self.revcounter0 == self.len_values - 1) | python | def iterate(self):
"""
Updates values as if we had iterated over the for
"""
self.counter += 1
self.counter0 += 1
self.revcounter -= 1
self.revcounter0 -= 1
self.first = False
self.last = (self.revcounter0 == self.len_values - 1) | [
"def",
"iterate",
"(",
"self",
")",
":",
"self",
".",
"counter",
"+=",
"1",
"self",
".",
"counter0",
"+=",
"1",
"self",
".",
"revcounter",
"-=",
"1",
"self",
".",
"revcounter0",
"-=",
"1",
"self",
".",
"first",
"=",
"False",
"self",
".",
"last",
"=... | Updates values as if we had iterated over the for | [
"Updates",
"values",
"as",
"if",
"we",
"had",
"iterated",
"over",
"the",
"for"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/templatetags/crispy_forms_tags.py#L43-L52 | train | 220,358 |
django-crispy-forms/django-crispy-forms | crispy_forms/templatetags/crispy_forms_tags.py | BasicNode.get_render | def get_render(self, context):
"""
Returns a `Context` object with all the necessary stuff for rendering the form
:param context: `django.template.Context` variable holding the context for the node
`self.form` and `self.helper` are resolved into real Python objects resolving them
from the `context`. The `actual_form` can be a form or a formset. If it's a formset
`is_formset` is set to True. If the helper has a layout we use it, for rendering the
form or the formset's forms.
"""
# Nodes are not thread safe in multithreaded environments
# https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#thread-safety-considerations
if self not in context.render_context:
context.render_context[self] = (
template.Variable(self.form),
template.Variable(self.helper) if self.helper else None
)
form, helper = context.render_context[self]
actual_form = form.resolve(context)
if self.helper is not None:
helper = helper.resolve(context)
else:
# If the user names the helper within the form `helper` (standard), we use it
# This allows us to have simplified tag syntax: {% crispy form %}
helper = FormHelper() if not hasattr(actual_form, 'helper') else actual_form.helper
# use template_pack from helper, if defined
try:
if helper.template_pack:
self.template_pack = helper.template_pack
except AttributeError:
pass
self.actual_helper = helper
# We get the response dictionary
is_formset = isinstance(actual_form, BaseFormSet)
response_dict = self.get_response_dict(helper, context, is_formset)
node_context = context.__copy__()
node_context.update(response_dict)
final_context = node_context.__copy__()
# If we have a helper's layout we use it, for the form or the formset's forms
if helper and helper.layout:
if not is_formset:
actual_form.form_html = helper.render_layout(actual_form, node_context, template_pack=self.template_pack)
else:
forloop = ForLoopSimulator(actual_form)
helper.render_hidden_fields = True
for form in actual_form:
node_context.update({'forloop': forloop})
node_context.update({'formset_form': form})
form.form_html = helper.render_layout(form, node_context, template_pack=self.template_pack)
forloop.iterate()
if is_formset:
final_context['formset'] = actual_form
else:
final_context['form'] = actual_form
return final_context | python | def get_render(self, context):
"""
Returns a `Context` object with all the necessary stuff for rendering the form
:param context: `django.template.Context` variable holding the context for the node
`self.form` and `self.helper` are resolved into real Python objects resolving them
from the `context`. The `actual_form` can be a form or a formset. If it's a formset
`is_formset` is set to True. If the helper has a layout we use it, for rendering the
form or the formset's forms.
"""
# Nodes are not thread safe in multithreaded environments
# https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#thread-safety-considerations
if self not in context.render_context:
context.render_context[self] = (
template.Variable(self.form),
template.Variable(self.helper) if self.helper else None
)
form, helper = context.render_context[self]
actual_form = form.resolve(context)
if self.helper is not None:
helper = helper.resolve(context)
else:
# If the user names the helper within the form `helper` (standard), we use it
# This allows us to have simplified tag syntax: {% crispy form %}
helper = FormHelper() if not hasattr(actual_form, 'helper') else actual_form.helper
# use template_pack from helper, if defined
try:
if helper.template_pack:
self.template_pack = helper.template_pack
except AttributeError:
pass
self.actual_helper = helper
# We get the response dictionary
is_formset = isinstance(actual_form, BaseFormSet)
response_dict = self.get_response_dict(helper, context, is_formset)
node_context = context.__copy__()
node_context.update(response_dict)
final_context = node_context.__copy__()
# If we have a helper's layout we use it, for the form or the formset's forms
if helper and helper.layout:
if not is_formset:
actual_form.form_html = helper.render_layout(actual_form, node_context, template_pack=self.template_pack)
else:
forloop = ForLoopSimulator(actual_form)
helper.render_hidden_fields = True
for form in actual_form:
node_context.update({'forloop': forloop})
node_context.update({'formset_form': form})
form.form_html = helper.render_layout(form, node_context, template_pack=self.template_pack)
forloop.iterate()
if is_formset:
final_context['formset'] = actual_form
else:
final_context['form'] = actual_form
return final_context | [
"def",
"get_render",
"(",
"self",
",",
"context",
")",
":",
"# Nodes are not thread safe in multithreaded environments",
"# https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#thread-safety-considerations",
"if",
"self",
"not",
"in",
"context",
".",
"render_context",
... | Returns a `Context` object with all the necessary stuff for rendering the form
:param context: `django.template.Context` variable holding the context for the node
`self.form` and `self.helper` are resolved into real Python objects resolving them
from the `context`. The `actual_form` can be a form or a formset. If it's a formset
`is_formset` is set to True. If the helper has a layout we use it, for rendering the
form or the formset's forms. | [
"Returns",
"a",
"Context",
"object",
"with",
"all",
"the",
"necessary",
"stuff",
"for",
"rendering",
"the",
"form"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/templatetags/crispy_forms_tags.py#L71-L133 | train | 220,359 |
django-crispy-forms/django-crispy-forms | crispy_forms/templatetags/crispy_forms_utils.py | specialspaceless | def specialspaceless(parser, token):
"""
Removes whitespace between HTML tags, and introduces a whitespace
after buttons an inputs, necessary for Bootstrap to place them
correctly in the layout.
"""
nodelist = parser.parse(('endspecialspaceless',))
parser.delete_first_token()
return SpecialSpacelessNode(nodelist) | python | def specialspaceless(parser, token):
"""
Removes whitespace between HTML tags, and introduces a whitespace
after buttons an inputs, necessary for Bootstrap to place them
correctly in the layout.
"""
nodelist = parser.parse(('endspecialspaceless',))
parser.delete_first_token()
return SpecialSpacelessNode(nodelist) | [
"def",
"specialspaceless",
"(",
"parser",
",",
"token",
")",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endspecialspaceless'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"SpecialSpacelessNode",
"(",
"nodelist",
")"
] | Removes whitespace between HTML tags, and introduces a whitespace
after buttons an inputs, necessary for Bootstrap to place them
correctly in the layout. | [
"Removes",
"whitespace",
"between",
"HTML",
"tags",
"and",
"introduces",
"a",
"whitespace",
"after",
"buttons",
"an",
"inputs",
"necessary",
"for",
"Bootstrap",
"to",
"place",
"them",
"correctly",
"in",
"the",
"layout",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/templatetags/crispy_forms_utils.py#L38-L47 | train | 220,360 |
django-crispy-forms/django-crispy-forms | crispy_forms/bootstrap.py | ContainerHolder.first_container_with_errors | def first_container_with_errors(self, errors):
"""
Returns the first container with errors, otherwise returns None.
"""
for tab in self.fields:
errors_here = any(error in tab for error in errors)
if errors_here:
return tab
return None | python | def first_container_with_errors(self, errors):
"""
Returns the first container with errors, otherwise returns None.
"""
for tab in self.fields:
errors_here = any(error in tab for error in errors)
if errors_here:
return tab
return None | [
"def",
"first_container_with_errors",
"(",
"self",
",",
"errors",
")",
":",
"for",
"tab",
"in",
"self",
".",
"fields",
":",
"errors_here",
"=",
"any",
"(",
"error",
"in",
"tab",
"for",
"error",
"in",
"errors",
")",
"if",
"errors_here",
":",
"return",
"ta... | Returns the first container with errors, otherwise returns None. | [
"Returns",
"the",
"first",
"container",
"with",
"errors",
"otherwise",
"returns",
"None",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/bootstrap.py#L230-L238 | train | 220,361 |
django-crispy-forms/django-crispy-forms | crispy_forms/bootstrap.py | ContainerHolder.open_target_group_for_form | def open_target_group_for_form(self, form):
"""
Makes sure that the first group that should be open is open.
This is either the first group with errors or the first group
in the container, unless that first group was originally set to
active=False.
"""
target = self.first_container_with_errors(form.errors.keys())
if target is None:
target = self.fields[0]
if not getattr(target, '_active_originally_included', None):
target.active = True
return target
target.active = True
return target | python | def open_target_group_for_form(self, form):
"""
Makes sure that the first group that should be open is open.
This is either the first group with errors or the first group
in the container, unless that first group was originally set to
active=False.
"""
target = self.first_container_with_errors(form.errors.keys())
if target is None:
target = self.fields[0]
if not getattr(target, '_active_originally_included', None):
target.active = True
return target
target.active = True
return target | [
"def",
"open_target_group_for_form",
"(",
"self",
",",
"form",
")",
":",
"target",
"=",
"self",
".",
"first_container_with_errors",
"(",
"form",
".",
"errors",
".",
"keys",
"(",
")",
")",
"if",
"target",
"is",
"None",
":",
"target",
"=",
"self",
".",
"fi... | Makes sure that the first group that should be open is open.
This is either the first group with errors or the first group
in the container, unless that first group was originally set to
active=False. | [
"Makes",
"sure",
"that",
"the",
"first",
"group",
"that",
"should",
"be",
"open",
"is",
"open",
".",
"This",
"is",
"either",
"the",
"first",
"group",
"with",
"errors",
"or",
"the",
"first",
"group",
"in",
"the",
"container",
"unless",
"that",
"first",
"g... | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/bootstrap.py#L240-L255 | train | 220,362 |
django-crispy-forms/django-crispy-forms | crispy_forms/bootstrap.py | Tab.render_link | def render_link(self, template_pack=TEMPLATE_PACK, **kwargs):
"""
Render the link for the tab-pane. It must be called after render so css_class is updated
with active if needed.
"""
link_template = self.link_template % template_pack
return render_to_string(link_template, {'link': self}) | python | def render_link(self, template_pack=TEMPLATE_PACK, **kwargs):
"""
Render the link for the tab-pane. It must be called after render so css_class is updated
with active if needed.
"""
link_template = self.link_template % template_pack
return render_to_string(link_template, {'link': self}) | [
"def",
"render_link",
"(",
"self",
",",
"template_pack",
"=",
"TEMPLATE_PACK",
",",
"*",
"*",
"kwargs",
")",
":",
"link_template",
"=",
"self",
".",
"link_template",
"%",
"template_pack",
"return",
"render_to_string",
"(",
"link_template",
",",
"{",
"'link'",
... | Render the link for the tab-pane. It must be called after render so css_class is updated
with active if needed. | [
"Render",
"the",
"link",
"for",
"the",
"tab",
"-",
"pane",
".",
"It",
"must",
"be",
"called",
"after",
"render",
"so",
"css_class",
"is",
"updated",
"with",
"active",
"if",
"needed",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/bootstrap.py#L268-L274 | train | 220,363 |
django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.wrapped_object | def wrapped_object(self, LayoutClass, fields, *args, **kwargs):
"""
Returns a layout object of type `LayoutClass` with `args` and `kwargs` that
wraps `fields` inside.
"""
if args:
if isinstance(fields, list):
fields = tuple(fields)
else:
fields = (fields,)
if LayoutClass in self.args_first:
arguments = args + fields
else:
arguments = fields + args
return LayoutClass(*arguments, **kwargs)
else:
if isinstance(fields, list):
return LayoutClass(*fields, **kwargs)
else:
return LayoutClass(fields, **kwargs) | python | def wrapped_object(self, LayoutClass, fields, *args, **kwargs):
"""
Returns a layout object of type `LayoutClass` with `args` and `kwargs` that
wraps `fields` inside.
"""
if args:
if isinstance(fields, list):
fields = tuple(fields)
else:
fields = (fields,)
if LayoutClass in self.args_first:
arguments = args + fields
else:
arguments = fields + args
return LayoutClass(*arguments, **kwargs)
else:
if isinstance(fields, list):
return LayoutClass(*fields, **kwargs)
else:
return LayoutClass(fields, **kwargs) | [
"def",
"wrapped_object",
"(",
"self",
",",
"LayoutClass",
",",
"fields",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
":",
"if",
"isinstance",
"(",
"fields",
",",
"list",
")",
":",
"fields",
"=",
"tuple",
"(",
"fields",
")",
"... | Returns a layout object of type `LayoutClass` with `args` and `kwargs` that
wraps `fields` inside. | [
"Returns",
"a",
"layout",
"object",
"of",
"type",
"LayoutClass",
"with",
"args",
"and",
"kwargs",
"that",
"wraps",
"fields",
"inside",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L19-L40 | train | 220,364 |
django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.pre_map | def pre_map(self, function):
"""
Iterates over layout objects pointed in `self.slice` executing `function` on them.
It passes `function` penultimate layout object and the position where to find last one
"""
if isinstance(self.slice, slice):
for i in range(*self.slice.indices(len(self.layout.fields))):
function(self.layout, i)
elif isinstance(self.slice, list):
# A list of pointers Ex: [[[0, 0], 'div'], [[0, 2, 3], 'field_name']]
for pointer in self.slice:
position = pointer[0]
# If it's pointing first level
if len(position) == 1:
function(self.layout, position[-1])
else:
layout_object = self.layout.fields[position[0]]
for i in position[1:-1]:
layout_object = layout_object.fields[i]
try:
function(layout_object, position[-1])
except IndexError:
# We could avoid this exception, recalculating pointers.
# However this case is most of the time an undesired behavior
raise DynamicError("Trying to wrap a field within an already wrapped field, \
recheck your filter or layout") | python | def pre_map(self, function):
"""
Iterates over layout objects pointed in `self.slice` executing `function` on them.
It passes `function` penultimate layout object and the position where to find last one
"""
if isinstance(self.slice, slice):
for i in range(*self.slice.indices(len(self.layout.fields))):
function(self.layout, i)
elif isinstance(self.slice, list):
# A list of pointers Ex: [[[0, 0], 'div'], [[0, 2, 3], 'field_name']]
for pointer in self.slice:
position = pointer[0]
# If it's pointing first level
if len(position) == 1:
function(self.layout, position[-1])
else:
layout_object = self.layout.fields[position[0]]
for i in position[1:-1]:
layout_object = layout_object.fields[i]
try:
function(layout_object, position[-1])
except IndexError:
# We could avoid this exception, recalculating pointers.
# However this case is most of the time an undesired behavior
raise DynamicError("Trying to wrap a field within an already wrapped field, \
recheck your filter or layout") | [
"def",
"pre_map",
"(",
"self",
",",
"function",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"slice",
",",
"slice",
")",
":",
"for",
"i",
"in",
"range",
"(",
"*",
"self",
".",
"slice",
".",
"indices",
"(",
"len",
"(",
"self",
".",
"layout",
".... | Iterates over layout objects pointed in `self.slice` executing `function` on them.
It passes `function` penultimate layout object and the position where to find last one | [
"Iterates",
"over",
"layout",
"objects",
"pointed",
"in",
"self",
".",
"slice",
"executing",
"function",
"on",
"them",
".",
"It",
"passes",
"function",
"penultimate",
"layout",
"object",
"and",
"the",
"position",
"where",
"to",
"find",
"last",
"one"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L42-L70 | train | 220,365 |
django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.wrap | def wrap(self, LayoutClass, *args, **kwargs):
"""
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed.
"""
def wrap_object(layout_object, j):
layout_object.fields[j] = self.wrapped_object(
LayoutClass, layout_object.fields[j], *args, **kwargs
)
self.pre_map(wrap_object) | python | def wrap(self, LayoutClass, *args, **kwargs):
"""
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed.
"""
def wrap_object(layout_object, j):
layout_object.fields[j] = self.wrapped_object(
LayoutClass, layout_object.fields[j], *args, **kwargs
)
self.pre_map(wrap_object) | [
"def",
"wrap",
"(",
"self",
",",
"LayoutClass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrap_object",
"(",
"layout_object",
",",
"j",
")",
":",
"layout_object",
".",
"fields",
"[",
"j",
"]",
"=",
"self",
".",
"wrapped_object",
"(... | Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed. | [
"Wraps",
"every",
"layout",
"object",
"pointed",
"in",
"self",
".",
"slice",
"under",
"a",
"LayoutClass",
"instance",
"with",
"args",
"and",
"kwargs",
"passed",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L72-L82 | train | 220,366 |
django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.wrap_once | def wrap_once(self, LayoutClass, *args, **kwargs):
"""
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed, unless layout object's parent is already a subclass of
`LayoutClass`.
"""
def wrap_object_once(layout_object, j):
if not isinstance(layout_object, LayoutClass):
layout_object.fields[j] = self.wrapped_object(
LayoutClass, layout_object.fields[j], *args, **kwargs
)
self.pre_map(wrap_object_once) | python | def wrap_once(self, LayoutClass, *args, **kwargs):
"""
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed, unless layout object's parent is already a subclass of
`LayoutClass`.
"""
def wrap_object_once(layout_object, j):
if not isinstance(layout_object, LayoutClass):
layout_object.fields[j] = self.wrapped_object(
LayoutClass, layout_object.fields[j], *args, **kwargs
)
self.pre_map(wrap_object_once) | [
"def",
"wrap_once",
"(",
"self",
",",
"LayoutClass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrap_object_once",
"(",
"layout_object",
",",
"j",
")",
":",
"if",
"not",
"isinstance",
"(",
"layout_object",
",",
"LayoutClass",
")",
":",
... | Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed, unless layout object's parent is already a subclass of
`LayoutClass`. | [
"Wraps",
"every",
"layout",
"object",
"pointed",
"in",
"self",
".",
"slice",
"under",
"a",
"LayoutClass",
"instance",
"with",
"args",
"and",
"kwargs",
"passed",
"unless",
"layout",
"object",
"s",
"parent",
"is",
"already",
"a",
"subclass",
"of",
"LayoutClass",... | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L84-L96 | train | 220,367 |
django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.wrap_together | def wrap_together(self, LayoutClass, *args, **kwargs):
"""
Wraps all layout objects pointed in `self.slice` together under a `LayoutClass`
instance with `args` and `kwargs` passed.
"""
if isinstance(self.slice, slice):
# The start of the slice is replaced
start = self.slice.start if self.slice.start is not None else 0
self.layout.fields[start] = self.wrapped_object(
LayoutClass, self.layout.fields[self.slice], *args, **kwargs
)
# The rest of places of the slice are removed, as they are included in the previous
for i in reversed(range(*self.slice.indices(len(self.layout.fields)))):
if i != start:
del self.layout.fields[i]
elif isinstance(self.slice, list):
raise DynamicError("wrap_together doesn't work with filter, only with [] operator") | python | def wrap_together(self, LayoutClass, *args, **kwargs):
"""
Wraps all layout objects pointed in `self.slice` together under a `LayoutClass`
instance with `args` and `kwargs` passed.
"""
if isinstance(self.slice, slice):
# The start of the slice is replaced
start = self.slice.start if self.slice.start is not None else 0
self.layout.fields[start] = self.wrapped_object(
LayoutClass, self.layout.fields[self.slice], *args, **kwargs
)
# The rest of places of the slice are removed, as they are included in the previous
for i in reversed(range(*self.slice.indices(len(self.layout.fields)))):
if i != start:
del self.layout.fields[i]
elif isinstance(self.slice, list):
raise DynamicError("wrap_together doesn't work with filter, only with [] operator") | [
"def",
"wrap_together",
"(",
"self",
",",
"LayoutClass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"slice",
",",
"slice",
")",
":",
"# The start of the slice is replaced",
"start",
"=",
"self",
".",
"slice",... | Wraps all layout objects pointed in `self.slice` together under a `LayoutClass`
instance with `args` and `kwargs` passed. | [
"Wraps",
"all",
"layout",
"objects",
"pointed",
"in",
"self",
".",
"slice",
"together",
"under",
"a",
"LayoutClass",
"instance",
"with",
"args",
"and",
"kwargs",
"passed",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L98-L116 | train | 220,368 |
django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.map | def map(self, function):
"""
Iterates over layout objects pointed in `self.slice` executing `function` on them
It passes `function` last layout object
"""
if isinstance(self.slice, slice):
for i in range(*self.slice.indices(len(self.layout.fields))):
function(self.layout.fields[i])
elif isinstance(self.slice, list):
# A list of pointers Ex: [[[0, 0], 'div'], [[0, 2, 3], 'field_name']]
for pointer in self.slice:
position = pointer[0]
layout_object = self.layout.fields[position[0]]
for i in position[1:]:
previous_layout_object = layout_object
layout_object = layout_object.fields[i]
# If update_attrs is applied to a string, we call to its wrapping layout object
if (
function.__name__ == 'update_attrs'
and isinstance(layout_object, string_types)
):
function(previous_layout_object)
else:
function(layout_object) | python | def map(self, function):
"""
Iterates over layout objects pointed in `self.slice` executing `function` on them
It passes `function` last layout object
"""
if isinstance(self.slice, slice):
for i in range(*self.slice.indices(len(self.layout.fields))):
function(self.layout.fields[i])
elif isinstance(self.slice, list):
# A list of pointers Ex: [[[0, 0], 'div'], [[0, 2, 3], 'field_name']]
for pointer in self.slice:
position = pointer[0]
layout_object = self.layout.fields[position[0]]
for i in position[1:]:
previous_layout_object = layout_object
layout_object = layout_object.fields[i]
# If update_attrs is applied to a string, we call to its wrapping layout object
if (
function.__name__ == 'update_attrs'
and isinstance(layout_object, string_types)
):
function(previous_layout_object)
else:
function(layout_object) | [
"def",
"map",
"(",
"self",
",",
"function",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"slice",
",",
"slice",
")",
":",
"for",
"i",
"in",
"range",
"(",
"*",
"self",
".",
"slice",
".",
"indices",
"(",
"len",
"(",
"self",
".",
"layout",
".",
... | Iterates over layout objects pointed in `self.slice` executing `function` on them
It passes `function` last layout object | [
"Iterates",
"over",
"layout",
"objects",
"pointed",
"in",
"self",
".",
"slice",
"executing",
"function",
"on",
"them",
"It",
"passes",
"function",
"last",
"layout",
"object"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L118-L144 | train | 220,369 |
django-crispy-forms/django-crispy-forms | crispy_forms/layout_slice.py | LayoutSlice.update_attributes | def update_attributes(self, **original_kwargs):
"""
Updates attributes of every layout object pointed in `self.slice` using kwargs
"""
def update_attrs(layout_object):
kwargs = original_kwargs.copy()
if hasattr(layout_object, 'attrs'):
if 'css_class' in kwargs:
if 'class' in layout_object.attrs:
layout_object.attrs['class'] += " %s" % kwargs.pop('css_class')
else:
layout_object.attrs['class'] = kwargs.pop('css_class')
layout_object.attrs.update(kwargs)
self.map(update_attrs) | python | def update_attributes(self, **original_kwargs):
"""
Updates attributes of every layout object pointed in `self.slice` using kwargs
"""
def update_attrs(layout_object):
kwargs = original_kwargs.copy()
if hasattr(layout_object, 'attrs'):
if 'css_class' in kwargs:
if 'class' in layout_object.attrs:
layout_object.attrs['class'] += " %s" % kwargs.pop('css_class')
else:
layout_object.attrs['class'] = kwargs.pop('css_class')
layout_object.attrs.update(kwargs)
self.map(update_attrs) | [
"def",
"update_attributes",
"(",
"self",
",",
"*",
"*",
"original_kwargs",
")",
":",
"def",
"update_attrs",
"(",
"layout_object",
")",
":",
"kwargs",
"=",
"original_kwargs",
".",
"copy",
"(",
")",
"if",
"hasattr",
"(",
"layout_object",
",",
"'attrs'",
")",
... | Updates attributes of every layout object pointed in `self.slice` using kwargs | [
"Updates",
"attributes",
"of",
"every",
"layout",
"object",
"pointed",
"in",
"self",
".",
"slice",
"using",
"kwargs"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/layout_slice.py#L146-L160 | train | 220,370 |
django-crispy-forms/django-crispy-forms | crispy_forms/helper.py | DynamicLayoutHandler.all | def all(self):
"""
Returns all layout objects of first level of depth
"""
self._check_layout()
return LayoutSlice(self.layout, slice(0, len(self.layout.fields), 1)) | python | def all(self):
"""
Returns all layout objects of first level of depth
"""
self._check_layout()
return LayoutSlice(self.layout, slice(0, len(self.layout.fields), 1)) | [
"def",
"all",
"(",
"self",
")",
":",
"self",
".",
"_check_layout",
"(",
")",
"return",
"LayoutSlice",
"(",
"self",
".",
"layout",
",",
"slice",
"(",
"0",
",",
"len",
"(",
"self",
".",
"layout",
".",
"fields",
")",
",",
"1",
")",
")"
] | Returns all layout objects of first level of depth | [
"Returns",
"all",
"layout",
"objects",
"of",
"first",
"level",
"of",
"depth"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/helper.py#L31-L36 | train | 220,371 |
django-crispy-forms/django-crispy-forms | crispy_forms/helper.py | DynamicLayoutHandler.filter | def filter(self, *LayoutClasses, **kwargs):
"""
Returns a LayoutSlice pointing to layout objects of type `LayoutClass`
"""
self._check_layout()
max_level = kwargs.pop('max_level', 0)
greedy = kwargs.pop('greedy', False)
filtered_layout_objects = self.layout.get_layout_objects(LayoutClasses, max_level=max_level, greedy=greedy)
return LayoutSlice(self.layout, filtered_layout_objects) | python | def filter(self, *LayoutClasses, **kwargs):
"""
Returns a LayoutSlice pointing to layout objects of type `LayoutClass`
"""
self._check_layout()
max_level = kwargs.pop('max_level', 0)
greedy = kwargs.pop('greedy', False)
filtered_layout_objects = self.layout.get_layout_objects(LayoutClasses, max_level=max_level, greedy=greedy)
return LayoutSlice(self.layout, filtered_layout_objects) | [
"def",
"filter",
"(",
"self",
",",
"*",
"LayoutClasses",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_layout",
"(",
")",
"max_level",
"=",
"kwargs",
".",
"pop",
"(",
"'max_level'",
",",
"0",
")",
"greedy",
"=",
"kwargs",
".",
"pop",
"(",
... | Returns a LayoutSlice pointing to layout objects of type `LayoutClass` | [
"Returns",
"a",
"LayoutSlice",
"pointing",
"to",
"layout",
"objects",
"of",
"type",
"LayoutClass"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/helper.py#L38-L47 | train | 220,372 |
django-crispy-forms/django-crispy-forms | crispy_forms/helper.py | DynamicLayoutHandler.filter_by_widget | def filter_by_widget(self, widget_type):
"""
Returns a LayoutSlice pointing to fields with widgets of `widget_type`
"""
self._check_layout_and_form()
layout_field_names = self.layout.get_field_names()
# Let's filter all fields with widgets like widget_type
filtered_fields = []
for pointer in layout_field_names:
if isinstance(self.form.fields[pointer[1]].widget, widget_type):
filtered_fields.append(pointer)
return LayoutSlice(self.layout, filtered_fields) | python | def filter_by_widget(self, widget_type):
"""
Returns a LayoutSlice pointing to fields with widgets of `widget_type`
"""
self._check_layout_and_form()
layout_field_names = self.layout.get_field_names()
# Let's filter all fields with widgets like widget_type
filtered_fields = []
for pointer in layout_field_names:
if isinstance(self.form.fields[pointer[1]].widget, widget_type):
filtered_fields.append(pointer)
return LayoutSlice(self.layout, filtered_fields) | [
"def",
"filter_by_widget",
"(",
"self",
",",
"widget_type",
")",
":",
"self",
".",
"_check_layout_and_form",
"(",
")",
"layout_field_names",
"=",
"self",
".",
"layout",
".",
"get_field_names",
"(",
")",
"# Let's filter all fields with widgets like widget_type",
"filtere... | Returns a LayoutSlice pointing to fields with widgets of `widget_type` | [
"Returns",
"a",
"LayoutSlice",
"pointing",
"to",
"fields",
"with",
"widgets",
"of",
"widget_type"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/helper.py#L49-L62 | train | 220,373 |
django-crispy-forms/django-crispy-forms | crispy_forms/helper.py | FormHelper.get_attributes | def get_attributes(self, template_pack=TEMPLATE_PACK):
"""
Used by crispy_forms_tags to get helper attributes
"""
items = {
'form_method': self.form_method.strip(),
'form_tag': self.form_tag,
'form_style': self.form_style.strip(),
'form_show_errors': self.form_show_errors,
'help_text_inline': self.help_text_inline,
'error_text_inline': self.error_text_inline,
'html5_required': self.html5_required,
'form_show_labels': self.form_show_labels,
'disable_csrf': self.disable_csrf,
'label_class': self.label_class,
'field_class': self.field_class,
'include_media': self.include_media
}
if template_pack == 'bootstrap4':
bootstrap_size_match = re.findall('col-(xl|lg|md|sm)-(\d+)', self.label_class)
if bootstrap_size_match:
if template_pack == 'bootstrap4':
offset_pattern = 'offset-%s-%s'
else:
offset_pattern = 'col-%s-offset-%s'
items['bootstrap_checkbox_offsets'] = [offset_pattern % m for m in bootstrap_size_match]
else:
bootstrap_size_match = re.findall('col-(lg|md|sm|xs)-(\d+)', self.label_class)
if bootstrap_size_match:
if template_pack == 'bootstrap4':
offset_pattern = 'offset-%s-%s'
else:
offset_pattern = 'col-%s-offset-%s'
items['bootstrap_checkbox_offsets'] = [offset_pattern % m for m in bootstrap_size_match]
items['attrs'] = {}
if self.attrs:
items['attrs'] = self.attrs.copy()
if self.form_action:
items['attrs']['action'] = self.form_action.strip()
if self.form_id:
items['attrs']['id'] = self.form_id.strip()
if self.form_class:
# uni_form TEMPLATE PACK has a uniForm class by default
if template_pack == 'uni_form':
items['attrs']['class'] = "uniForm %s" % self.form_class.strip()
else:
items['attrs']['class'] = self.form_class.strip()
else:
if template_pack == 'uni_form':
items['attrs']['class'] = self.attrs.get('class', '') + " uniForm"
if self.form_group_wrapper_class:
items['attrs']['form_group_wrapper_class'] = self.form_group_wrapper_class
items['flat_attrs'] = flatatt(items['attrs'])
if self.inputs:
items['inputs'] = self.inputs
if self.form_error_title:
items['form_error_title'] = self.form_error_title.strip()
if self.formset_error_title:
items['formset_error_title'] = self.formset_error_title.strip()
for attribute_name, value in self.__dict__.items():
if attribute_name not in items and attribute_name not in ['layout', 'inputs'] and not attribute_name.startswith('_'):
items[attribute_name] = value
return items | python | def get_attributes(self, template_pack=TEMPLATE_PACK):
"""
Used by crispy_forms_tags to get helper attributes
"""
items = {
'form_method': self.form_method.strip(),
'form_tag': self.form_tag,
'form_style': self.form_style.strip(),
'form_show_errors': self.form_show_errors,
'help_text_inline': self.help_text_inline,
'error_text_inline': self.error_text_inline,
'html5_required': self.html5_required,
'form_show_labels': self.form_show_labels,
'disable_csrf': self.disable_csrf,
'label_class': self.label_class,
'field_class': self.field_class,
'include_media': self.include_media
}
if template_pack == 'bootstrap4':
bootstrap_size_match = re.findall('col-(xl|lg|md|sm)-(\d+)', self.label_class)
if bootstrap_size_match:
if template_pack == 'bootstrap4':
offset_pattern = 'offset-%s-%s'
else:
offset_pattern = 'col-%s-offset-%s'
items['bootstrap_checkbox_offsets'] = [offset_pattern % m for m in bootstrap_size_match]
else:
bootstrap_size_match = re.findall('col-(lg|md|sm|xs)-(\d+)', self.label_class)
if bootstrap_size_match:
if template_pack == 'bootstrap4':
offset_pattern = 'offset-%s-%s'
else:
offset_pattern = 'col-%s-offset-%s'
items['bootstrap_checkbox_offsets'] = [offset_pattern % m for m in bootstrap_size_match]
items['attrs'] = {}
if self.attrs:
items['attrs'] = self.attrs.copy()
if self.form_action:
items['attrs']['action'] = self.form_action.strip()
if self.form_id:
items['attrs']['id'] = self.form_id.strip()
if self.form_class:
# uni_form TEMPLATE PACK has a uniForm class by default
if template_pack == 'uni_form':
items['attrs']['class'] = "uniForm %s" % self.form_class.strip()
else:
items['attrs']['class'] = self.form_class.strip()
else:
if template_pack == 'uni_form':
items['attrs']['class'] = self.attrs.get('class', '') + " uniForm"
if self.form_group_wrapper_class:
items['attrs']['form_group_wrapper_class'] = self.form_group_wrapper_class
items['flat_attrs'] = flatatt(items['attrs'])
if self.inputs:
items['inputs'] = self.inputs
if self.form_error_title:
items['form_error_title'] = self.form_error_title.strip()
if self.formset_error_title:
items['formset_error_title'] = self.formset_error_title.strip()
for attribute_name, value in self.__dict__.items():
if attribute_name not in items and attribute_name not in ['layout', 'inputs'] and not attribute_name.startswith('_'):
items[attribute_name] = value
return items | [
"def",
"get_attributes",
"(",
"self",
",",
"template_pack",
"=",
"TEMPLATE_PACK",
")",
":",
"items",
"=",
"{",
"'form_method'",
":",
"self",
".",
"form_method",
".",
"strip",
"(",
")",
",",
"'form_tag'",
":",
"self",
".",
"form_tag",
",",
"'form_style'",
"... | Used by crispy_forms_tags to get helper attributes | [
"Used",
"by",
"crispy_forms_tags",
"to",
"get",
"helper",
"attributes"
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/helper.py#L353-L421 | train | 220,374 |
django-crispy-forms/django-crispy-forms | crispy_forms/utils.py | flatatt | def flatatt(attrs):
"""
Convert a dictionary of attributes to a single string.
Passed attributes are redirected to `django.forms.utils.flatatt()`
with replaced "_" (underscores) by "-" (dashes) in their names.
"""
return _flatatt({k.replace('_', '-'): v for k, v in attrs.items()}) | python | def flatatt(attrs):
"""
Convert a dictionary of attributes to a single string.
Passed attributes are redirected to `django.forms.utils.flatatt()`
with replaced "_" (underscores) by "-" (dashes) in their names.
"""
return _flatatt({k.replace('_', '-'): v for k, v in attrs.items()}) | [
"def",
"flatatt",
"(",
"attrs",
")",
":",
"return",
"_flatatt",
"(",
"{",
"k",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"items",
"(",
")",
"}",
")"
] | Convert a dictionary of attributes to a single string.
Passed attributes are redirected to `django.forms.utils.flatatt()`
with replaced "_" (underscores) by "-" (dashes) in their names. | [
"Convert",
"a",
"dictionary",
"of",
"attributes",
"to",
"a",
"single",
"string",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/utils.py#L153-L160 | train | 220,375 |
django-crispy-forms/django-crispy-forms | crispy_forms/utils.py | render_crispy_form | def render_crispy_form(form, helper=None, context=None):
"""
Renders a form and returns its HTML output.
This function wraps the template logic in a function easy to use in a Django view.
"""
from crispy_forms.templatetags.crispy_forms_tags import CrispyFormNode
if helper is not None:
node = CrispyFormNode('form', 'helper')
else:
node = CrispyFormNode('form', None)
node_context = Context(context)
node_context.update({
'form': form,
'helper': helper
})
return node.render(node_context) | python | def render_crispy_form(form, helper=None, context=None):
"""
Renders a form and returns its HTML output.
This function wraps the template logic in a function easy to use in a Django view.
"""
from crispy_forms.templatetags.crispy_forms_tags import CrispyFormNode
if helper is not None:
node = CrispyFormNode('form', 'helper')
else:
node = CrispyFormNode('form', None)
node_context = Context(context)
node_context.update({
'form': form,
'helper': helper
})
return node.render(node_context) | [
"def",
"render_crispy_form",
"(",
"form",
",",
"helper",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"from",
"crispy_forms",
".",
"templatetags",
".",
"crispy_forms_tags",
"import",
"CrispyFormNode",
"if",
"helper",
"is",
"not",
"None",
":",
"node",
... | Renders a form and returns its HTML output.
This function wraps the template logic in a function easy to use in a Django view. | [
"Renders",
"a",
"form",
"and",
"returns",
"its",
"HTML",
"output",
"."
] | cd476927a756133c667c199bb12120f877bf6b7e | https://github.com/django-crispy-forms/django-crispy-forms/blob/cd476927a756133c667c199bb12120f877bf6b7e/crispy_forms/utils.py#L163-L182 | train | 220,376 |
moderngl/moderngl | moderngl/vertex_array.py | VertexArray.bind | def bind(self, attribute, cls, buffer, fmt, *, offset=0, stride=0, divisor=0, normalize=False) -> None:
'''
Bind individual attributes to buffers.
Args:
location (int): The attribute location.
cls (str): The attribute class. Valid values are ``f``, ``i`` or ``d``.
buffer (Buffer): The buffer.
format (str): The buffer format.
Keyword Args:
offset (int): The offset.
stride (int): The stride.
divisor (int): The divisor.
normalize (bool): The normalize parameter, if applicable.
'''
self.mglo.bind(attribute, cls, buffer.mglo, fmt, offset, stride, divisor, normalize) | python | def bind(self, attribute, cls, buffer, fmt, *, offset=0, stride=0, divisor=0, normalize=False) -> None:
'''
Bind individual attributes to buffers.
Args:
location (int): The attribute location.
cls (str): The attribute class. Valid values are ``f``, ``i`` or ``d``.
buffer (Buffer): The buffer.
format (str): The buffer format.
Keyword Args:
offset (int): The offset.
stride (int): The stride.
divisor (int): The divisor.
normalize (bool): The normalize parameter, if applicable.
'''
self.mglo.bind(attribute, cls, buffer.mglo, fmt, offset, stride, divisor, normalize) | [
"def",
"bind",
"(",
"self",
",",
"attribute",
",",
"cls",
",",
"buffer",
",",
"fmt",
",",
"*",
",",
"offset",
"=",
"0",
",",
"stride",
"=",
"0",
",",
"divisor",
"=",
"0",
",",
"normalize",
"=",
"False",
")",
"->",
"None",
":",
"self",
".",
"mgl... | Bind individual attributes to buffers.
Args:
location (int): The attribute location.
cls (str): The attribute class. Valid values are ``f``, ``i`` or ``d``.
buffer (Buffer): The buffer.
format (str): The buffer format.
Keyword Args:
offset (int): The offset.
stride (int): The stride.
divisor (int): The divisor.
normalize (bool): The normalize parameter, if applicable. | [
"Bind",
"individual",
"attributes",
"to",
"buffers",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/vertex_array.py#L173-L190 | train | 220,377 |
moderngl/moderngl | examples/08_compute_shader.py | source | def source(uri, consts):
''' read gl code '''
with open(uri, 'r') as fp:
content = fp.read()
# feed constant values
for key, value in consts.items():
content = content.replace(f"%%{key}%%", str(value))
return content | python | def source(uri, consts):
''' read gl code '''
with open(uri, 'r') as fp:
content = fp.read()
# feed constant values
for key, value in consts.items():
content = content.replace(f"%%{key}%%", str(value))
return content | [
"def",
"source",
"(",
"uri",
",",
"consts",
")",
":",
"with",
"open",
"(",
"uri",
",",
"'r'",
")",
"as",
"fp",
":",
"content",
"=",
"fp",
".",
"read",
"(",
")",
"# feed constant values",
"for",
"key",
",",
"value",
"in",
"consts",
".",
"items",
"("... | read gl code | [
"read",
"gl",
"code"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/08_compute_shader.py#L17-L25 | train | 220,378 |
moderngl/moderngl | moderngl/context.py | create_standalone_context | def create_standalone_context(require=None, **settings) -> 'Context':
'''
Create a standalone ModernGL context.
Example::
# Create a context with highest possible supported version
ctx = moderngl.create_context()
# Require at least OpenGL 4.3
ctx = moderngl.create_context(require=430)
Keyword Arguments:
require (int): OpenGL version code.
Returns:
:py:class:`Context` object
'''
backend = os.environ.get('MODERNGL_BACKEND')
if backend is not None:
settings['backend'] = backend
ctx = Context.__new__(Context)
ctx.mglo, ctx.version_code = mgl.create_standalone_context(settings)
ctx._screen = None
ctx.fbo = None
ctx._info = None
ctx.extra = None
if require is not None and ctx.version_code < require:
raise ValueError('Requested OpenGL version {}, got version {}'.format(
require, ctx.version_code))
return ctx | python | def create_standalone_context(require=None, **settings) -> 'Context':
'''
Create a standalone ModernGL context.
Example::
# Create a context with highest possible supported version
ctx = moderngl.create_context()
# Require at least OpenGL 4.3
ctx = moderngl.create_context(require=430)
Keyword Arguments:
require (int): OpenGL version code.
Returns:
:py:class:`Context` object
'''
backend = os.environ.get('MODERNGL_BACKEND')
if backend is not None:
settings['backend'] = backend
ctx = Context.__new__(Context)
ctx.mglo, ctx.version_code = mgl.create_standalone_context(settings)
ctx._screen = None
ctx.fbo = None
ctx._info = None
ctx.extra = None
if require is not None and ctx.version_code < require:
raise ValueError('Requested OpenGL version {}, got version {}'.format(
require, ctx.version_code))
return ctx | [
"def",
"create_standalone_context",
"(",
"require",
"=",
"None",
",",
"*",
"*",
"settings",
")",
"->",
"'Context'",
":",
"backend",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'MODERNGL_BACKEND'",
")",
"if",
"backend",
"is",
"not",
"None",
":",
"settings"... | Create a standalone ModernGL context.
Example::
# Create a context with highest possible supported version
ctx = moderngl.create_context()
# Require at least OpenGL 4.3
ctx = moderngl.create_context(require=430)
Keyword Arguments:
require (int): OpenGL version code.
Returns:
:py:class:`Context` object | [
"Create",
"a",
"standalone",
"ModernGL",
"context",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L1135-L1169 | train | 220,379 |
moderngl/moderngl | moderngl/context.py | Context.copy_buffer | def copy_buffer(self, dst, src, size=-1, *, read_offset=0, write_offset=0) -> None:
'''
Copy buffer content.
Args:
dst (Buffer): The destination buffer.
src (Buffer): The source buffer.
size (int): The number of bytes to copy.
Keyword Args:
read_offset (int): The read offset.
write_offset (int): The write offset.
'''
self.mglo.copy_buffer(dst.mglo, src.mglo, size, read_offset, write_offset) | python | def copy_buffer(self, dst, src, size=-1, *, read_offset=0, write_offset=0) -> None:
'''
Copy buffer content.
Args:
dst (Buffer): The destination buffer.
src (Buffer): The source buffer.
size (int): The number of bytes to copy.
Keyword Args:
read_offset (int): The read offset.
write_offset (int): The write offset.
'''
self.mglo.copy_buffer(dst.mglo, src.mglo, size, read_offset, write_offset) | [
"def",
"copy_buffer",
"(",
"self",
",",
"dst",
",",
"src",
",",
"size",
"=",
"-",
"1",
",",
"*",
",",
"read_offset",
"=",
"0",
",",
"write_offset",
"=",
"0",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"copy_buffer",
"(",
"dst",
".",
"mglo"... | Copy buffer content.
Args:
dst (Buffer): The destination buffer.
src (Buffer): The source buffer.
size (int): The number of bytes to copy.
Keyword Args:
read_offset (int): The read offset.
write_offset (int): The write offset. | [
"Copy",
"buffer",
"content",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L505-L519 | train | 220,380 |
moderngl/moderngl | moderngl/context.py | Context.copy_framebuffer | def copy_framebuffer(self, dst, src) -> None:
'''
Copy framebuffer content.
Use this method to:
- blit framebuffers.
- copy framebuffer content into a texture.
- downsample framebuffers. (it will allow to read the framebuffer's content)
- downsample a framebuffer directly to a texture.
Args:
dst (Framebuffer or Texture): Destination framebuffer or texture.
src (Framebuffer): Source framebuffer.
'''
self.mglo.copy_framebuffer(dst.mglo, src.mglo) | python | def copy_framebuffer(self, dst, src) -> None:
'''
Copy framebuffer content.
Use this method to:
- blit framebuffers.
- copy framebuffer content into a texture.
- downsample framebuffers. (it will allow to read the framebuffer's content)
- downsample a framebuffer directly to a texture.
Args:
dst (Framebuffer or Texture): Destination framebuffer or texture.
src (Framebuffer): Source framebuffer.
'''
self.mglo.copy_framebuffer(dst.mglo, src.mglo) | [
"def",
"copy_framebuffer",
"(",
"self",
",",
"dst",
",",
"src",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"copy_framebuffer",
"(",
"dst",
".",
"mglo",
",",
"src",
".",
"mglo",
")"
] | Copy framebuffer content.
Use this method to:
- blit framebuffers.
- copy framebuffer content into a texture.
- downsample framebuffers. (it will allow to read the framebuffer's content)
- downsample a framebuffer directly to a texture.
Args:
dst (Framebuffer or Texture): Destination framebuffer or texture.
src (Framebuffer): Source framebuffer. | [
"Copy",
"framebuffer",
"content",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L521-L537 | train | 220,381 |
moderngl/moderngl | moderngl/context.py | Context.detect_framebuffer | def detect_framebuffer(self, glo=None) -> 'Framebuffer':
'''
Detect framebuffer.
Args:
glo (int): Framebuffer object.
Returns:
:py:class:`Framebuffer` object
'''
res = Framebuffer.__new__(Framebuffer)
res.mglo, res._size, res._samples, res._glo = self.mglo.detect_framebuffer(glo)
res._color_attachments = None
res._depth_attachment = None
res.ctx = self
res.extra = None
return res | python | def detect_framebuffer(self, glo=None) -> 'Framebuffer':
'''
Detect framebuffer.
Args:
glo (int): Framebuffer object.
Returns:
:py:class:`Framebuffer` object
'''
res = Framebuffer.__new__(Framebuffer)
res.mglo, res._size, res._samples, res._glo = self.mglo.detect_framebuffer(glo)
res._color_attachments = None
res._depth_attachment = None
res.ctx = self
res.extra = None
return res | [
"def",
"detect_framebuffer",
"(",
"self",
",",
"glo",
"=",
"None",
")",
"->",
"'Framebuffer'",
":",
"res",
"=",
"Framebuffer",
".",
"__new__",
"(",
"Framebuffer",
")",
"res",
".",
"mglo",
",",
"res",
".",
"_size",
",",
"res",
".",
"_samples",
",",
"res... | Detect framebuffer.
Args:
glo (int): Framebuffer object.
Returns:
:py:class:`Framebuffer` object | [
"Detect",
"framebuffer",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L539-L556 | train | 220,382 |
moderngl/moderngl | moderngl/context.py | Context.core_profile_check | def core_profile_check(self) -> None:
'''
Core profile check.
FOR DEBUG PURPOSES ONLY
'''
profile_mask = self.info['GL_CONTEXT_PROFILE_MASK']
if profile_mask != 1:
warnings.warn('The window should request a CORE OpenGL profile')
version_code = self.version_code
if not version_code:
major, minor = map(int, self.info['GL_VERSION'].split('.', 2)[:2])
version_code = major * 100 + minor * 10
if version_code < 330:
warnings.warn('The window should support OpenGL 3.3+ (version_code=%d)' % version_code) | python | def core_profile_check(self) -> None:
'''
Core profile check.
FOR DEBUG PURPOSES ONLY
'''
profile_mask = self.info['GL_CONTEXT_PROFILE_MASK']
if profile_mask != 1:
warnings.warn('The window should request a CORE OpenGL profile')
version_code = self.version_code
if not version_code:
major, minor = map(int, self.info['GL_VERSION'].split('.', 2)[:2])
version_code = major * 100 + minor * 10
if version_code < 330:
warnings.warn('The window should support OpenGL 3.3+ (version_code=%d)' % version_code) | [
"def",
"core_profile_check",
"(",
"self",
")",
"->",
"None",
":",
"profile_mask",
"=",
"self",
".",
"info",
"[",
"'GL_CONTEXT_PROFILE_MASK'",
"]",
"if",
"profile_mask",
"!=",
"1",
":",
"warnings",
".",
"warn",
"(",
"'The window should request a CORE OpenGL profile'"... | Core profile check.
FOR DEBUG PURPOSES ONLY | [
"Core",
"profile",
"check",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/context.py#L1072-L1089 | train | 220,383 |
moderngl/moderngl | examples/window/glfw/window.py | Window.mouse_button_callback | def mouse_button_callback(self, window, button, action, mods):
"""
Handle mouse button events and forward them to the example
"""
# Offset button index by 1 to make it match the other libraries
button += 1
# Support left and right mouse button for now
if button not in [1, 2]:
return
xpos, ypos = glfw.get_cursor_pos(self.window)
if action == glfw.PRESS:
self.example.mouse_press_event(xpos, ypos, button)
else:
self.example.mouse_release_event(xpos, ypos, button) | python | def mouse_button_callback(self, window, button, action, mods):
"""
Handle mouse button events and forward them to the example
"""
# Offset button index by 1 to make it match the other libraries
button += 1
# Support left and right mouse button for now
if button not in [1, 2]:
return
xpos, ypos = glfw.get_cursor_pos(self.window)
if action == glfw.PRESS:
self.example.mouse_press_event(xpos, ypos, button)
else:
self.example.mouse_release_event(xpos, ypos, button) | [
"def",
"mouse_button_callback",
"(",
"self",
",",
"window",
",",
"button",
",",
"action",
",",
"mods",
")",
":",
"# Offset button index by 1 to make it match the other libraries\r",
"button",
"+=",
"1",
"# Support left and right mouse button for now\r",
"if",
"button",
"not... | Handle mouse button events and forward them to the example | [
"Handle",
"mouse",
"button",
"events",
"and",
"forward",
"them",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/glfw/window.py#L121-L136 | train | 220,384 |
moderngl/moderngl | moderngl/buffer.py | Buffer.write_chunks | def write_chunks(self, data, start, step, count) -> None:
'''
Split data to count equal parts.
Write the chunks using offsets calculated from start, step and stop.
Args:
data (bytes): The data.
start (int): First offset.
step (int): Offset increment.
count (int): The number of offsets.
'''
self.mglo.write_chunks(data, start, step, count) | python | def write_chunks(self, data, start, step, count) -> None:
'''
Split data to count equal parts.
Write the chunks using offsets calculated from start, step and stop.
Args:
data (bytes): The data.
start (int): First offset.
step (int): Offset increment.
count (int): The number of offsets.
'''
self.mglo.write_chunks(data, start, step, count) | [
"def",
"write_chunks",
"(",
"self",
",",
"data",
",",
"start",
",",
"step",
",",
"count",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"write_chunks",
"(",
"data",
",",
"start",
",",
"step",
",",
"count",
")"
] | Split data to count equal parts.
Write the chunks using offsets calculated from start, step and stop.
Args:
data (bytes): The data.
start (int): First offset.
step (int): Offset increment.
count (int): The number of offsets. | [
"Split",
"data",
"to",
"count",
"equal",
"parts",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/buffer.py#L72-L85 | train | 220,385 |
moderngl/moderngl | moderngl/buffer.py | Buffer.read_into | def read_into(self, buffer, size=-1, *, offset=0, write_offset=0) -> None:
'''
Read the content into a buffer.
Args:
buffer (bytarray): The buffer that will receive the content.
size (int): The size. Value ``-1`` means all.
Keyword Args:
offset (int): The read offset.
write_offset (int): The write offset.
'''
return self.mglo.read_into(buffer, size, offset, write_offset) | python | def read_into(self, buffer, size=-1, *, offset=0, write_offset=0) -> None:
'''
Read the content into a buffer.
Args:
buffer (bytarray): The buffer that will receive the content.
size (int): The size. Value ``-1`` means all.
Keyword Args:
offset (int): The read offset.
write_offset (int): The write offset.
'''
return self.mglo.read_into(buffer, size, offset, write_offset) | [
"def",
"read_into",
"(",
"self",
",",
"buffer",
",",
"size",
"=",
"-",
"1",
",",
"*",
",",
"offset",
"=",
"0",
",",
"write_offset",
"=",
"0",
")",
"->",
"None",
":",
"return",
"self",
".",
"mglo",
".",
"read_into",
"(",
"buffer",
",",
"size",
","... | Read the content into a buffer.
Args:
buffer (bytarray): The buffer that will receive the content.
size (int): The size. Value ``-1`` means all.
Keyword Args:
offset (int): The read offset.
write_offset (int): The write offset. | [
"Read",
"the",
"content",
"into",
"a",
"buffer",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/buffer.py#L103-L116 | train | 220,386 |
moderngl/moderngl | moderngl/buffer.py | Buffer.clear | def clear(self, size=-1, *, offset=0, chunk=None) -> None:
'''
Clear the content.
Args:
size (int): The size. Value ``-1`` means all.
Keyword Args:
offset (int): The offset.
chunk (bytes): The chunk to use repeatedly.
'''
self.mglo.clear(size, offset, chunk) | python | def clear(self, size=-1, *, offset=0, chunk=None) -> None:
'''
Clear the content.
Args:
size (int): The size. Value ``-1`` means all.
Keyword Args:
offset (int): The offset.
chunk (bytes): The chunk to use repeatedly.
'''
self.mglo.clear(size, offset, chunk) | [
"def",
"clear",
"(",
"self",
",",
"size",
"=",
"-",
"1",
",",
"*",
",",
"offset",
"=",
"0",
",",
"chunk",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"clear",
"(",
"size",
",",
"offset",
",",
"chunk",
")"
] | Clear the content.
Args:
size (int): The size. Value ``-1`` means all.
Keyword Args:
offset (int): The offset.
chunk (bytes): The chunk to use repeatedly. | [
"Clear",
"the",
"content",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/buffer.py#L157-L169 | train | 220,387 |
moderngl/moderngl | moderngl/buffer.py | Buffer.bind_to_uniform_block | def bind_to_uniform_block(self, binding=0, *, offset=0, size=-1) -> None:
'''
Bind the buffer to a uniform block.
Args:
binding (int): The uniform block binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all.
'''
self.mglo.bind_to_uniform_block(binding, offset, size) | python | def bind_to_uniform_block(self, binding=0, *, offset=0, size=-1) -> None:
'''
Bind the buffer to a uniform block.
Args:
binding (int): The uniform block binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all.
'''
self.mglo.bind_to_uniform_block(binding, offset, size) | [
"def",
"bind_to_uniform_block",
"(",
"self",
",",
"binding",
"=",
"0",
",",
"*",
",",
"offset",
"=",
"0",
",",
"size",
"=",
"-",
"1",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"bind_to_uniform_block",
"(",
"binding",
",",
"offset",
",",
"size... | Bind the buffer to a uniform block.
Args:
binding (int): The uniform block binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all. | [
"Bind",
"the",
"buffer",
"to",
"a",
"uniform",
"block",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/buffer.py#L171-L183 | train | 220,388 |
moderngl/moderngl | moderngl/buffer.py | Buffer.bind_to_storage_buffer | def bind_to_storage_buffer(self, binding=0, *, offset=0, size=-1) -> None:
'''
Bind the buffer to a shader storage buffer.
Args:
binding (int): The shader storage binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all.
'''
self.mglo.bind_to_storage_buffer(binding, offset, size) | python | def bind_to_storage_buffer(self, binding=0, *, offset=0, size=-1) -> None:
'''
Bind the buffer to a shader storage buffer.
Args:
binding (int): The shader storage binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all.
'''
self.mglo.bind_to_storage_buffer(binding, offset, size) | [
"def",
"bind_to_storage_buffer",
"(",
"self",
",",
"binding",
"=",
"0",
",",
"*",
",",
"offset",
"=",
"0",
",",
"size",
"=",
"-",
"1",
")",
"->",
"None",
":",
"self",
".",
"mglo",
".",
"bind_to_storage_buffer",
"(",
"binding",
",",
"offset",
",",
"si... | Bind the buffer to a shader storage buffer.
Args:
binding (int): The shader storage binding.
Keyword Args:
offset (int): The offset.
size (int): The size. Value ``-1`` means all. | [
"Bind",
"the",
"buffer",
"to",
"a",
"shader",
"storage",
"buffer",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/buffer.py#L185-L197 | train | 220,389 |
moderngl/moderngl | examples/window/pyqt5/window.py | Window.swap_buffers | def swap_buffers(self):
"""
Swap buffers, set viewport, trigger events and increment frame counter
"""
self.widget.swapBuffers()
self.set_default_viewport()
self.app.processEvents()
self.frames += 1 | python | def swap_buffers(self):
"""
Swap buffers, set viewport, trigger events and increment frame counter
"""
self.widget.swapBuffers()
self.set_default_viewport()
self.app.processEvents()
self.frames += 1 | [
"def",
"swap_buffers",
"(",
"self",
")",
":",
"self",
".",
"widget",
".",
"swapBuffers",
"(",
")",
"self",
".",
"set_default_viewport",
"(",
")",
"self",
".",
"app",
".",
"processEvents",
"(",
")",
"self",
".",
"frames",
"+=",
"1"
] | Swap buffers, set viewport, trigger events and increment frame counter | [
"Swap",
"buffers",
"set",
"viewport",
"trigger",
"events",
"and",
"increment",
"frame",
"counter"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L100-L107 | train | 220,390 |
moderngl/moderngl | examples/window/pyqt5/window.py | Window.resize | def resize(self, width: int, height: int):
"""
Replacement for Qt's resizeGL method.
"""
self.width = width // self.widget.devicePixelRatio()
self.height = height // self.widget.devicePixelRatio()
self.buffer_width = width
self.buffer_height = height
if self.ctx:
self.set_default_viewport()
# Make sure we notify the example about the resize
super().resize(self.buffer_width, self.buffer_height) | python | def resize(self, width: int, height: int):
"""
Replacement for Qt's resizeGL method.
"""
self.width = width // self.widget.devicePixelRatio()
self.height = height // self.widget.devicePixelRatio()
self.buffer_width = width
self.buffer_height = height
if self.ctx:
self.set_default_viewport()
# Make sure we notify the example about the resize
super().resize(self.buffer_width, self.buffer_height) | [
"def",
"resize",
"(",
"self",
",",
"width",
":",
"int",
",",
"height",
":",
"int",
")",
":",
"self",
".",
"width",
"=",
"width",
"//",
"self",
".",
"widget",
".",
"devicePixelRatio",
"(",
")",
"self",
".",
"height",
"=",
"height",
"//",
"self",
"."... | Replacement for Qt's resizeGL method. | [
"Replacement",
"for",
"Qt",
"s",
"resizeGL",
"method",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L109-L122 | train | 220,391 |
moderngl/moderngl | examples/window/pyqt5/window.py | Window.key_pressed_event | def key_pressed_event(self, event):
"""
Process Qt key press events forwarding them to the example
"""
if event.key() == self.keys.ESCAPE:
self.close()
self.example.key_event(event.key(), self.keys.ACTION_PRESS) | python | def key_pressed_event(self, event):
"""
Process Qt key press events forwarding them to the example
"""
if event.key() == self.keys.ESCAPE:
self.close()
self.example.key_event(event.key(), self.keys.ACTION_PRESS) | [
"def",
"key_pressed_event",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"key",
"(",
")",
"==",
"self",
".",
"keys",
".",
"ESCAPE",
":",
"self",
".",
"close",
"(",
")",
"self",
".",
"example",
".",
"key_event",
"(",
"event",
".",
"key",... | Process Qt key press events forwarding them to the example | [
"Process",
"Qt",
"key",
"press",
"events",
"forwarding",
"them",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L124-L131 | train | 220,392 |
moderngl/moderngl | examples/window/pyqt5/window.py | Window.key_release_event | def key_release_event(self, event):
"""
Process Qt key release events forwarding them to the example
"""
self.example.key_event(event.key(), self.keys.ACTION_RELEASE) | python | def key_release_event(self, event):
"""
Process Qt key release events forwarding them to the example
"""
self.example.key_event(event.key(), self.keys.ACTION_RELEASE) | [
"def",
"key_release_event",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"example",
".",
"key_event",
"(",
"event",
".",
"key",
"(",
")",
",",
"self",
".",
"keys",
".",
"ACTION_RELEASE",
")"
] | Process Qt key release events forwarding them to the example | [
"Process",
"Qt",
"key",
"release",
"events",
"forwarding",
"them",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L133-L137 | train | 220,393 |
moderngl/moderngl | examples/window/pyqt5/window.py | Window.mouse_move_event | def mouse_move_event(self, event):
"""
Forward mouse cursor position events to the example
"""
self.example.mouse_position_event(event.x(), event.y()) | python | def mouse_move_event(self, event):
"""
Forward mouse cursor position events to the example
"""
self.example.mouse_position_event(event.x(), event.y()) | [
"def",
"mouse_move_event",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"example",
".",
"mouse_position_event",
"(",
"event",
".",
"x",
"(",
")",
",",
"event",
".",
"y",
"(",
")",
")"
] | Forward mouse cursor position events to the example | [
"Forward",
"mouse",
"cursor",
"position",
"events",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L139-L143 | train | 220,394 |
moderngl/moderngl | examples/window/pyqt5/window.py | Window.mouse_press_event | def mouse_press_event(self, event):
"""
Forward mouse press events to the example
"""
# Support left and right mouse button for now
if event.button() not in [1, 2]:
return
self.example.mouse_press_event(event.x(), event.y(), event.button()) | python | def mouse_press_event(self, event):
"""
Forward mouse press events to the example
"""
# Support left and right mouse button for now
if event.button() not in [1, 2]:
return
self.example.mouse_press_event(event.x(), event.y(), event.button()) | [
"def",
"mouse_press_event",
"(",
"self",
",",
"event",
")",
":",
"# Support left and right mouse button for now\r",
"if",
"event",
".",
"button",
"(",
")",
"not",
"in",
"[",
"1",
",",
"2",
"]",
":",
"return",
"self",
".",
"example",
".",
"mouse_press_event",
... | Forward mouse press events to the example | [
"Forward",
"mouse",
"press",
"events",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L145-L153 | train | 220,395 |
moderngl/moderngl | examples/window/pyqt5/window.py | Window.mouse_release_event | def mouse_release_event(self, event):
"""
Forward mouse release events to the example
"""
# Support left and right mouse button for now
if event.button() not in [1, 2]:
return
self.example.mouse_release_event(event.x(), event.y(), event.button()) | python | def mouse_release_event(self, event):
"""
Forward mouse release events to the example
"""
# Support left and right mouse button for now
if event.button() not in [1, 2]:
return
self.example.mouse_release_event(event.x(), event.y(), event.button()) | [
"def",
"mouse_release_event",
"(",
"self",
",",
"event",
")",
":",
"# Support left and right mouse button for now\r",
"if",
"event",
".",
"button",
"(",
")",
"not",
"in",
"[",
"1",
",",
"2",
"]",
":",
"return",
"self",
".",
"example",
".",
"mouse_release_event... | Forward mouse release events to the example | [
"Forward",
"mouse",
"release",
"events",
"to",
"the",
"example"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/pyqt5/window.py#L155-L163 | train | 220,396 |
moderngl/moderngl | moderngl/framebuffer.py | Framebuffer.read | def read(self, viewport=None, components=3, *, attachment=0, alignment=1, dtype='f1') -> bytes:
'''
Read the content of the framebuffer.
Args:
viewport (tuple): The viewport.
components (int): The number of components to read.
Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
Returns:
bytes
'''
return self.mglo.read(viewport, components, attachment, alignment, dtype) | python | def read(self, viewport=None, components=3, *, attachment=0, alignment=1, dtype='f1') -> bytes:
'''
Read the content of the framebuffer.
Args:
viewport (tuple): The viewport.
components (int): The number of components to read.
Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
Returns:
bytes
'''
return self.mglo.read(viewport, components, attachment, alignment, dtype) | [
"def",
"read",
"(",
"self",
",",
"viewport",
"=",
"None",
",",
"components",
"=",
"3",
",",
"*",
",",
"attachment",
"=",
"0",
",",
"alignment",
"=",
"1",
",",
"dtype",
"=",
"'f1'",
")",
"->",
"bytes",
":",
"return",
"self",
".",
"mglo",
".",
"rea... | Read the content of the framebuffer.
Args:
viewport (tuple): The viewport.
components (int): The number of components to read.
Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
Returns:
bytes | [
"Read",
"the",
"content",
"of",
"the",
"framebuffer",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/framebuffer.py#L174-L191 | train | 220,397 |
moderngl/moderngl | moderngl/framebuffer.py | Framebuffer.read_into | def read_into(self, buffer, viewport=None, components=3, *,
attachment=0, alignment=1, dtype='f1', write_offset=0) -> None:
'''
Read the content of the framebuffer into a buffer.
Args:
buffer (bytearray): The buffer that will receive the pixels.
viewport (tuple): The viewport.
components (int): The number of components to read.
Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
write_offset (int): The write offset.
'''
if type(buffer) is Buffer:
buffer = buffer.mglo
return self.mglo.read_into(buffer, viewport, components, attachment, alignment, dtype, write_offset) | python | def read_into(self, buffer, viewport=None, components=3, *,
attachment=0, alignment=1, dtype='f1', write_offset=0) -> None:
'''
Read the content of the framebuffer into a buffer.
Args:
buffer (bytearray): The buffer that will receive the pixels.
viewport (tuple): The viewport.
components (int): The number of components to read.
Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
write_offset (int): The write offset.
'''
if type(buffer) is Buffer:
buffer = buffer.mglo
return self.mglo.read_into(buffer, viewport, components, attachment, alignment, dtype, write_offset) | [
"def",
"read_into",
"(",
"self",
",",
"buffer",
",",
"viewport",
"=",
"None",
",",
"components",
"=",
"3",
",",
"*",
",",
"attachment",
"=",
"0",
",",
"alignment",
"=",
"1",
",",
"dtype",
"=",
"'f1'",
",",
"write_offset",
"=",
"0",
")",
"->",
"None... | Read the content of the framebuffer into a buffer.
Args:
buffer (bytearray): The buffer that will receive the pixels.
viewport (tuple): The viewport.
components (int): The number of components to read.
Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
write_offset (int): The write offset. | [
"Read",
"the",
"content",
"of",
"the",
"framebuffer",
"into",
"a",
"buffer",
"."
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/moderngl/framebuffer.py#L193-L213 | train | 220,398 |
moderngl/moderngl | examples/window/base.py | BaseWindow.resize | def resize(self, width, height):
"""
Should be called every time window is resized
so the example can adapt to the new size if needed
"""
if self.example:
self.example.resize(width, height) | python | def resize(self, width, height):
"""
Should be called every time window is resized
so the example can adapt to the new size if needed
"""
if self.example:
self.example.resize(width, height) | [
"def",
"resize",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"if",
"self",
".",
"example",
":",
"self",
".",
"example",
".",
"resize",
"(",
"width",
",",
"height",
")"
] | Should be called every time window is resized
so the example can adapt to the new size if needed | [
"Should",
"be",
"called",
"every",
"time",
"window",
"is",
"resized",
"so",
"the",
"example",
"can",
"adapt",
"to",
"the",
"new",
"size",
"if",
"needed"
] | a8f5dce8dc72ae84a2f9523887fb5f6b620049b9 | https://github.com/moderngl/moderngl/blob/a8f5dce8dc72ae84a2f9523887fb5f6b620049b9/examples/window/base.py#L136-L142 | train | 220,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.