idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
31,400
def rtruncated_normal ( mu , tau , a = - np . inf , b = np . inf , size = None ) : sigma = 1. / np . sqrt ( tau ) na = utils . normcdf ( ( a - mu ) / sigma ) nb = utils . normcdf ( ( b - mu ) / sigma ) U = np . random . mtrand . uniform ( size = size ) q = U * nb + ( 1 - U ) * na R = utils . invcdf ( q ) return R * sig...
Random truncated normal variates .
31,401
def truncated_normal_expval ( mu , tau , a , b ) : phia = np . exp ( normal_like ( a , mu , tau ) ) phib = np . exp ( normal_like ( b , mu , tau ) ) sigma = 1. / np . sqrt ( tau ) Phia = utils . normcdf ( ( a - mu ) / sigma ) if b == np . inf : Phib = 1.0 else : Phib = utils . normcdf ( ( b - mu ) / sigma ) return ( mu...
Expected value of the truncated normal distribution .
31,402
def truncated_normal_like ( x , mu , tau , a = None , b = None ) : R x = np . atleast_1d ( x ) if a is None : a = - np . inf a = np . atleast_1d ( a ) if b is None : b = np . inf b = np . atleast_1d ( b ) mu = np . atleast_1d ( mu ) sigma = ( 1. / np . atleast_1d ( np . sqrt ( tau ) ) ) if ( x < a ) . any ( ) or ( x > ...
R Truncated normal log - likelihood .
31,403
def rskew_normal ( mu , tau , alpha , size = ( ) ) : size_ = size or ( 1 , ) len_ = np . prod ( size_ ) return flib . rskewnorm ( len_ , mu , tau , alpha , np . random . normal ( size = 2 * len_ ) ) . reshape ( size )
Skew - normal random variates .
31,404
def skew_normal_expval ( mu , tau , alpha ) : delta = alpha / np . sqrt ( 1. + alpha ** 2 ) return mu + np . sqrt ( 2 / pi / tau ) * delta
Expectation of skew - normal random variables .
31,405
def skew_normal_like ( x , mu , tau , alpha ) : R return flib . sn_like ( x , mu , tau , alpha )
R Azzalini s skew - normal log - likelihood
31,406
def rt ( nu , size = None ) : return rnormal ( 0 , 1 , size ) / np . sqrt ( rchi2 ( nu , size ) / nu )
Student s t random variates .
31,407
def t_like ( x , nu ) : R nu = np . asarray ( nu ) return flib . t ( x , nu )
R Student s T log - likelihood .
31,408
def rnoncentral_t ( mu , lam , nu , size = None ) : tau = rgamma ( nu / 2. , nu / ( 2. * lam ) , size ) return rnormal ( mu , tau )
Non - central Student s t random variates .
31,409
def noncentral_t_like ( x , mu , lam , nu ) : R mu = np . asarray ( mu ) lam = np . asarray ( lam ) nu = np . asarray ( nu ) return flib . nct ( x , mu , lam , nu )
R Non - central Student s T log - likelihood .
31,410
def rdiscrete_uniform ( lower , upper , size = None ) : return np . random . randint ( lower , upper + 1 , size )
Random discrete_uniform variates .
31,411
def runiform ( lower , upper , size = None ) : return np . random . uniform ( lower , upper , size )
Random uniform variates .
31,412
def rweibull ( alpha , beta , size = None ) : tmp = - np . log ( runiform ( 0 , 1 , size ) ) return beta * ( tmp ** ( 1. / alpha ) )
Weibull random variates .
31,413
def rwishart_cov ( n , C ) : p = np . shape ( C ) [ 0 ] sig = np . linalg . cholesky ( C ) if n <= ( p - 1 ) : raise ValueError ( 'Wishart parameter n must be greater ' 'than size of matrix.' ) norms = np . random . normal ( size = ( p * ( p - 1 ) ) // 2 ) chi_sqs = np . sqrt ( np . random . chisquare ( df = np . arang...
Return a Wishart random matrix .
31,414
def valuewrapper ( f , arguments = None ) : def wrapper ( ** kwds ) : value = kwds . pop ( 'value' ) return f ( value , ** kwds ) if arguments is None : wrapper . __dict__ . update ( f . __dict__ ) else : wrapper . __dict__ . update ( arguments ) return wrapper
Return a likelihood accepting value instead of x as a keyword argument . This is specifically intended for the instantiator above .
31,415
def local_decorated_likelihoods ( obj ) : for name , like in six . iteritems ( likelihoods ) : obj [ name + '_like' ] = gofwrapper ( like , snapshot )
New interface likelihoods
31,416
def _inject_dist ( distname , kwargs = { } , ns = locals ( ) ) : dist_logp , dist_random , grad_logp = name_to_funcs ( distname , ns ) classname = capitalize ( distname ) ns [ classname ] = stochastic_from_dist ( distname , dist_logp , dist_random , grad_logp , ** kwargs )
Reusable function to inject Stochastic subclasses into module namespace
31,417
def mod_categorical_expval ( p ) : p = extend_dirichlet ( p ) return np . sum ( [ p * i for i , p in enumerate ( p ) ] )
Expected value of categorical distribution with parent p of length k - 1 .
31,418
def Impute ( name , dist_class , imputable , ** parents ) : dims = np . shape ( imputable ) masked_values = np . ravel ( imputable ) if not isinstance ( masked_values , np . ma . core . MaskedArray ) : mask = [ v is None or np . isnan ( v ) for v in masked_values ] masked_values = np . ma . masked_array ( masked_values...
This function accomodates missing elements for the data of simple Stochastic distribution subclasses . The masked_values argument is an object of type numpy . ma . MaskedArray which contains the raw data and a boolean mask indicating missing values . The resulting list contains a list of stochastics of type dist_class ...
31,419
def logp_gradient_of_set ( variable_set , calculation_set = None ) : logp_gradients = { } for variable in variable_set : logp_gradients [ variable ] = logp_gradient ( variable , calculation_set ) return logp_gradients
Calculates the gradient of the joint log posterior with respect to all the variables in variable_set . Calculation of the log posterior is restricted to the variables in calculation_set .
31,420
def logp_gradient ( variable , calculation_set = None ) : return variable . logp_partial_gradient ( variable , calculation_set ) + sum ( [ child . logp_partial_gradient ( variable , calculation_set ) for child in variable . children ] )
Calculates the gradient of the joint log posterior with respect to variable . Calculation of the log posterior is restricted to the variables in calculation_set .
31,421
def summary ( self , alpha = 0.05 , start = 0 , batches = 100 , chain = None , roundto = 3 ) : statdict = self . stats ( alpha = alpha , start = start , batches = batches , chain = chain ) size = np . size ( statdict [ 'mean' ] ) print_ ( '\n%s:' % self . __name__ ) print_ ( ' ' ) buffer = [ ] iindex = [ key . split ( ...
Generate a pretty - printed summary of the node .
31,422
def file_items ( container , iterable ) : container . nodes = set ( ) container . variables = set ( ) container . deterministics = set ( ) container . stochastics = set ( ) container . potentials = set ( ) container . observed_stochastics = set ( ) container . containers = [ ] i = - 1 for item in iterable : if isinstan...
Files away objects into the appropriate attributes of the container .
31,423
def gas_price_strategy_middleware ( make_request , web3 ) : def middleware ( method , params ) : if method == 'eth_sendTransaction' : transaction = params [ 0 ] if 'gasPrice' not in transaction : generated_gas_price = web3 . eth . generateGasPrice ( transaction ) if generated_gas_price is not None : transaction = assoc...
Includes a gas price using the gas price strategy
31,424
def fill_transaction_defaults ( web3 , transaction ) : defaults = { } for key , default_getter in TRANSACTION_DEFAULTS . items ( ) : if key not in transaction : if callable ( default_getter ) : if web3 is not None : default_val = default_getter ( web3 , transaction ) else : raise ValueError ( "You must specify %s in th...
if web3 is None fill as much as possible while offline
31,425
def _compute_probabilities ( miner_data , wait_blocks , sample_size ) : miner_data_by_price = tuple ( sorted ( miner_data , key = operator . attrgetter ( 'low_percentile_gas_price' ) , reverse = True , ) ) for idx in range ( len ( miner_data_by_price ) ) : low_percentile_gas_price = miner_data_by_price [ idx ] . low_pe...
Computes the probabilities that a txn will be accepted at each of the gas prices accepted by the miners .
31,426
def _compute_gas_price ( probabilities , desired_probability ) : first = probabilities [ 0 ] last = probabilities [ - 1 ] if desired_probability >= first . prob : return int ( first . gas_price ) elif desired_probability <= last . prob : return int ( last . gas_price ) for left , right in sliding_window ( 2 , probabili...
Given a sorted range of Probability named - tuples returns a gas price computed based on where the desired_probability would fall within the range .
31,427
def construct_time_based_gas_price_strategy ( max_wait_seconds , sample_size = 120 , probability = 98 ) : def time_based_gas_price_strategy ( web3 , transaction_params ) : avg_block_time = _get_avg_block_time ( web3 , sample_size = sample_size ) wait_blocks = int ( math . ceil ( max_wait_seconds / avg_block_time ) ) ra...
A gas pricing strategy that uses recently mined block data to derive a gas price for which a transaction is likely to be mined within X seconds with probability P .
31,428
def default_middlewares ( web3 ) : return [ ( request_parameter_normalizer , 'request_param_normalizer' ) , ( gas_price_strategy_middleware , 'gas_price_strategy' ) , ( name_to_address_middleware ( web3 ) , 'name_to_address' ) , ( attrdict_middleware , 'attrdict' ) , ( pythonic_middleware , 'pythonic' ) , ( normalize_e...
List the default middlewares for the request manager . Leaving ens unspecified will prevent the middleware from resolving names .
31,429
def request_blocking ( self , method , params ) : response = self . _make_request ( method , params ) if "error" in response : raise ValueError ( response [ "error" ] ) return response [ 'result' ]
Make a synchronous request using the provider
31,430
async def coro_request ( self , method , params ) : response = await self . _coro_make_request ( method , params ) if "error" in response : raise ValueError ( response [ "error" ] ) if response [ 'result' ] is None : raise ValueError ( f"The call to {method} did not return a value." ) return response [ 'result' ]
Couroutine for making a request using the provider
31,431
def construct_fixture_middleware ( fixtures ) : def fixture_middleware ( make_request , web3 ) : def middleware ( method , params ) : if method in fixtures : result = fixtures [ method ] return { 'result' : result } else : return make_request ( method , params ) return middleware return fixture_middleware
Constructs a middleware which returns a static response for any method which is found in the provided fixtures .
31,432
def combine_middlewares ( middlewares , web3 , provider_request_fn ) : return functools . reduce ( lambda request_fn , middleware : middleware ( request_fn , web3 ) , reversed ( middlewares ) , provider_request_fn , )
Returns a callable function which will call the provider . provider_request function wrapped with all of the middlewares .
31,433
def get_event_data ( event_abi , log_entry ) : if event_abi [ 'anonymous' ] : log_topics = log_entry [ 'topics' ] elif not log_entry [ 'topics' ] : raise MismatchedABI ( "Expected non-anonymous event to have 1 or more topics" ) elif event_abi_to_log_topic ( event_abi ) != log_entry [ 'topics' ] [ 0 ] : raise Mismatched...
Given an event ABI and a log entry for that event return the decoded event data
31,434
def exception_retry_middleware ( make_request , web3 , errors , retries = 5 ) : def middleware ( method , params ) : if check_if_retry_on_failure ( method ) : for i in range ( retries ) : try : return make_request ( method , params ) except errors : if i < retries - 1 : continue else : raise else : return make_request ...
Creates middleware that retries failed HTTP requests . Is a default middleware for HTTPProvider .
31,435
def mod9710 ( iban ) : remainder = iban block = None while len ( remainder ) > 2 : block = remainder [ : 9 ] remainder = str ( int ( block ) % 97 ) + remainder [ len ( block ) : ] return int ( remainder ) % 97
Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064 .
31,436
def baseN ( num , b , numerals = "0123456789abcdefghijklmnopqrstuvwxyz" ) : return ( ( num == 0 ) and numerals [ 0 ] ) or ( baseN ( num // b , b , numerals ) . lstrip ( numerals [ 0 ] ) + numerals [ num % b ] )
This prototype should be used to create an iban object from iban correct string
31,437
def fromAddress ( address ) : 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 ( ) )
This method should be used to create an iban object from ethereum address
31,438
def address ( self ) : if self . isDirect ( ) : base36 = self . _iban [ 4 : ] asInt = int ( base36 , 36 ) return to_checksum_address ( pad_left_hex ( baseN ( asInt , 16 ) , 20 ) ) return ""
Should be called to get client direct address
31,439
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." , "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 ,...
Returns 2 - tuple ranges describing ranges of block from start_block to last_block
31,440
def get_logs_multipart ( w3 , startBlock , stopBlock , address , topics , 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...
Used to break up requests to eth_getLogs
31,441
def method_selector_fn ( self ) : 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" )
Gets the method selector from the config .
31,442
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 ( abi_type ) if is_array_type ( abi_type ) : sub_type = sub_type_of_array_type ( abi_type ) return "" . join ( [ remove_0x_prefix ( hex_encode_...
Encodes value into a hex string in format of abi_type
31,443
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 ( value ) hex_value = hex_value . rstrip ( "L" ) return hex_value
Converts integer value to twos compliment hex representation with given bit_size
31,444
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
31,445
def to_int ( value = None , hexstr = None , text = None ) : 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 ) : rai...
Converts value to it s integer representation .
31,446
def deploy_new_instance ( cls , w3 : Web3 ) -> "VyperReferenceRegistry" : 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 . ...
Returns a new instance of VyperReferenceRegistry representing a freshly deployed instance on the given web3 instance of the Vyper Reference Registry implementation .
31,447
def transfer_owner ( self , new_owner : Address ) -> TxReceipt : tx_hash = self . registry . functions . transferOwner ( new_owner ) . transact ( ) return self . w3 . eth . waitForTransactionReceipt ( tx_hash )
Transfers ownership of this registry instance to the given new_owner . Only the owner is allowed to transfer ownership .
31,448
def release_package ( self , package_name : str , version : str , manifest_uri : str ) -> bytes : 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_...
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 .
31,449
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_ids : yield self . registry . _get_package_name ( package_id )
Returns a tuple containing all the package names available on the current registry .
31,450
def get_release_count ( self , package_name : str ) -> int : validate_package_name ( package_name ) self . _validate_set_registry ( ) return self . registry . _num_release_ids ( package_name )
Returns the number of releases of the given package name available on the current registry .
31,451
def get_release_id ( self , package_name : str , version : str ) -> bytes : validate_package_name ( package_name ) validate_package_version ( version ) self . _validate_set_registry ( ) return self . registry . _get_release_id ( package_name , version )
Returns the 32 byte identifier of a release for the given package name and version if they are available on the current registry .
31,452
def get_package ( self , package_name : str , version : str ) -> Package : 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 )
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 .
31,453
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 tuple ( ( normalize_to_text ( value ) for value in data_value ) ) else : return normalize_to_text ( data_value ) return data_value
Decodes utf - 8 bytes to strings for abi string values .
31,454
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 data_value , match_values , abi_type in zip ( decoded_values , all_match_values , abi_types ) : if match_values is None : continue normalized_dat...
Match function used for filtering non - indexed event arguments .
31,455
def attrdict_middleware ( make_request , web3 ) : 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...
Converts any result which is a dictionary into an a
31,456
def fromWeb3 ( cls , web3 , addr = None ) : return cls ( web3 . manager . provider , addr = addr )
Generate an ENS instance with web3
31,457
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 .
31,458
def setup_address ( self , name , address = default , transact = { } ) : 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_c...
Set up the name to point to the supplied address . The sender of the transaction must own the name or its parent name .
31,459
def setup_owner ( self , name , new_owner = default , transact = { } ) : ( 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 ( ...
Set the owner of the supplied name to new_owner .
31,460
def _first_owner ( self , name ) : 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 , u...
Takes a name and returns the owner of the deepest subdomain that has an owner
31,461
def call_contract_function ( web3 , address , normalizers , function_identifier , transaction , block_id = None , contract_abi = None , fn_abi = None , * args , ** kwargs ) : call_transaction = prepare_transaction ( address , web3 , fn_identifier = function_identifier , contract_abi = contract_abi , fn_abi = fn_abi , t...
Helper function for interacting with a contract function using the eth_call API .
31,462
def transact_with_contract_function ( address , web3 , function_name = None , transaction = None , contract_abi = None , fn_abi = None , * args , ** kwargs ) : transact_transaction = prepare_transaction ( address , web3 , fn_identifier = function_name , contract_abi = contract_abi , transaction = transaction , fn_abi =...
Helper function for interacting with a contract function by sending a transaction .
31,463
def estimate_gas_for_function ( address , web3 , fn_identifier = None , transaction = None , contract_abi = None , fn_abi = None , * args , ** kwargs ) : estimate_transaction = prepare_transaction ( address , web3 , fn_identifier = fn_identifier , contract_abi = contract_abi , fn_abi = fn_abi , transaction = transactio...
Estimates gas cost a function call would take .
31,464
def build_transaction_for_function ( address , web3 , function_name = None , transaction = None , contract_abi = None , fn_abi = None , * args , ** kwargs ) : prepared_transaction = prepare_transaction ( address , web3 , fn_identifier = function_name , contract_abi = contract_abi , fn_abi = fn_abi , transaction = trans...
Builds a dictionary with the fields required to make the given transaction
31,465
def encodeABI ( cls , fn_name , args = None , kwargs = None , data = None ) : 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 )
Encodes the arguments using the Ethereum ABI for the contract function that matches the given name and arguments ..
31,466
def call ( self , transaction = None , block_identifier = 'latest' ) : 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' , s...
Execute a contract function call using the eth_call interface .
31,467
def getLogs ( self , argument_filters = None , fromBlock = None , toBlock = None , blockHash = None ) : 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 ( ) _filte...
Get events for this contract instance using eth_getLogs API .
31,468
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
copy dict keyword args to avoid modifying caller s copy
31,469
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' % label ) else : return label
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 .
31,470
def map_collection ( func , collection ) : 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 ,...
Apply func to each element of a collection or value of a dictionary . If the value is not a collection return it unmodified
31,471
def percentile ( values = None , percentile = None ) : 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 ( perc...
Calculates a simplified weighted average percentile
31,472
def _repr_pretty_ ( self , builder , cycle ) : builder . text ( self . __class__ . __name__ + "(" ) if cycle : builder . text ( "<cycle>" ) else : builder . pretty ( self . __dict__ ) builder . text ( ")" )
Custom pretty output for the IPython console
31,473
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 != 0 and layer != len ( self . _queue ) : raise NotImplementedError ( "You can only insert to the beginning or end of a %s, currently. " "You tried to inser...
Inject a named element to an arbitrary layer in the onion .
31,474
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 = compose ( format_transaction , fill_transaction_defaults ( w3 ) , fill_nonce ( w3 ) ) def middleware ( metho...
Capture transactions sign and send as raw transactions
31,475
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 ValueError ( "'abi' is not a list of dictionaries" ) functions = filter_by_type ( 'function' , abi ) selectors = groupby ( compose ( encode_hex , function_abi_to_4byte_se...
Helper function for validating an ABI
31,476
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 ) return if not isinstance ( value , str ) : raise TypeError ( 'Address {} must be provided as a string' . format ( value ) ) if not is_hex_add...
Helper function for validating an address
31,477
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 = cache_class ( ) lock = threading . Lock ( ) def middleware ( method , params ) : lock_acquired = lock . acquire ( blocking ...
Constructs a middleware which caches responses based on the request method and params
31,478
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_request , web3 ) : cache = cache_class ( ) lock = threading . Lock ( ) def middleware ( method , params ) : lo...
Constructs a middleware which caches responses based on the request method and params for a maximum amount of time as specified
31,479
def reject_recursive_repeats ( to_wrap ) : 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 : ...
Prevent simple cycles by returning None when called recursively with same instance
31,480
def get_tuple_type_str_parts ( s : str ) -> Optional [ Tuple [ str , Optional [ str ] ] ] : 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
Takes a JSON ABI type string . For tuple type strings returns the separated prefix and array dimension parts . For all other strings returns None .
31,481
def _align_abi_input ( arg_abi , arg ) : tuple_parts = get_tuple_type_str_parts ( arg_abi [ 'type' ] ) if tuple_parts is None : return arg tuple_prefix , tuple_dims = tuple_parts if tuple_dims is None : sub_abis = arg_abi [ 'components' ] else : new_abi = copy . copy ( arg_abi ) new_abi [ 'type' ] = tuple_prefix sub_ab...
Aligns the values of any mapping at any level of nesting in arg according to the layout of the corresponding abi spec .
31,482
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' : return 8 if abi_type == 'address' : return 160 return int ( re . sub ( r"\D" , "" , abi_type ) )
Returns size in bits of abi_type
31,483
def ix ( self , word ) : temp = np . where ( self . vocab == word ) [ 0 ] if temp . size == 0 : raise KeyError ( "Word not in vocabulary" ) else : return temp [ 0 ]
Returns the index on self . vocab and self . clusters for word
31,484
def get_cluster ( self , word ) : idx = self . ix ( word ) return self . clusters [ idx ]
Returns the cluster number for a word in the vocabulary
31,485
def closest ( self , vector , n = 10 , metric = "cosine" ) : distances = distance ( self . vectors , vector , metric = metric ) best = np . argsort ( distances ) [ : : - 1 ] [ 1 : n + 1 ] best_metrics = distances [ best ] return best , best_metrics
Returns the closest n words to a vector
31,486
def similar ( self , word , n = 10 , metric = "cosine" ) : return self . closest ( self [ word ] , n = n , metric = metric )
Return similar words based on a metric
31,487
def analogy ( self , pos , neg , n = 10 , metric = "cosine" ) : 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 = dist...
Analogy similarity .
31,488
def from_binary ( cls , fname , vocab_unicode_size = 78 , desired_vocab = None , encoding = "utf-8" , new_lines = True , ) : 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" % vocab_unico...
Create a WordVectors class based on a word2vec binary file
31,489
def from_text ( cls , fname , vocabUnicodeSize = 78 , desired_vocab = None , encoding = "utf-8" ) : 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 . em...
Create a WordVectors class based on a word2vec text file
31,490
def from_mmap ( cls , fname ) : memmaped = joblib . load ( fname , mmap_mode = "r+" ) return cls ( vocab = memmaped . vocab , vectors = memmaped . vectors )
Create a WordVectors class from a memory map
31,491
def distance ( a , b , metric = "cosine" ) : if metric == "cosine" : return np . dot ( a , b . T ) raise Exception ( "Unknown metric '{metric}'" . format ( metric = metric ) )
Calculate distance between two vectors based on a Metric
31,492
def load ( fname , kind = "auto" , * args , ** kwargs ) : 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 ) e...
Loads a word vectors file
31,493
def iterate ( self ) : self . counter += 1 self . counter0 += 1 self . revcounter -= 1 self . revcounter0 -= 1 self . first = False self . last = ( self . revcounter0 == self . len_values - 1 )
Updates values as if we had iterated over the for
31,494
def get_render ( self , context ) : 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 ...
Returns a Context object with all the necessary stuff for rendering the form
31,495
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 .
31,496
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 tab return None
Returns the first container with errors otherwise returns None .
31,497
def open_target_group_for_form ( self , form ) : 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
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 .
31,498
def render_link ( self , template_pack = TEMPLATE_PACK , ** kwargs ) : link_template = self . link_template % template_pack return render_to_string ( link_template , { 'link' : self } )
Render the link for the tab - pane . It must be called after render so css_class is updated with active if needed .
31,499
def wrapped_object ( self , LayoutClass , fields , * args , ** kwargs ) : 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 ) els...
Returns a layout object of type LayoutClass with args and kwargs that wraps fields inside .