code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def bech32_create_checksum(hrp, data): """Compute the checksum values given HRP and data.""" values = bech32_hrp_expand(hrp) + data polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1 return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
Compute the checksum values given HRP and data.
bech32_create_checksum
python
FuzzingLabs/octopus
octopus/platforms/BTC/bech32.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/bech32.py
MIT
def bech32_encode(hrp, data): """Compute a Bech32 string given HRP and data values.""" combined = data + bech32_create_checksum(hrp, data) return hrp + '1' + ''.join([CHARSET[d] for d in combined])
Compute a Bech32 string given HRP and data values.
bech32_encode
python
FuzzingLabs/octopus
octopus/platforms/BTC/bech32.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/bech32.py
MIT
def bech32_decode(bech): """Validate a Bech32 string, and determine HRP and data.""" if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or (bech.lower() != bech and bech.upper() != bech)): return (None, None) bech = bech.lower() pos = bech.rfind('1') if pos < 1 or pos + 7 > len...
Validate a Bech32 string, and determine HRP and data.
bech32_decode
python
FuzzingLabs/octopus
octopus/platforms/BTC/bech32.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/bech32.py
MIT
def _get_reverse_table(self): """Build an internal table used in the assembler.""" reverse_table = {} for (opcode, (mnemonic, immediate_operand_size, pops, pushes, gas, description)) in _table.items(): reverse_table[mnemonic] = opcode, mnemonic, immediate_operan...
Build an internal table used in the assembler.
_get_reverse_table
python
FuzzingLabs/octopus
octopus/platforms/BTC/btcscript.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/btcscript.py
MIT
def gettxoutproof(self, txids, blockhash=None): ''' TESTED http://chainquery.com/bitcoin-api/gettxoutproof Returns a hex-encoded proof that "txid" was included in a block. NOTE: By default this function only works sometimes. This is when there is an unspent output in ...
TESTED http://chainquery.com/bitcoin-api/gettxoutproof Returns a hex-encoded proof that "txid" was included in a block. NOTE: By default this function only works sometimes. This is when there is an unspent output in the utxo for this transaction. To make it always work, ...
gettxoutproof
python
FuzzingLabs/octopus
octopus/platforms/BTC/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py
MIT
def help(self, command=None): ''' TESTED http://chainquery.com/bitcoin-api/help List all commands, or get help for a specified command. Arguments: 1. "command" (string, optional) The command to get help on Result: "text" (string) The help text...
TESTED http://chainquery.com/bitcoin-api/help List all commands, or get help for a specified command. Arguments: 1. "command" (string, optional) The command to get help on Result: "text" (string) The help text
help
python
FuzzingLabs/octopus
octopus/platforms/BTC/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py
MIT
def lockunspent(self, unlock, transactions=None): ''' TESTED http://chainquery.com/bitcoin-api/lockunspent Updates list of temporarily unspendable outputs. Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs. If no transaction outputs ...
TESTED http://chainquery.com/bitcoin-api/lockunspent Updates list of temporarily unspendable outputs. Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs. If no transaction outputs are specified when unlocking then all current locked transact...
lockunspent
python
FuzzingLabs/octopus
octopus/platforms/BTC/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py
MIT
def sendfrom(self, fromaccount, toaddress, amount, minconf=1, comment=None, comment_to=None): ''' http://chainquery.com/bitcoin-api/sendfrom NOT TESTED DEPRECATED (use sendtoaddress). Sent an amount from an account to a bitcoin address. Requires wallet passphrase to be set with...
http://chainquery.com/bitcoin-api/sendfrom NOT TESTED DEPRECATED (use sendtoaddress). Sent an amount from an account to a bitcoin address. Requires wallet passphrase to be set with walletpassphrase call. Arguments: 1. "fromaccount" (string, required) The name of...
sendfrom
python
FuzzingLabs/octopus
octopus/platforms/BTC/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py
MIT
def sendmany(self, fromaccount, amounts, minconf=1, comment=None, subtractfeefrom=None, replaceable=None, conf_target=None, estimate_mode="UNSET"): ''' http://chainquery.com/bitcoin-api/sendmany NOT TESTED Send multiple times. Amounts are double-precision floating point numbers. ...
http://chainquery.com/bitcoin-api/sendmany NOT TESTED Send multiple times. Amounts are double-precision floating point numbers. Requires wallet passphrase to be set with walletpassphrase call. Arguments: 1. "fromaccount" (string, required) DEPRECATED. The acco...
sendmany
python
FuzzingLabs/octopus
octopus/platforms/BTC/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py
MIT
def sendtoaddress(self, address, amount, comment=None, comment_to=None, subtractfeefromamount=False, replaceable=None, estimate_mode="UNSET"): ''' http://chainquery.com/bitcoin-api/sendtoaddress NOT TESTED Send an amount to a given address. Requires wallet passphrase to be set...
http://chainquery.com/bitcoin-api/sendtoaddress NOT TESTED Send an amount to a given address. Requires wallet passphrase to be set with walletpassphrase call. Arguments: 1. "address" (string, required) The bitcoin address to send to. 2. "amount" ...
sendtoaddress
python
FuzzingLabs/octopus
octopus/platforms/BTC/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py
MIT
def signrawtransaction(self, hexstring, prevtxs=None, privkeys=None, sighashtype="ALL"): ''' http://chainquery.com/bitcoin-api/signrawtransaction NOT TESTED Sign inputs for raw transaction (serialized, hex-encoded). The second optional argument (may be null) is an array of prev...
http://chainquery.com/bitcoin-api/signrawtransaction NOT TESTED Sign inputs for raw transaction (serialized, hex-encoded). The second optional argument (may be null) is an array of previous transaction outputs that this transaction depends on but may not yet be in the block ch...
signrawtransaction
python
FuzzingLabs/octopus
octopus/platforms/BTC/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/BTC/explorer.py
MIT
def get_block(self, block_num_or_id): '''Get information related to a block. TESTED ''' data = {'block_num_or_id': block_num_or_id} return self.call('get_block', data)
Get information related to a block. TESTED
get_block
python
FuzzingLabs/octopus
octopus/platforms/EOS/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/EOS/explorer.py
MIT
def get_account(self, account_name): '''Get information related to an account. TESTED ''' data = {'account_name': account_name} return self.call('get_account', data)
Get information related to an account. TESTED
get_account
python
FuzzingLabs/octopus
octopus/platforms/EOS/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/EOS/explorer.py
MIT
def get_table_rows(self, scope, code, table, json=False, lower_bound=None, upper_bound=None, limit=None): '''Fetch smart contract data from an account. NOT TESTED ''' data = {'scope': scope, 'code': code, 'table': table, 'json': json} ...
Fetch smart contract data from an account. NOT TESTED
get_table_rows
python
FuzzingLabs/octopus
octopus/platforms/EOS/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/EOS/explorer.py
MIT
def abi_json_to_bin(self, code, action, args): '''Serialize json to binary hex. The resulting binary hex is usually used for the data field in push_transaction. NOT TESTED ''' data = {'code': code, 'action': action, 'args': args} print(data) ...
Serialize json to binary hex. The resulting binary hex is usually used for the data field in push_transaction. NOT TESTED
abi_json_to_bin
python
FuzzingLabs/octopus
octopus/platforms/EOS/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/EOS/explorer.py
MIT
def abi_bin_to_json(self, code, action, binargs): '''Serialize back binary hex to json. NOT TESTED ''' data = {'code': code, 'action': action, 'binargs': binargs} return self.call('abi_bin_to_json', data)
Serialize back binary hex to json. NOT TESTED
abi_bin_to_json
python
FuzzingLabs/octopus
octopus/platforms/EOS/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/EOS/explorer.py
MIT
def get_required_keys(self, transaction): '''Get required keys to sign a transaction from list of your keys. NOT TESTED ''' data = {'transaction': transaction} return self.call('get_required_keys', data)
Get required keys to sign a transaction from list of your keys. NOT TESTED
get_required_keys
python
FuzzingLabs/octopus
octopus/platforms/EOS/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/EOS/explorer.py
MIT
def decode_tx(self, transaction_id): """ Return dict with important information about the given transaction """ tx_data = self.eth_getTransactionByHash(transaction_id) return tx_data #TODO
Return dict with important information about the given transaction
decode_tx
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def create_contract(self, from_, code, gas, sig=None, args=None): """ Create a contract on the blockchain from compiled EVM code. Returns the transaction hash. """ ''' from_ = from_ or self.eth_coinbase() if sig is not None and args is not None: types ...
Create a contract on the blockchain from compiled EVM code. Returns the transaction hash.
create_contract
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def call_without_transaction(self, address, sig, args, result_types): """ Call a contract function on the RPC server, without sending a transaction (useful for reading data) """ ''' data = self._encode_function(sig, args) data_hex = data.encode('hex') resp...
Call a contract function on the RPC server, without sending a transaction (useful for reading data)
call_without_transaction
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def call_with_transaction(self, from_, address, sig, args, gas=None, gas_price=None, value=None): """ Call a contract function by sending a transaction (useful for storing data) """ ''' gas = gas or DEFAULT_GAS_PER_TX gas_price = gas_price or DEFAULT_GAS_PRICE ...
Call a contract function by sending a transaction (useful for storing data)
call_with_transaction
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def web3_sha3(self, data): """ Returns Keccak-256 (not the standardized SHA3-256) of the given data. :param data: the data to convert into a SHA3 hash :type data: hex string :return: The SHA3 result of the given string. :rtype: hex string :Example: >>> explorer...
Returns Keccak-256 (not the standardized SHA3-256) of the given data. :param data: the data to convert into a SHA3 hash :type data: hex string :return: The SHA3 result of the given string. :rtype: hex string :Example: >>> explorer = EthereumExplorerRPC() >>> e...
web3_sha3
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def eth_getBalance(self, address=None, block=BLOCK_TAG_LATEST): """ Returns the balance of the account of given address. :param address: 20 Bytes - address to check for balance. :type address: str :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pen...
Returns the balance of the account of given address. :param address: 20 Bytes - address to check for balance. :type address: str :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" :type block: int or str :return: integer of the curr...
eth_getBalance
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def eth_getStorageAt(self, address=None, position=0, block=BLOCK_TAG_LATEST): """ Returns the value from a storage position at a given address. :param address: 20 Bytes - address to check for balance. :type address: str :param address: (optionnal) integer of the position in the storage....
Returns the value from a storage position at a given address. :param address: 20 Bytes - address to check for balance. :type address: str :param address: (optionnal) integer of the position in the storage. default is 0 :type address: int :param block: (optionnal) integer block ...
eth_getStorageAt
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def eth_getTransactionCount(self, address, block=BLOCK_TAG_LATEST): """ Returns the number of transactions sent from an address. :param address: 20 Bytes - address. :type address: str :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" ...
Returns the number of transactions sent from an address. :param address: 20 Bytes - address. :type address: str :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" :type block: int or str :return: integer of the number of transactions...
eth_getTransactionCount
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def eth_getBlockTransactionCountByNumber(self, block=BLOCK_TAG_LATEST): """ Returns the number of transactions in a block matching the given block number. :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" :type block: int or str :return: in...
Returns the number of transactions in a block matching the given block number. :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" :type block: int or str :return: integer of the number of transactions in this block. :rtype: int :Ex...
eth_getBlockTransactionCountByNumber
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def eth_getUncleCountByBlockNumber(self, block=BLOCK_TAG_LATEST): """ Returns the number of uncles in a block from a block matching the given block number. :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" :type block: int or str :return: in...
Returns the number of uncles in a block from a block matching the given block number. :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" :type block: int or str :return: integer of the number of uncles in this block. :rtype: int :Ex...
eth_getUncleCountByBlockNumber
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def eth_getCode(self, address, default_block=BLOCK_TAG_LATEST): """ Returns code at a given address. :param address: 20 Bytes - address. :type address: str :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" :type block: int or str ...
Returns code at a given address. :param address: 20 Bytes - address. :type address: str :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" :type block: int or str :return: the code from the given address. :rtype: hex str ...
eth_getCode
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def eth_sendTransaction(self, to_address=None, from_address=None, gas=None, gas_price=None, value=None, data=None, nonce=None): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sendtransaction NEEDS TESTING """ params = {} params['from']...
ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sendtransaction\n\n NEEDS TESTING\n "
eth_sendTransaction
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def eth_call(self, to_address, from_address=None, gas=None, gas_price=None, value=None, data=None, default_block=BLOCK_TAG_LATEST): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_call NEEDS TESTING """ default_block = validate_block(default_block) ...
ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_call\n\n NEEDS TESTING\n "
eth_call
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def eth_estimateGas(self, to_address=None, from_address=None, gas=None, gas_price=None, value=None, data=None, default_block=BLOCK_TAG_LATEST): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_estimategas NEEDS TESTING """ if isinstance(default_bloc...
ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_estimategas\n\n NEEDS TESTING\n "
eth_estimateGas
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def eth_getTransactionByBlockNumberAndIndex(self, block=BLOCK_TAG_LATEST, index=0): """ Returns information about a transaction by block number and transaction index position. :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" :type block: int or str...
Returns information about a transaction by block number and transaction index position. :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" :type block: int or str :param index: (optionnal) integer of the transaction index position. :type ind...
eth_getTransactionByBlockNumberAndIndex
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def eth_getUncleByBlockNumberAndIndex(self, block=BLOCK_TAG_LATEST, index=0): """ Returns information about a uncle of a block by number and uncle index position. :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" :type block: int or str :par...
Returns information about a uncle of a block by number and uncle index position. :param block: (optionnal) integer block number, or the string "latest", "earliest" or "pending" :type block: int or str :param index: (optionnal) the uncle's index position. :type index: int :retur...
eth_getUncleByBlockNumberAndIndex
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def eth_newFilter(self, from_block=BLOCK_TAG_LATEST, to_block=BLOCK_TAG_LATEST, address=None, topics=None): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newfilter NEEDS TESTING """ _filter = { 'fromBlock': from_block, 'toBlock': to_block, ...
ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newfilter\n\n NEEDS TESTING\n "
eth_newFilter
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def db_putString(self, db_name, key, value): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#db_putstring TESTED """ warnings.warn('deprecated', DeprecationWarning) return self.call('db_putString', [db_name, key, value])
ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#db_putstring\n\n TESTED\n "
db_putString
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def db_getString(self, db_name, key): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#db_getstring TESTED """ warnings.warn('deprecated', DeprecationWarning) return self.call('db_getString', [db_name, key])
ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#db_getstring\n\n TESTED\n "
db_getString
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def db_putHex(self, db_name, key, value): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#db_puthex TESTED """ if not value.startswith('0x'): value = '0x{}'.format(value) warnings.warn('deprecated', DeprecationWarning) return self.call('db_putHex',...
ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#db_puthex\n\n TESTED\n "
db_putHex
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def db_getHex(self, db_name, key): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#db_gethex TESTED """ warnings.warn('deprecated', DeprecationWarning) return self.call('db_getHex', [db_name, key])
ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#db_gethex\n\n TESTED\n "
db_getHex
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def shh_post(self, topics, payload, priority, ttl, from_=None, to=None): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#shh_post NEEDS TESTING """ whisper_object = { 'from': from_, 'to': to, 'topics': topics, 'payload': payload...
ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#shh_post\n\n NEEDS TESTING\n "
shh_post
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def shh_newFilter(self, to, topics): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#shh_newfilter NEEDS TESTING """ _filter = { 'to': to, 'topics': topics, } return self.call('shh_newFilter', [_filter])
ERROR: type should be string, got "\n https://github.com/ethereum/wiki/wiki/JSON-RPC#shh_newfilter\n\n NEEDS TESTING\n "
shh_newFilter
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def trace_filter(self, from_block=None, to_block=None, from_addresses=None, to_addresses=None): """ https://github.com/ethcore/parity/wiki/JSONRPC-trace-module#trace_filter TESTED """ params = {} if from_block is not None: from_block = validate_block(from_blo...
ERROR: type should be string, got "\n https://github.com/ethcore/parity/wiki/JSONRPC-trace-module#trace_filter\n\n TESTED\n "
trace_filter
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def trace_get(self, tx_hash, positions): """ https://wiki.parity.io/JSONRPC https://github.com/ethcore/parity/wiki/JSONRPC-trace-module#trace_get NEEDS TESTING """ if not isinstance(positions, list): positions = [positions] return self.call('trace_get...
ERROR: type should be string, got "\n https://wiki.parity.io/JSONRPC\n https://github.com/ethcore/parity/wiki/JSONRPC-trace-module#trace_get\n\n NEEDS TESTING\n "
trace_get
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def trace_block(self, block=BLOCK_TAG_LATEST): """ https://wiki.parity.io/JSONRPC https://github.com/ethcore/parity/wiki/JSONRPC-trace-module#trace_block NEEDS TESTING """ block = validate_block(block) return self.call('trace_block', [block])
ERROR: type should be string, got "\n https://wiki.parity.io/JSONRPC\n https://github.com/ethcore/parity/wiki/JSONRPC-trace-module#trace_block\n\n NEEDS TESTING\n "
trace_block
python
FuzzingLabs/octopus
octopus/platforms/ETH/explorer.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/explorer.py
MIT
def ssa_sha3_instruction(self, instr, state): '''Symbolic execution of SHA3 group of opcode''' # SSA STACK s0, s1 = state.ssa_stack.pop(), state.ssa_stack.pop() instr.ssa = SSA(new_assignement=self.ssa_counter, method_name=instr.name, args=[s0, s1]) state.ssa_stack.append(instr)...
Symbolic execution of SHA3 group of opcode
ssa_sha3_instruction
python
FuzzingLabs/octopus
octopus/platforms/ETH/save_ssa.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/save_ssa.py
MIT
def clean_hex(d): ''' Convert decimal to hex and remove the "L" suffix that is appended to large numbers ''' try: return hex(d).rstrip('L') except: return None
Convert decimal to hex and remove the "L" suffix that is appended to large numbers
clean_hex
python
FuzzingLabs/octopus
octopus/platforms/ETH/util.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/util.py
MIT
def validate_block(block): ''' Test if the block tag is valid ''' if isinstance(block, str): if block not in BLOCK_TAGS: raise ValueError('invalid block tag') if isinstance(block, int): block = hex(block) return block
Test if the block tag is valid
validate_block
python
FuzzingLabs/octopus
octopus/platforms/ETH/util.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/ETH/util.py
MIT
def _get_reverse_table(self): """Build an internal table used in the assembler.""" reverse_table = {} for (opcode, (mnemonic, immediate_operand_size, pops, pushes, gas, description)) in self.table.items(): reverse_table[mnemonic] = opcode, mnemonic, immediate_op...
Build an internal table used in the assembler.
_get_reverse_table
python
FuzzingLabs/octopus
octopus/platforms/NEO/avm.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/NEO/avm.py
MIT
def enum_blocks_edges(instructions): """ Return a list of basicblock after statically parsing given instructions """ basicblocks = list() edges = list() xrefs = enumerate_xref(instructions) # create the first block new_block = True for inst in instructions: if new_bloc...
Return a list of basicblock after statically parsing given instructions
enum_blocks_edges
python
FuzzingLabs/octopus
octopus/platforms/NEO/cfg.py
https://github.com/FuzzingLabs/octopus/blob/master/octopus/platforms/NEO/cfg.py
MIT
def get_stats(ids, counts=None): """ Given a list of integers, return a dictionary of counts of consecutive pairs Example: [1, 2, 3, 1, 2] -> {(1, 2): 2, (2, 3): 1, (3, 1): 1} Optionally allows to update an existing dictionary of counts """ counts = {} if counts is None else counts for pair ...
Given a list of integers, return a dictionary of counts of consecutive pairs Example: [1, 2, 3, 1, 2] -> {(1, 2): 2, (2, 3): 1, (3, 1): 1} Optionally allows to update an existing dictionary of counts
get_stats
python
karpathy/minbpe
minbpe/base.py
https://github.com/karpathy/minbpe/blob/master/minbpe/base.py
MIT
def merge(ids, pair, idx): """ In the list of integers (ids), replace all consecutive occurrences of pair with the new integer token idx Example: ids=[1, 2, 3, 1, 2], pair=(1, 2), idx=4 -> [4, 3, 4] """ newids = [] i = 0 while i < len(ids): # if not at the very last position AND ...
In the list of integers (ids), replace all consecutive occurrences of pair with the new integer token idx Example: ids=[1, 2, 3, 1, 2], pair=(1, 2), idx=4 -> [4, 3, 4]
merge
python
karpathy/minbpe
minbpe/base.py
https://github.com/karpathy/minbpe/blob/master/minbpe/base.py
MIT
def load(self, model_file): """Inverse of save() but only for the model file""" assert model_file.endswith(".model") # read the model file merges = {} special_tokens = {} idx = 256 with open(model_file, 'r', encoding="utf-8") as f: # read the version ...
Inverse of save() but only for the model file
load
python
karpathy/minbpe
minbpe/base.py
https://github.com/karpathy/minbpe/blob/master/minbpe/base.py
MIT
def __init__(self, pattern=None): """ - pattern: optional string to override the default (GPT-4 split pattern) - special_tokens: str -> int dictionary of special tokens example: {'<|endoftext|>': 100257} """ super().__init__() self.pattern = GPT4_SPLIT_PATTERN i...
- pattern: optional string to override the default (GPT-4 split pattern) - special_tokens: str -> int dictionary of special tokens example: {'<|endoftext|>': 100257}
__init__
python
karpathy/minbpe
minbpe/regex.py
https://github.com/karpathy/minbpe/blob/master/minbpe/regex.py
MIT
def encode_ordinary(self, text): """Encoding that ignores any special tokens.""" # split text into chunks of text by categories defined in regex pattern text_chunks = re.findall(self.compiled_pattern, text) # all chunks of text are encoded separately, then results are joined ids ...
Encoding that ignores any special tokens.
encode_ordinary
python
karpathy/minbpe
minbpe/regex.py
https://github.com/karpathy/minbpe/blob/master/minbpe/regex.py
MIT
def encode(self, text, allowed_special="none_raise"): """ Unlike encode_ordinary, this function handles special tokens. allowed_special: can be "all"|"none"|"none_raise" or a custom set of special tokens if none_raise, then an error is raised if any special token is encountered in text ...
Unlike encode_ordinary, this function handles special tokens. allowed_special: can be "all"|"none"|"none_raise" or a custom set of special tokens if none_raise, then an error is raised if any special token is encountered in text this is the default tiktoken behavior right now as well ...
encode
python
karpathy/minbpe
minbpe/regex.py
https://github.com/karpathy/minbpe/blob/master/minbpe/regex.py
MIT
def test_wikipedia_example(tokenizer_factory): """ Quick unit test, following along the Wikipedia example: https://en.wikipedia.org/wiki/Byte_pair_encoding According to Wikipedia, running bpe on the input string: "aaabdaaabac" for 3 merges will result in string: "XdXac" where: X=Z...
Quick unit test, following along the Wikipedia example: https://en.wikipedia.org/wiki/Byte_pair_encoding According to Wikipedia, running bpe on the input string: "aaabdaaabac" for 3 merges will result in string: "XdXac" where: X=ZY Y=ab Z=aa Keep in mind that for us a=97...
test_wikipedia_example
python
karpathy/minbpe
tests/test_tokenizer.py
https://github.com/karpathy/minbpe/blob/master/tests/test_tokenizer.py
MIT
def __init__( self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True, ffn_bias=True, proj_bias=True, drop_path_rate=...
Args: img_size (int, tuple): input image size patch_size (int, tuple): patch size in_chans (int): number of input channels embed_dim (int): embedding dimension depth (int): depth of transformer num_heads (int): number of attention heads ...
__init__
python
ali-vilab/VACE
vace/annotators/depth_anything_v2/dinov2.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/depth_anything_v2/dinov2.py
Apache-2.0
def init_weights_vit_timm(module: nn.Module, name: str = ""): """ViT weight initialization, original timm impl (for reproducibility)""" if isinstance(module, nn.Linear): trunc_normal_(module.weight, std=0.02) if module.bias is not None: nn.init.zeros_(module.bias)
ViT weight initialization, original timm impl (for reproducibility)
init_weights_vit_timm
python
ali-vilab/VACE
vace/annotators/depth_anything_v2/dinov2.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/depth_anything_v2/dinov2.py
Apache-2.0
def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs): """ Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64 """ model = DinoVisionTransformer( patch_size=patch_size, embed_dim=1536, depth=40, num_heads=24, mlp_ratio=4, ...
Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
vit_giant2
python
ali-vilab/VACE
vace/annotators/depth_anything_v2/dinov2.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/depth_anything_v2/dinov2.py
Apache-2.0
def get_attn_bias_and_cat(x_list, branges=None): """ this will perform the index select, cat the tensors, and provide the attn_bias from cache """ batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list] all_shapes = tuple((b, x.shape[1]) for b, x in zip(b...
this will perform the index select, cat the tensors, and provide the attn_bias from cache
get_attn_bias_and_cat
python
ali-vilab/VACE
vace/annotators/depth_anything_v2/layers/block.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/depth_anything_v2/layers/block.py
Apache-2.0
def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]: """ x_list contains a list of tensors to nest together and run """ assert isinstance(self.attn, MemEffAttention) if self.training and self.sample_drop_ratio > 0.0: def attn_residual_func(x: Tensor, attn...
x_list contains a list of tensors to nest together and run
forward_nested
python
ali-vilab/VACE
vace/annotators/depth_anything_v2/layers/block.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/depth_anything_v2/layers/block.py
Apache-2.0
def __init__(self, features, activation, bn): """Init. Args: features (int): number of features """ super().__init__() self.bn = bn self.groups = 1 self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=sel...
Init. Args: features (int): number of features
__init__
python
ali-vilab/VACE
vace/annotators/depth_anything_v2/util/blocks.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/depth_anything_v2/util/blocks.py
Apache-2.0
def forward(self, x): """Forward pass. Args: x (tensor): input Returns: tensor: output """ out = self.activation(x) out = self.conv1(out) if self.bn == True: out = self.bn1(out) out = self.activation(out) out...
Forward pass. Args: x (tensor): input Returns: tensor: output
forward
python
ali-vilab/VACE
vace/annotators/depth_anything_v2/util/blocks.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/depth_anything_v2/util/blocks.py
Apache-2.0
def __init__( self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None ): """Init. Args: features (int): number of features """ super(Fe...
Init. Args: features (int): number of features
__init__
python
ali-vilab/VACE
vace/annotators/depth_anything_v2/util/blocks.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/depth_anything_v2/util/blocks.py
Apache-2.0
def __init__( self, width, height, resize_target=True, keep_aspect_ratio=False, ensure_multiple_of=1, resize_method="lower_bound", image_interpolation_method=cv2.INTER_AREA, ): """Init. Args: ...
Init. Args: width (int): desired output width height (int): desired output height resize_target (bool, optional): True: Resize the full sample (image, mask, target). False: Resize image only. Defaults to True. keep_...
__init__
python
ali-vilab/VACE
vace/annotators/depth_anything_v2/util/transform.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/depth_anything_v2/util/transform.py
Apache-2.0
def nms(boxes, scores, nms_thr): """Single class NMS implemented in Numpy.""" x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.a...
Single class NMS implemented in Numpy.
nms
python
ali-vilab/VACE
vace/annotators/dwpose/onnxdet.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxdet.py
Apache-2.0
def multiclass_nms(boxes, scores, nms_thr, score_thr): """Multiclass NMS implemented in Numpy. Class-aware version.""" final_dets = [] num_classes = scores.shape[1] for cls_ind in range(num_classes): cls_scores = scores[:, cls_ind] valid_score_mask = cls_scores > score_thr if val...
Multiclass NMS implemented in Numpy. Class-aware version.
multiclass_nms
python
ali-vilab/VACE
vace/annotators/dwpose/onnxdet.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxdet.py
Apache-2.0
def preprocess( img: np.ndarray, out_bbox, input_size: Tuple[int, int] = (192, 256) ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Do preprocessing for RTMPose model inference. Args: img (np.ndarray): Input image in shape. input_size (tuple): Input image size in shape (w, h). Retur...
Do preprocessing for RTMPose model inference. Args: img (np.ndarray): Input image in shape. input_size (tuple): Input image size in shape (w, h). Returns: tuple: - resized_img (np.ndarray): Preprocessed image. - center (np.ndarray): Center of image. - scale (np....
preprocess
python
ali-vilab/VACE
vace/annotators/dwpose/onnxpose.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxpose.py
Apache-2.0
def inference(sess: ort.InferenceSession, img: np.ndarray) -> np.ndarray: """Inference RTMPose model. Args: sess (ort.InferenceSession): ONNXRuntime session. img (np.ndarray): Input image in shape. Returns: outputs (np.ndarray): Output of RTMPose model. """ all_out = [] ...
Inference RTMPose model. Args: sess (ort.InferenceSession): ONNXRuntime session. img (np.ndarray): Input image in shape. Returns: outputs (np.ndarray): Output of RTMPose model.
inference
python
ali-vilab/VACE
vace/annotators/dwpose/onnxpose.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxpose.py
Apache-2.0
def postprocess(outputs: List[np.ndarray], model_input_size: Tuple[int, int], center: Tuple[int, int], scale: Tuple[int, int], simcc_split_ratio: float = 2.0 ) -> Tuple[np.ndarray, np.ndarray]: """Postprocess for RTMPose model output. ...
Postprocess for RTMPose model output. Args: outputs (np.ndarray): Output of RTMPose model. model_input_size (tuple): RTMPose model Input image size. center (tuple): Center of bbox in shape (x, y). scale (tuple): Scale of bbox in shape (w, h). simcc_split_ratio (float): Split...
postprocess
python
ali-vilab/VACE
vace/annotators/dwpose/onnxpose.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxpose.py
Apache-2.0
def bbox_xyxy2cs(bbox: np.ndarray, padding: float = 1.) -> Tuple[np.ndarray, np.ndarray]: """Transform the bbox format from (x,y,w,h) into (center, scale) Args: bbox (ndarray): Bounding box(es) in shape (4,) or (n, 4), formatted as (left, top, right, bottom) padding...
Transform the bbox format from (x,y,w,h) into (center, scale) Args: bbox (ndarray): Bounding box(es) in shape (4,) or (n, 4), formatted as (left, top, right, bottom) padding (float): BBox padding factor that will be multilied to scale. Default: 1.0 Returns: tupl...
bbox_xyxy2cs
python
ali-vilab/VACE
vace/annotators/dwpose/onnxpose.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxpose.py
Apache-2.0
def _fix_aspect_ratio(bbox_scale: np.ndarray, aspect_ratio: float) -> np.ndarray: """Extend the scale to match the given aspect ratio. Args: scale (np.ndarray): The image scale (w, h) in shape (2, ) aspect_ratio (float): The ratio of ``w/h`` Returns: np.ndarra...
Extend the scale to match the given aspect ratio. Args: scale (np.ndarray): The image scale (w, h) in shape (2, ) aspect_ratio (float): The ratio of ``w/h`` Returns: np.ndarray: The reshaped image scale in (2, )
_fix_aspect_ratio
python
ali-vilab/VACE
vace/annotators/dwpose/onnxpose.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxpose.py
Apache-2.0
def _rotate_point(pt: np.ndarray, angle_rad: float) -> np.ndarray: """Rotate a point by an angle. Args: pt (np.ndarray): 2D point coordinates (x, y) in shape (2, ) angle_rad (float): rotation angle in radian Returns: np.ndarray: Rotated point in shape (2, ) """ sn, cs = np....
Rotate a point by an angle. Args: pt (np.ndarray): 2D point coordinates (x, y) in shape (2, ) angle_rad (float): rotation angle in radian Returns: np.ndarray: Rotated point in shape (2, )
_rotate_point
python
ali-vilab/VACE
vace/annotators/dwpose/onnxpose.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxpose.py
Apache-2.0
def _get_3rd_point(a: np.ndarray, b: np.ndarray) -> np.ndarray: """To calculate the affine matrix, three pairs of points are required. This function is used to get the 3rd point, given 2D points a & b. The 3rd point is defined by rotating vector `a - b` by 90 degrees anticlockwise, using b as the rotat...
To calculate the affine matrix, three pairs of points are required. This function is used to get the 3rd point, given 2D points a & b. The 3rd point is defined by rotating vector `a - b` by 90 degrees anticlockwise, using b as the rotation center. Args: a (np.ndarray): The 1st point (x,y) in s...
_get_3rd_point
python
ali-vilab/VACE
vace/annotators/dwpose/onnxpose.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxpose.py
Apache-2.0
def get_warp_matrix(center: np.ndarray, scale: np.ndarray, rot: float, output_size: Tuple[int, int], shift: Tuple[float, float] = (0., 0.), inv: bool = False) -> np.ndarray: """Calculate the affine transformation mat...
Calculate the affine transformation matrix that can warp the bbox area in the input image to the output size. Args: center (np.ndarray[2, ]): Center of the bounding box (x, y). scale (np.ndarray[2, ]): Scale of the bounding box wrt [width, height]. rot (float): Rotation angl...
get_warp_matrix
python
ali-vilab/VACE
vace/annotators/dwpose/onnxpose.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxpose.py
Apache-2.0
def top_down_affine(input_size: dict, bbox_scale: dict, bbox_center: dict, img: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Get the bbox image as the model input by affine transform. Args: input_size (dict): The input size of the model. bbox_scale (dict): The bbox scale...
Get the bbox image as the model input by affine transform. Args: input_size (dict): The input size of the model. bbox_scale (dict): The bbox scale of the img. bbox_center (dict): The bbox center of the img. img (np.ndarray): The original image. Returns: tuple: A tuple c...
top_down_affine
python
ali-vilab/VACE
vace/annotators/dwpose/onnxpose.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxpose.py
Apache-2.0
def get_simcc_maximum(simcc_x: np.ndarray, simcc_y: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Get maximum response location and value from simcc representations. Note: instance number: N num_keypoints: K heatmap height: H heatmap width: W Args: ...
Get maximum response location and value from simcc representations. Note: instance number: N num_keypoints: K heatmap height: H heatmap width: W Args: simcc_x (np.ndarray): x-axis SimCC in shape (K, Wx) or (N, K, Wx) simcc_y (np.ndarray): y-axis SimCC in shape (...
get_simcc_maximum
python
ali-vilab/VACE
vace/annotators/dwpose/onnxpose.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxpose.py
Apache-2.0
def decode(simcc_x: np.ndarray, simcc_y: np.ndarray, simcc_split_ratio) -> Tuple[np.ndarray, np.ndarray]: """Modulate simcc distribution with Gaussian. Args: simcc_x (np.ndarray[K, Wx]): model predicted simcc in x. simcc_y (np.ndarray[K, Wy]): model predicted simcc in y. simc...
Modulate simcc distribution with Gaussian. Args: simcc_x (np.ndarray[K, Wx]): model predicted simcc in x. simcc_y (np.ndarray[K, Wy]): model predicted simcc in y. simcc_split_ratio (int): The split ratio of simcc. Returns: tuple: A tuple containing center and scale. - n...
decode
python
ali-vilab/VACE
vace/annotators/dwpose/onnxpose.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/dwpose/onnxpose.py
Apache-2.0
def load(self, path): """Load model from file. Args: path (str): file path """ parameters = torch.load(path, map_location=torch.device('cpu'), weights_only=True) if 'optimizer' in parameters: parameters = parameters['model'] self.load_state_dict...
Load model from file. Args: path (str): file path
load
python
ali-vilab/VACE
vace/annotators/midas/base_model.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/base_model.py
Apache-2.0
def __init__(self, scale_factor, mode, align_corners=False): """Init. Args: scale_factor (float): scaling mode (str): interpolation mode """ super(Interpolate, self).__init__() self.interp = nn.functional.interpolate self.scale_factor = scale_fac...
Init. Args: scale_factor (float): scaling mode (str): interpolation mode
__init__
python
ali-vilab/VACE
vace/annotators/midas/blocks.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/blocks.py
Apache-2.0
def forward(self, x): """Forward pass. Args: x (tensor): input Returns: tensor: interpolated data """ x = self.interp(x, scale_factor=self.scale_factor, mode=self.mode, align_corner...
Forward pass. Args: x (tensor): input Returns: tensor: interpolated data
forward
python
ali-vilab/VACE
vace/annotators/midas/blocks.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/blocks.py
Apache-2.0
def __init__(self, features): """Init. Args: features (int): number of features """ super().__init__() self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, ...
Init. Args: features (int): number of features
__init__
python
ali-vilab/VACE
vace/annotators/midas/blocks.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/blocks.py
Apache-2.0
def forward(self, x): """Forward pass. Args: x (tensor): input Returns: tensor: output """ out = self.relu(x) out = self.conv1(out) out = self.relu(out) out = self.conv2(out) return out + x
Forward pass. Args: x (tensor): input Returns: tensor: output
forward
python
ali-vilab/VACE
vace/annotators/midas/blocks.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/blocks.py
Apache-2.0
def __init__(self, features): """Init. Args: features (int): number of features """ super(FeatureFusionBlock, self).__init__() self.resConfUnit1 = ResidualConvUnit(features) self.resConfUnit2 = ResidualConvUnit(features)
Init. Args: features (int): number of features
__init__
python
ali-vilab/VACE
vace/annotators/midas/blocks.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/blocks.py
Apache-2.0
def __init__(self, features, activation, bn): """Init. Args: features (int): number of features """ super().__init__() self.bn = bn self.groups = 1 self.conv1 = nn.Conv2d(features, features, ...
Init. Args: features (int): number of features
__init__
python
ali-vilab/VACE
vace/annotators/midas/blocks.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/blocks.py
Apache-2.0
def forward(self, x): """Forward pass. Args: x (tensor): input Returns: tensor: output """ out = self.activation(x) out = self.conv1(out) if self.bn is True: out = self.bn1(out) out = self.activation(out) out...
Forward pass. Args: x (tensor): input Returns: tensor: output
forward
python
ali-vilab/VACE
vace/annotators/midas/blocks.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/blocks.py
Apache-2.0
def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True): """Init. Args: features (int): number of features """ super(FeatureFusion...
Init. Args: features (int): number of features
__init__
python
ali-vilab/VACE
vace/annotators/midas/blocks.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/blocks.py
Apache-2.0
def __init__(self, path=None, features=256, non_negative=True): """Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encoder. Defaults...
Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encoder. Defaults to resnet50
__init__
python
ali-vilab/VACE
vace/annotators/midas/midas_net.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/midas_net.py
Apache-2.0
def forward(self, x): """Forward pass. Args: x (tensor): input data (image) Returns: tensor: depth """ layer_1 = self.pretrained.layer1(x) layer_2 = self.pretrained.layer2(layer_1) layer_3 = self.pretrained.layer3(layer_2) layer_...
Forward pass. Args: x (tensor): input data (image) Returns: tensor: depth
forward
python
ali-vilab/VACE
vace/annotators/midas/midas_net.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/midas_net.py
Apache-2.0
def __init__(self, path=None, features=64, backbone='efficientnet_lite3', non_negative=True, exportable=True, channels_last=False, align_corners=True, blocks={'expand': True}): ...
Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256. backbone (str, optional): Backbone network for encoder. Defaults to resnet50
__init__
python
ali-vilab/VACE
vace/annotators/midas/midas_net_custom.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/midas_net_custom.py
Apache-2.0
def forward(self, x): """Forward pass. Args: x (tensor): input data (image) Returns: tensor: depth """ if self.channels_last is True: print('self.channels_last = ', self.channels_last) x.contiguous(memory_format=torch.channels_las...
Forward pass. Args: x (tensor): input data (image) Returns: tensor: depth
forward
python
ali-vilab/VACE
vace/annotators/midas/midas_net_custom.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/midas_net_custom.py
Apache-2.0
def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA): """Rezise the sample to ensure the given size. Keeps aspect ratio. Args: sample (dict): sample size (tuple): image size Returns: tuple: new size """ shape = list(sample['disparity'].shape) if ...
Rezise the sample to ensure the given size. Keeps aspect ratio. Args: sample (dict): sample size (tuple): image size Returns: tuple: new size
apply_min_size
python
ali-vilab/VACE
vace/annotators/midas/transforms.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/transforms.py
Apache-2.0
def __init__( self, width, height, resize_target=True, keep_aspect_ratio=False, ensure_multiple_of=1, resize_method='lower_bound', image_interpolation_method=cv2.INTER_AREA, ): """Init. Args: width (int): desired output wid...
Init. Args: width (int): desired output width height (int): desired output height resize_target (bool, optional): True: Resize the full sample (image, mask, target). False: Resize image only. Defaults to True. keep_...
__init__
python
ali-vilab/VACE
vace/annotators/midas/transforms.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/transforms.py
Apache-2.0
def read_pfm(path): """Read pfm file. Args: path (str): path to file Returns: tuple: (data, scale) """ with open(path, 'rb') as file: color = None width = None height = None scale = None endian = None header = file.readline().rstrip...
Read pfm file. Args: path (str): path to file Returns: tuple: (data, scale)
read_pfm
python
ali-vilab/VACE
vace/annotators/midas/utils.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/utils.py
Apache-2.0
def write_pfm(path, image, scale=1): """Write pfm file. Args: path (str): pathto file image (array): data scale (int, optional): Scale. Defaults to 1. """ with open(path, 'wb') as file: color = None if image.dtype.name != 'float32': raise Exception(...
Write pfm file. Args: path (str): pathto file image (array): data scale (int, optional): Scale. Defaults to 1.
write_pfm
python
ali-vilab/VACE
vace/annotators/midas/utils.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/utils.py
Apache-2.0
def read_image(path): """Read image and output RGB image (0-1). Args: path (str): path to file Returns: array: RGB image (0-1) """ img = cv2.imread(path) if img.ndim == 2: img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255...
Read image and output RGB image (0-1). Args: path (str): path to file Returns: array: RGB image (0-1)
read_image
python
ali-vilab/VACE
vace/annotators/midas/utils.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/utils.py
Apache-2.0
def resize_image(img): """Resize image and make it fit for network. Args: img (array): image Returns: tensor: data ready for network """ height_orig = img.shape[0] width_orig = img.shape[1] if width_orig > height_orig: scale = width_orig / 384 else: sca...
Resize image and make it fit for network. Args: img (array): image Returns: tensor: data ready for network
resize_image
python
ali-vilab/VACE
vace/annotators/midas/utils.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/utils.py
Apache-2.0
def resize_depth(depth, width, height): """Resize depth map and bring to CPU (numpy). Args: depth (tensor): depth width (int): image width height (int): image height Returns: array: processed depth """ depth = torch.squeeze(depth[0, :, :, :]).to('cpu') depth_re...
Resize depth map and bring to CPU (numpy). Args: depth (tensor): depth width (int): image width height (int): image height Returns: array: processed depth
resize_depth
python
ali-vilab/VACE
vace/annotators/midas/utils.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/utils.py
Apache-2.0
def write_depth(path, depth, bits=1): """Write depth map to pfm and png file. Args: path (str): filepath without extension depth (array): depth """ write_pfm(path + '.pfm', depth.astype(np.float32)) depth_min = depth.min() depth_max = depth.max() max_val = (2**(8 * bits)) ...
Write depth map to pfm and png file. Args: path (str): filepath without extension depth (array): depth
write_depth
python
ali-vilab/VACE
vace/annotators/midas/utils.py
https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/utils.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, indices_grid: torch.Tensor, source_latents: torch.Tensor = None, source_mask_latents: torch.Tensor = None, encoder_hidden_states: Optional[torch.Tensor] = None, timestep: Optional[torch.Lo...
The [`Transformer2DModel`] forward method. Args: hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous): Input `hidden_states`. indices_grid (`t...
forward
python
ali-vilab/VACE
vace/models/ltx/models/transformers/transformer3d.py
https://github.com/ali-vilab/VACE/blob/master/vace/models/ltx/models/transformers/transformer3d.py
Apache-2.0
def _resize_crop(self, img, oh, ow, normalize=True): """ Resize, center crop, convert to tensor, and normalize. """ # resize and crop iw, ih = img.size if iw != ow or ih != oh: # resize scale = max(ow / iw, oh / ih) img = img.resize( ...
Resize, center crop, convert to tensor, and normalize.
_resize_crop
python
ali-vilab/VACE
vace/models/utils/preprocessor.py
https://github.com/ali-vilab/VACE/blob/master/vace/models/utils/preprocessor.py
Apache-2.0