idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
246,000
def set_sum_w2 ( self , w , ix , iy = 0 , iz = 0 ) : if self . GetSumw2N ( ) == 0 : raise RuntimeError ( "Attempting to access Sumw2 in histogram " "where weights were not stored" ) xl = self . nbins ( axis = 0 , overflow = True ) yl = self . nbins ( axis = 1 , overflow = True ) idx = xl * yl * iz + xl * iy + ix if not...
Sets the true number of entries in the bin weighted by w^2
163
15
246,001
def rebinned ( self , bins , axis = 0 ) : ndim = self . GetDimension ( ) if axis >= ndim : raise ValueError ( "axis must be less than the dimensionality of the histogram" ) if isinstance ( bins , int ) : _bins = [ 1 ] * ndim try : _bins [ axis ] = bins except IndexError : raise ValueError ( "axis must be 0, 1, or 2" ) ...
Return a new rebinned histogram
714
8
246,002
def smoothed ( self , iterations = 1 ) : copy = self . Clone ( shallow = True ) copy . Smooth ( iterations ) return copy
Return a smoothed copy of this histogram
29
9
246,003
def empty_clone ( self , binning = None , axis = 0 , type = None , * * kwargs ) : ndim = self . GetDimension ( ) if binning is False and ndim == 1 : raise ValueError ( "cannot remove the x-axis of a 1D histogram" ) args = [ ] for iaxis in range ( ndim ) : if iaxis == axis : if binning is False : # skip this axis contin...
Return a new empty histogram . The binning may be modified along one axis by specifying the binning and axis arguments . If binning is False then the corresponding axis is dropped from the returned histogram .
219
42
246,004
def poisson_errors ( self ) : graph = Graph ( self . nbins ( axis = 0 ) , type = 'asymm' ) graph . SetLineWidth ( self . GetLineWidth ( ) ) graph . SetMarkerSize ( self . GetMarkerSize ( ) ) chisqr = ROOT . TMath . ChisquareQuantile npoints = 0 for bin in self . bins ( overflow = False ) : entries = bin . effective_ent...
Return a TGraphAsymmErrors representation of this histogram where the point y errors are Poisson .
260
22
246,005
def attach_event_handler ( canvas , handler = close_on_esc_or_middlemouse ) : if getattr ( canvas , "_py_event_dispatcher_attached" , None ) : return event_dispatcher = C . TPyDispatcherProcessedEvent ( handler ) canvas . Connect ( "ProcessedEvent(int,int,int,TObject*)" , "TPyDispatcherProcessedEvent" , event_dispatche...
Attach a handler function to the ProcessedEvent slot defaulting to closing when middle mouse is clicked or escape is pressed
151
23
246,006
def _num_to_string ( self , number , pad_to_length = None ) : output = "" while number : number , digit = divmod ( number , self . _alpha_len ) output += self . _alphabet [ digit ] if pad_to_length : remainder = max ( pad_to_length - len ( output ) , 0 ) output = output + self . _alphabet [ 0 ] * remainder return outpu...
Convert a number to a string using the given alphabet .
93
12
246,007
def _string_to_int ( self , string ) : number = 0 for char in string [ : : - 1 ] : number = number * self . _alpha_len + self . _alphabet . index ( char ) return number
Convert a string to a number using the given alphabet ..
50
12
246,008
def uuid ( self , name = None , pad_length = 22 ) : # If no name is given, generate a random UUID. if name is None : uuid = _uu . uuid4 ( ) elif "http" not in name . lower ( ) : uuid = _uu . uuid5 ( _uu . NAMESPACE_DNS , name ) else : uuid = _uu . uuid5 ( _uu . NAMESPACE_URL , name ) return self . encode ( uuid , pad_l...
Generate and return a UUID .
118
8
246,009
def fit ( self , data = 'obsData' , model_config = 'ModelConfig' , param_const = None , param_values = None , param_ranges = None , poi_const = False , poi_value = None , poi_range = None , extended = False , num_cpu = 1 , process_strategy = 0 , offset = False , print_level = None , return_nll = False , * * kwargs ) : ...
Fit a pdf to data in a workspace
664
8
246,010
def ensure_trafaret ( trafaret ) : if isinstance ( trafaret , Trafaret ) : return trafaret elif isinstance ( trafaret , type ) : if issubclass ( trafaret , Trafaret ) : return trafaret ( ) # str, int, float are classes, but its appropriate to use them # as trafaret functions return Call ( lambda val : trafaret ( val ) ...
Helper for complex trafarets takes trafaret instance or class and returns trafaret instance
137
19
246,011
def DictKeys ( keys ) : req = [ ( Key ( key ) , Any ) for key in keys ] return Dict ( dict ( req ) )
Checks if dict has all given keys
33
8
246,012
def guard ( trafaret = None , * * kwargs ) : if ( trafaret and not isinstance ( trafaret , Dict ) and not isinstance ( trafaret , Forward ) ) : raise RuntimeError ( "trafaret should be instance of Dict or Forward" ) elif trafaret and kwargs : raise RuntimeError ( "choose one way of initialization," " trafaret or kwargs...
Decorator for protecting function with trafarets
364
10
246,013
def _clone_args ( self ) : keys = list ( self . keys ) kw = { } if self . allow_any or self . extras : kw [ 'allow_extra' ] = list ( self . extras ) if self . allow_any : kw [ 'allow_extra' ] . append ( '*' ) kw [ 'allow_extra_trafaret' ] = self . extras_trafaret if self . ignore_any or self . ignore : kw [ 'ignore_ext...
return args to create new Dict clone
148
8
246,014
def merge ( self , other ) : ignore = self . ignore extra = self . extras if isinstance ( other , Dict ) : other_keys = other . keys ignore += other . ignore extra += other . extras elif isinstance ( other , ( list , tuple ) ) : other_keys = list ( other ) elif isinstance ( other , dict ) : return self . __class__ ( ot...
Extends one Dict with other Dict Key s or Key s list or dict instance supposed for Dict
145
22
246,015
def get_deep_attr ( obj , keys ) : cur = obj for k in keys : if isinstance ( cur , Mapping ) and k in cur : cur = cur [ k ] continue else : try : cur = getattr ( cur , k ) continue except AttributeError : pass raise DataError ( error = 'Unexistent key' ) return cur
Helper for DeepKey
76
4
246,016
def construct ( arg ) : if isinstance ( arg , t . Trafaret ) : return arg elif isinstance ( arg , tuple ) or ( isinstance ( arg , list ) and len ( arg ) > 1 ) : return t . Tuple ( * ( construct ( a ) for a in arg ) ) elif isinstance ( arg , list ) : # if len(arg) == 1 return t . List ( construct ( arg [ 0 ] ) ) elif is...
Shortcut syntax to define trafarets .
240
9
246,017
def subdict ( name , * keys , * * kw ) : trafaret = kw . pop ( 'trafaret' ) # coz py2k def inner ( data , context = None ) : errors = False preserve_output = [ ] touched = set ( ) collect = { } for key in keys : for k , v , names in key ( data , context = context ) : touched . update ( names ) preserve_output . append ...
Subdict key .
161
4
246,018
def xor_key ( first , second , trafaret ) : trafaret = t . Trafaret . _trafaret ( trafaret ) def check_ ( value ) : if ( first in value ) ^ ( second in value ) : key = first if first in value else second yield first , t . catch_error ( trafaret , value [ key ] ) , ( key , ) elif first in value and second in value : yie...
xor_key - takes first and second key names and trafaret .
225
16
246,019
def confirm_key ( name , confirm_name , trafaret ) : def check_ ( value ) : first , second = None , None if name in value : first = value [ name ] else : yield name , t . DataError ( 'is required' ) , ( name , ) if confirm_name in value : second = value [ confirm_name ] else : yield confirm_name , t . DataError ( 'is r...
confirm_key - takes name confirm_name and trafaret .
191
15
246,020
def get_capacity ( self , legacy = None ) : params = None if legacy : params = { 'legacy' : legacy } return self . call_api ( '/capacity' , params = params ) [ 'capacity' ]
Get capacity of all facilities .
48
6
246,021
def altcore_data ( self ) : ret = [ ] for symbol in self . supported_currencies ( project = 'altcore' , level = "address" ) : data = crypto_data [ symbol ] priv = data . get ( 'private_key_prefix' ) pub = data . get ( 'address_version_byte' ) hha = data . get ( 'header_hash_algo' ) shb = data . get ( 'script_hash_byte'...
Returns the crypto_data for all currencies defined in moneywagon that also meet the minimum support for altcore . Data is keyed according to the bitcore specification .
486
33
246,022
def from_unit_to_satoshi ( self , value , unit = 'satoshi' ) : if not unit or unit == 'satoshi' : return value if unit == 'bitcoin' or unit == 'btc' : return value * 1e8 # assume fiat currency that we can convert convert = get_current_price ( self . crypto , unit ) return int ( value / convert * 1e8 )
Convert a value to satoshis . units can be any fiat currency . By default the unit is satoshi .
88
24
246,023
def _get_utxos ( self , address , services , * * modes ) : return get_unspent_outputs ( self . crypto , address , services = services , * * modes )
Using the service fallback engine get utxos from remote service .
43
14
246,024
def total_input_satoshis ( self ) : just_inputs = [ x [ 'input' ] for x in self . ins ] return sum ( [ x [ 'amount' ] for x in just_inputs ] )
Add up all the satoshis coming from all input tx s .
50
14
246,025
def select_inputs ( self , amount ) : sorted_txin = sorted ( self . ins , key = lambda x : - x [ 'input' ] [ 'confirmations' ] ) total_amount = 0 for ( idx , tx_in ) in enumerate ( sorted_txin ) : total_amount += tx_in [ 'input' ] [ 'amount' ] if ( total_amount >= amount ) : break sorted_txin = sorted ( sorted_txin [ :...
Maximize transaction priority . Select the oldest inputs that are sufficient to cover the spent amount . Then remove any unneeded inputs starting with the smallest in value . Returns sum of amounts of inputs selected
199
38
246,026
def onchain_exchange ( self , withdraw_crypto , withdraw_address , value , unit = 'satoshi' ) : self . onchain_rate = get_onchain_exchange_rates ( self . crypto , withdraw_crypto , best = True , verbose = self . verbose ) exchange_rate = float ( self . onchain_rate [ 'rate' ] ) result = self . onchain_rate [ 'service' ...
This method is like add_output but it sends to another
248
12
246,027
def fee ( self , value = None , unit = 'satoshi' ) : convert = None if not value : # no fee was specified, use $0.02 as default. convert = get_current_price ( self . crypto , "usd" ) self . fee_satoshi = int ( 0.02 / convert * 1e8 ) verbose = "Using default fee of:" elif value == 'optimal' : self . fee_satoshi = get_op...
Set the miner fee if unit is not set assumes value is satoshi . If using optimal make sure you have already added all outputs .
242
27
246,028
def get_hex ( self , signed = True ) : total_ins_satoshi = self . total_input_satoshis ( ) if total_ins_satoshi == 0 : raise ValueError ( "Can't make transaction, there are zero inputs" ) # Note: there can be zero outs (sweep or coalesc transactions) total_outs_satoshi = sum ( [ x [ 'value' ] for x in self . outs ] ) i...
Given all the data the user has given so far make the hex using pybitcointools
417
19
246,029
def get_current_price ( crypto , fiat , services = None , convert_to = None , helper_prices = None , * * modes ) : fiat = fiat . lower ( ) args = { 'crypto' : crypto , 'fiat' : fiat , 'convert_to' : convert_to } if not services : services = get_optimal_services ( crypto , 'current_price' ) if fiat in services : # first...
High level function for getting current exchange rate for a cryptocurrency . If the fiat value is not explicitly defined it will try the wildcard service . if that does not work it tries converting to an intermediate cryptocurrency if available .
537
43
246,030
def get_onchain_exchange_rates ( deposit_crypto = None , withdraw_crypto = None , * * modes ) : from moneywagon . onchain_exchange import ALL_SERVICES rates = [ ] for Service in ALL_SERVICES : srv = Service ( verbose = modes . get ( 'verbose' , False ) ) rates . extend ( srv . onchain_exchange_rates ( ) ) if deposit_cr...
Gets exchange rates for all defined on - chain exchange services .
207
13
246,031
def generate_keypair ( crypto , seed , password = None ) : if crypto in [ 'eth' , 'etc' ] : raise CurrencyNotSupported ( "Ethereums not yet supported" ) pub_byte , priv_byte = get_magic_bytes ( crypto ) priv = sha256 ( seed ) pub = privtopub ( priv ) priv_wif = encode_privkey ( priv , 'wif_compressed' , vbyte = priv_by...
Generate a private key and publickey for any currency given a seed . That seed can be random or a brainwallet phrase .
363
26
246,032
def sweep ( crypto , private_key , to_address , fee = None , password = None , * * modes ) : from moneywagon . tx import Transaction tx = Transaction ( crypto , verbose = modes . get ( 'verbose' , False ) ) tx . add_inputs ( private_key = private_key , password = password , * * modes ) tx . change_address = to_address ...
Move all funds by private key to another address .
98
10
246,033
def guess_currency_from_address ( address ) : if is_py2 : fixer = lambda x : int ( x . encode ( 'hex' ) , 16 ) else : fixer = lambda x : x # does nothing first_byte = fixer ( b58decode_check ( address ) [ 0 ] ) double_first_byte = fixer ( b58decode_check ( address ) [ : 2 ] ) hits = [ ] for currency , data in crypto_da...
Given a crypto address find which currency it likely belongs to . Raises an exception if it can t find a match . Raises exception if address is invalid .
200
32
246,034
def service_table ( format = 'simple' , authenticated = False ) : if authenticated : all_services = ExchangeUniverse . get_authenticated_services ( ) else : all_services = ALL_SERVICES if format == 'html' : linkify = lambda x : "<a href='{0}' target='_blank'>{0}</a>" . format ( x ) else : linkify = lambda x : x ret = [...
Returns a string depicting all services currently installed .
211
9
246,035
def find_pair ( self , crypto = "" , fiat = "" , verbose = False ) : self . fetch_pairs ( ) if not crypto and not fiat : raise Exception ( "Fiat or Crypto required" ) def is_matched ( crypto , fiat , pair ) : if crypto and not fiat : return pair . startswith ( "%s-" % crypto ) if crypto and fiat : return pair == "%s-%s...
This utility is used to find an exchange that supports a given exchange pair .
177
15
246,036
def all_balances ( currency , services = None , verbose = False , timeout = None ) : balances = { } if not services : services = [ x ( verbose = verbose , timeout = timeout ) for x in ExchangeUniverse . get_authenticated_services ( ) ] for e in services : try : balances [ e ] = e . get_exchange_balance ( currency ) exc...
Get balances for passed in currency for all exchanges .
143
10
246,037
def total_exchange_balances ( services = None , verbose = None , timeout = None , by_service = False ) : balances = defaultdict ( lambda : 0 ) if not services : services = [ x ( verbose = verbose , timeout = timeout ) for x in ExchangeUniverse . get_authenticated_services ( ) ] for e in services : try : more_balances =...
Returns all balances for all currencies for all exchanges
198
9
246,038
def compress ( x , y ) : polarity = "02" if y % 2 == 0 else "03" wrap = lambda x : x if not is_py2 : wrap = lambda x : bytes ( x , 'ascii' ) return unhexlify ( wrap ( "%s%0.64x" % ( polarity , x ) ) )
Given a x y coordinate encode in compressed format Returned is always 33 bytes .
77
16
246,039
def decrypt ( self , passphrase , wif = False ) : passphrase = normalize ( 'NFC' , unicode ( passphrase ) ) if is_py2 : passphrase = passphrase . encode ( 'utf8' ) if self . ec_multiply : raise Exception ( "Not supported yet" ) key = scrypt . hash ( passphrase , self . addresshash , 16384 , 8 , 8 ) derivedhalf1 = key [...
BIP0038 non - ec - multiply decryption . Returns hex privkey .
395
16
246,040
def encrypt ( cls , crypto , privkey , passphrase ) : pub_byte , priv_byte = get_magic_bytes ( crypto ) privformat = get_privkey_format ( privkey ) if privformat in [ 'wif_compressed' , 'hex_compressed' ] : compressed = True flagbyte = b'\xe0' if privformat == 'wif_compressed' : privkey = encode_privkey ( privkey , 'he...
BIP0038 non - ec - multiply encryption . Returns BIP0038 encrypted privkey .
520
19
246,041
def create_from_intermediate ( cls , crypto , intermediate_point , seed , compressed = True , include_cfrm = True ) : flagbyte = b'\x20' if compressed else b'\x00' payload = b58decode_check ( str ( intermediate_point ) ) ownerentropy = payload [ 8 : 16 ] passpoint = payload [ 16 : - 4 ] x , y = uncompress ( passpoint )...
Given an intermediate point given to us by owner generate an address and encrypted private key that can be decoded by the passphrase used to generate the intermediate point .
574
32
246,042
def generate_address ( self , passphrase ) : inter = Bip38IntermediatePoint . create ( passphrase , ownersalt = self . ownersalt ) public_key = privtopub ( inter . passpoint ) # from Bip38EncryptedPrivateKey.create_from_intermediate derived = scrypt . hash ( inter . passpoint , self . addresshash + inter . ownerentropy...
Make sure the confirm code is valid for the given password and address .
252
14
246,043
def push_tx ( self , crypto , tx_hex ) : url = "%s/pushtx" % self . base_url return self . post_url ( url , { 'hex' : tx_hex } ) . content
This method is untested .
49
6
246,044
def replay_block ( self , block_to_replay , limit = 5 ) : if block_to_replay == 'latest' : if self . verbose : print ( "Getting latest %s block header" % source . upper ( ) ) block = get_block ( self . source , latest = True , verbose = self . verbose ) if self . verbose : print ( "Latest %s block is #%s" % ( self . so...
Replay all transactions in parent currency to passed in source currency . Block_to_replay can either be an integer or a block object .
457
29
246,045
def get_block_adjustments ( crypto , points = None , intervals = None , * * modes ) : from moneywagon import get_block all_points = [ ] if intervals : latest_block_height = get_block ( crypto , latest = True , * * modes ) [ 'block_number' ] interval = int ( latest_block_height / float ( intervals ) ) all_points = [ x *...
This utility is used to determine the actual block rate . The output can be directly copied to the blocktime_adjustments setting .
283
26
246,046
def _per_era_supply ( self , block_height ) : coins = 0 for era in self . supply_data [ 'eras' ] : end_block = era [ 'end' ] start_block = era [ 'start' ] reward = era [ 'reward' ] if not end_block or block_height <= end_block : blocks_this_era = block_height - start_block coins += blocks_this_era * reward break blocks...
Calculate the coin supply based on eras defined in crypto_data . Some currencies don t have a simple algorithmically defined halfing schedule so coins supply has to be defined explicitly per era .
124
39
246,047
def _prepare_consensus ( FetcherClass , results ) : # _get_results returns lists of 2 item list, first element is service, second is the returned value. # when determining consensus amoung services, only take into account values returned. if hasattr ( FetcherClass , "strip_for_consensus" ) : to_compare = [ FetcherClass...
Given a list of results return a list that is simplified to make consensus determination possible . Returns two item tuple first arg is simplified list the second argument is a list of all services used in making these results .
140
41
246,048
def _get_results ( FetcherClass , services , kwargs , num_results = None , fast = 0 , verbose = False , timeout = None ) : results = [ ] if not num_results or fast : num_results = len ( services ) with futures . ThreadPoolExecutor ( max_workers = len ( services ) ) as executor : fetches = { } for service in services [ ...
Does the fetching in multiple threads of needed . Used by paranoid and fast mode .
320
17
246,049
def _do_private_mode ( FetcherClass , services , kwargs , random_wait_seconds , timeout , verbose ) : addresses = kwargs . pop ( 'addresses' ) results = { } with futures . ThreadPoolExecutor ( max_workers = len ( addresses ) ) as executor : fetches = { } for address in addresses : k = kwargs k [ 'address' ] = address r...
Private mode is only applicable to address_balance unspent_outputs and historical_transactions . There will always be a list for the addresses argument . Each address goes to a random service . Also a random delay is performed before the external fetch for improved privacy .
254
54
246,050
def currency_to_protocol ( amount ) : if type ( amount ) in [ float , int ] : amount = "%.8f" % amount return int ( amount . replace ( "." , '' ) )
Convert a string of currency units to protocol units . For instance converts 19 . 1 bitcoin to 1910000000 satoshis .
45
25
246,051
def to_rawtx ( tx ) : if tx . get ( 'hex' ) : return tx [ 'hex' ] new_tx = { } locktime = tx . get ( 'locktime' , 0 ) new_tx [ 'locktime' ] = locktime new_tx [ 'version' ] = tx . get ( 'version' , 1 ) new_tx [ 'ins' ] = [ { 'outpoint' : { 'hash' : str ( x [ 'txid' ] ) , 'index' : x [ 'n' ] } , 'script' : str ( x [ 'scr...
Take a tx object in the moneywagon format and convert it to the format that pybitcointools s serialize funcion takes then return in raw hex format .
238
34
246,052
def check_error ( self , response ) : if response . status_code == 500 : raise ServiceError ( "500 - " + response . content ) if response . status_code == 503 : if "DDoS protection by Cloudflare" in response . content : raise ServiceError ( "Foiled by Cloudfare's DDoS protection" ) raise ServiceError ( "503 - Temporari...
If the service is returning an error this function should raise an exception . such as SkipThisService
149
19
246,053
def convert_currency ( self , base_fiat , base_amount , target_fiat ) : url = "http://api.fixer.io/latest?base=%s" % base_fiat data = self . get_url ( url ) . json ( ) try : return data [ 'rates' ] [ target_fiat . upper ( ) ] * base_amount except KeyError : raise Exception ( "Can not convert %s to %s" % ( base_fiat , t...
Convert one fiat amount to another fiat . Uses the fixer . io service .
113
17
246,054
def fix_symbol ( self , symbol , reverse = False ) : if not self . symbol_mapping : return symbol for old , new in self . symbol_mapping : if reverse : if symbol == new : return old else : if symbol == old : return new return symbol
In comes a moneywagon format symbol and returned in the symbol converted to one the service can understand .
59
20
246,055
def parse_market ( self , market , split_char = '_' ) : crypto , fiat = market . lower ( ) . split ( split_char ) return ( self . fix_symbol ( crypto , reverse = True ) , self . fix_symbol ( fiat , reverse = True ) )
In comes the market identifier directly from the service . Returned is the crypto and fiat identifier in moneywagon format .
64
23
246,056
def make_market ( self , crypto , fiat , seperator = "_" ) : return ( "%s%s%s" % ( self . fix_symbol ( crypto ) , seperator , self . fix_symbol ( fiat ) ) ) . lower ( )
Convert a crypto and fiat to a market string . All exchanges use their own format for specifying markets . Subclasses can define their own implementation .
59
29
246,057
def _external_request ( self , method , url , * args , * * kwargs ) : self . last_url = url if url in self . responses . keys ( ) and method == 'get' : return self . responses [ url ] # return from cache if its there headers = kwargs . pop ( 'headers' , None ) custom = { 'User-Agent' : useragent } if headers : headers ...
Wrapper for requests . get with useragent automatically set . And also all requests are reponses are cached .
291
23
246,058
def get_block ( self , crypto , block_hash = '' , block_number = '' , latest = False ) : raise NotImplementedError ( self . name + " does not support getting getting block data. " "Or rather it has no defined 'get_block' method." )
Get block based on either block height block number or get the latest block . Only one of the previous arguments must be passed on .
62
26
246,059
def make_order ( self , crypto , fiat , amount , price , type = "limit" ) : raise NotImplementedError ( self . name + " does not support making orders. " "Or rather it has no defined 'make_order' method." )
This method buys or sells crypto on an exchange using fiat balance . Type can either be fill - or - kill post - only market or limit . To get what modes are supported consult make_order . supported_types if one is defined .
56
48
246,060
def _try_services ( self , method_name , * args , * * kwargs ) : crypto = ( ( args and args [ 0 ] ) or kwargs [ 'crypto' ] ) . lower ( ) address = kwargs . get ( 'address' , '' ) . lower ( ) fiat = kwargs . get ( 'fiat' , '' ) . lower ( ) if not self . services : raise CurrencyNotSupported ( "No services defined for %s...
Try each service until one returns a response . This function only catches the bare minimum of exceptions from the service class . We want exceptions to be raised so the service classes can be debugged and fixed quickly .
793
41
246,061
def uconcatenate ( arrs , axis = 0 ) : v = np . concatenate ( arrs , axis = axis ) v = _validate_numpy_wrapper_units ( v , arrs ) return v
Concatenate a sequence of arrays .
50
9
246,062
def ucross ( arr1 , arr2 , registry = None , axisa = - 1 , axisb = - 1 , axisc = - 1 , axis = None ) : v = np . cross ( arr1 , arr2 , axisa = axisa , axisb = axisb , axisc = axisc , axis = axis ) units = arr1 . units * arr2 . units arr = unyt_array ( v , units , registry = registry ) return arr
Applies the cross product to two YT arrays .
99
11
246,063
def uintersect1d ( arr1 , arr2 , assume_unique = False ) : v = np . intersect1d ( arr1 , arr2 , assume_unique = assume_unique ) v = _validate_numpy_wrapper_units ( v , [ arr1 , arr2 ] ) return v
Find the sorted unique elements of the two input arrays .
67
11
246,064
def uunion1d ( arr1 , arr2 ) : v = np . union1d ( arr1 , arr2 ) v = _validate_numpy_wrapper_units ( v , [ arr1 , arr2 ] ) return v
Find the union of two arrays .
52
7
246,065
def unorm ( data , ord = None , axis = None , keepdims = False ) : norm = np . linalg . norm ( data , ord = ord , axis = axis , keepdims = keepdims ) if norm . shape == ( ) : return unyt_quantity ( norm , data . units ) return unyt_array ( norm , data . units )
Matrix or vector norm that preserves units
82
7
246,066
def udot ( op1 , op2 ) : dot = np . dot ( op1 . d , op2 . d ) units = op1 . units * op2 . units if dot . shape == ( ) : return unyt_quantity ( dot , units ) return unyt_array ( dot , units )
Matrix or vector dot product that preserves units
67
8
246,067
def uhstack ( arrs ) : v = np . hstack ( arrs ) v = _validate_numpy_wrapper_units ( v , arrs ) return v
Stack arrays in sequence horizontally while preserving units
38
8
246,068
def ustack ( arrs , axis = 0 ) : v = np . stack ( arrs , axis = axis ) v = _validate_numpy_wrapper_units ( v , arrs ) return v
Join a sequence of arrays along a new axis while preserving units
45
12
246,069
def loadtxt ( fname , dtype = "float" , delimiter = "\t" , usecols = None , comments = "#" ) : f = open ( fname , "r" ) next_one = False units = [ ] num_cols = - 1 for line in f . readlines ( ) : words = line . strip ( ) . split ( ) if len ( words ) == 0 : continue if line [ 0 ] == comments : if next_one : units = word...
r Load unyt_arrays with unit information from a text file . Each row in the text file must have the same number of values .
341
29
246,070
def savetxt ( fname , arrays , fmt = "%.18e" , delimiter = "\t" , header = "" , footer = "" , comments = "#" ) : if not isinstance ( arrays , list ) : arrays = [ arrays ] units = [ ] for array in arrays : if hasattr ( array , "units" ) : units . append ( str ( array . units ) ) else : units . append ( "dimensionless" )...
r Write unyt_arrays with unit information to a text file .
182
15
246,071
def convert_to_units ( self , units , equivalence = None , * * kwargs ) : units = _sanitize_units_convert ( units , self . units . registry ) if equivalence is None : conv_data = _check_em_conversion ( self . units , units , registry = self . units . registry ) if any ( conv_data ) : new_units , ( conv_factor , offset ...
Convert the array to the given units in - place .
448
12
246,072
def convert_to_base ( self , unit_system = None , equivalence = None , * * kwargs ) : self . convert_to_units ( self . units . get_base_equivalent ( unit_system ) , equivalence = equivalence , * * kwargs )
Convert the array in - place to the equivalent base units in the specified unit system .
63
18
246,073
def convert_to_cgs ( self , equivalence = None , * * kwargs ) : self . convert_to_units ( self . units . get_cgs_equivalent ( ) , equivalence = equivalence , * * kwargs )
Convert the array and in - place to the equivalent cgs units .
56
15
246,074
def convert_to_mks ( self , equivalence = None , * * kwargs ) : self . convert_to_units ( self . units . get_mks_equivalent ( ) , equivalence , * * kwargs )
Convert the array and units to the equivalent mks units .
53
13
246,075
def to_value ( self , units = None , equivalence = None , * * kwargs ) : if units is None : v = self . value else : v = self . in_units ( units , equivalence = equivalence , * * kwargs ) . value if isinstance ( self , unyt_quantity ) : return float ( v ) else : return v
Creates a copy of this array with the data in the supplied units and returns it without units . Output is therefore a bare NumPy array .
81
29
246,076
def in_base ( self , unit_system = None ) : us = _sanitize_unit_system ( unit_system , self ) try : conv_data = _check_em_conversion ( self . units , unit_system = us , registry = self . units . registry ) except MKSCGSConversionError : raise UnitsNotReducible ( self . units , us ) if any ( conv_data ) : to_units , ( c...
Creates a copy of this array with the data in the specified unit system and returns it in that system s base units .
230
25
246,077
def argsort ( self , axis = - 1 , kind = "quicksort" , order = None ) : return self . view ( np . ndarray ) . argsort ( axis , kind , order )
Returns the indices that would sort the array .
45
9
246,078
def from_astropy ( cls , arr , unit_registry = None ) : # Converting from AstroPy Quantity try : u = arr . unit _arr = arr except AttributeError : u = arr _arr = 1.0 * u ap_units = [ ] for base , exponent in zip ( u . bases , u . powers ) : unit_str = base . to_string ( ) # we have to do this because AstroPy is silly a...
Convert an AstroPy Quantity to a unyt_array or unyt_quantity .
231
19
246,079
def to_astropy ( self , * * kwargs ) : return self . value * _astropy . units . Unit ( str ( self . units ) , * * kwargs )
Creates a new AstroPy quantity with the same unit information .
41
13
246,080
def from_pint ( cls , arr , unit_registry = None ) : p_units = [ ] for base , exponent in arr . _units . items ( ) : bs = convert_pint_units ( base ) p_units . append ( "%s**(%s)" % ( bs , Rational ( exponent ) ) ) p_units = "*" . join ( p_units ) if isinstance ( arr . magnitude , np . ndarray ) : return unyt_array ( a...
Convert a Pint Quantity to a unyt_array or unyt_quantity .
149
19
246,081
def to_pint ( self , unit_registry = None ) : if unit_registry is None : unit_registry = _pint . UnitRegistry ( ) powers_dict = self . units . expr . as_powers_dict ( ) units = [ ] for unit , pow in powers_dict . items ( ) : # we have to do this because Pint doesn't recognize # "yr" as "year" if str ( unit ) . endswith...
Convert a unyt_array or unyt_quantity to a Pint Quantity .
183
19
246,082
def write_hdf5 ( self , filename , dataset_name = None , info = None , group_name = None ) : from unyt . _on_demand_imports import _h5py as h5py import pickle if info is None : info = { } info [ "units" ] = str ( self . units ) info [ "unit_registry" ] = np . void ( pickle . dumps ( self . units . registry . lut ) ) if...
r Writes a unyt_array to hdf5 file .
319
14
246,083
def from_hdf5 ( cls , filename , dataset_name = None , group_name = None ) : from unyt . _on_demand_imports import _h5py as h5py import pickle if dataset_name is None : dataset_name = "array_data" f = h5py . File ( filename ) if group_name is not None : g = f [ group_name ] else : g = f dataset = g [ dataset_name ] dat...
r Attempts read in and convert a dataset in an hdf5 file into a unyt_array .
193
22
246,084
def copy ( self , order = "C" ) : return type ( self ) ( np . copy ( np . asarray ( self ) ) , self . units )
Return a copy of the array .
35
7
246,085
def dot ( self , b , out = None ) : res_units = self . units * getattr ( b , "units" , NULL_UNIT ) ret = self . view ( np . ndarray ) . dot ( np . asarray ( b ) , out = out ) * res_units if out is not None : out . units = res_units return ret
dot product of two arrays .
80
6
246,086
def import_units ( module , namespace ) : for key , value in module . __dict__ . items ( ) : if isinstance ( value , ( unyt_quantity , Unit ) ) : namespace [ key ] = value
Import Unit objects from a module into a namespace
48
9
246,087
def _lookup_unit_symbol ( symbol_str , unit_symbol_lut ) : if symbol_str in unit_symbol_lut : # lookup successful, return the tuple directly return unit_symbol_lut [ symbol_str ] # could still be a known symbol with a prefix prefix , symbol_wo_prefix = _split_prefix ( symbol_str , unit_symbol_lut ) if prefix : # lookup...
Searches for the unit data tuple corresponding to the given symbol .
403
14
246,088
def unit_system_id ( self ) : if self . _unit_system_id is None : hash_data = bytearray ( ) for k , v in sorted ( self . lut . items ( ) ) : hash_data . extend ( k . encode ( "utf8" ) ) hash_data . extend ( repr ( v ) . encode ( "utf8" ) ) m = md5 ( ) m . update ( hash_data ) self . _unit_system_id = str ( m . hexdiges...
This is a unique identifier for the unit registry created from a FNV hash . It is needed to register a dataset s code unit system in the unit system registry .
126
33
246,089
def add ( self , symbol , base_value , dimensions , tex_repr = None , offset = None , prefixable = False , ) : from unyt . unit_object import _validate_dimensions self . _unit_system_id = None # Validate if not isinstance ( base_value , float ) : raise UnitParseError ( "base_value (%s) must be a float, got a %s." % ( b...
Add a symbol to this registry .
246
7
246,090
def remove ( self , symbol ) : self . _unit_system_id = None if symbol not in self . lut : raise SymbolNotFoundError ( "Tried to remove the symbol '%s', but it does not exist " "in this registry." % symbol ) del self . lut [ symbol ]
Remove the entry for the unit matching symbol .
66
9
246,091
def modify ( self , symbol , base_value ) : self . _unit_system_id = None if symbol not in self . lut : raise SymbolNotFoundError ( "Tried to modify the symbol '%s', but it does not exist " "in this registry." % symbol ) if hasattr ( base_value , "in_base" ) : new_dimensions = base_value . units . dimensions base_value...
Change the base value of a unit symbol . Useful for adjusting code units after parsing parameters .
165
18
246,092
def to_json ( self ) : sanitized_lut = { } for k , v in self . lut . items ( ) : san_v = list ( v ) repr_dims = str ( v [ 1 ] ) san_v [ 1 ] = repr_dims sanitized_lut [ k ] = tuple ( san_v ) return json . dumps ( sanitized_lut )
Returns a json - serialized version of the unit registry
87
11
246,093
def from_json ( cls , json_text ) : data = json . loads ( json_text ) lut = { } for k , v in data . items ( ) : unsan_v = list ( v ) unsan_v [ 1 ] = sympify ( v [ 1 ] , locals = vars ( unyt_dims ) ) lut [ k ] = tuple ( unsan_v ) return cls ( lut = lut , add_default_symbols = False )
Returns a UnitRegistry object from a json - serialized unit registry
109
14
246,094
def _em_conversion ( orig_units , conv_data , to_units = None , unit_system = None ) : conv_unit , canonical_unit , scale = conv_data if conv_unit is None : conv_unit = canonical_unit new_expr = scale * canonical_unit . expr if unit_system is not None : # we don't know the to_units, so we get it directly from the # con...
Convert between E&M & MKS base units .
156
12
246,095
def _check_em_conversion ( unit , to_unit = None , unit_system = None , registry = None ) : em_map = ( ) if unit == to_unit or unit . dimensions not in em_conversion_dims : return em_map if unit . is_atomic : prefix , unit_wo_prefix = _split_prefix ( str ( unit ) , unit . registry . lut ) else : prefix , unit_wo_prefix...
Check to see if the units contain E&M units
449
11
246,096
def _get_conversion_factor ( old_units , new_units , dtype ) : if old_units . dimensions != new_units . dimensions : raise UnitConversionError ( old_units , old_units . dimensions , new_units , new_units . dimensions ) ratio = old_units . base_value / new_units . base_value if old_units . base_offset == 0 and new_units...
Get the conversion factor between two units of equivalent dimensions . This is the number you multiply data by to convert from values in old_units to values in new_units .
153
34
246,097
def _get_unit_data_from_expr ( unit_expr , unit_symbol_lut ) : # Now for the sympy possibilities if isinstance ( unit_expr , Number ) : if unit_expr is sympy_one : return ( 1.0 , sympy_one ) return ( float ( unit_expr ) , sympy_one ) if isinstance ( unit_expr , Symbol ) : return _lookup_unit_symbol ( unit_expr . name ,...
Grabs the total base_value and dimensions from a valid unit expression .
355
15
246,098
def define_unit ( symbol , value , tex_repr = None , offset = None , prefixable = False , registry = None ) : from unyt . array import unyt_quantity , _iterable import unyt if registry is None : registry = default_unit_registry if symbol in registry : raise RuntimeError ( "Unit symbol '%s' already exists in the provide...
Define a new unit and add it to the specified unit registry .
258
14
246,099
def latex_repr ( self ) : if self . _latex_repr is not None : return self . _latex_repr if self . expr . is_Atom : expr = self . expr else : expr = self . expr . copy ( ) self . _latex_repr = _get_latex_representation ( expr , self . registry ) return self . _latex_repr
A LaTeX representation for the unit
90
7