idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
38,400
def write_translated ( self , name , value , event = None ) : data = { 'name' : name } if value is not None : data [ 'value' ] = self . _massage_write_value ( value ) if event is not None : data [ 'event' ] = self . _massage_write_value ( event ) message = self . streamer . serialize_for_stream ( data ) bytes_written =...
Send a translated write request to the VI .
38,401
def write_raw ( self , message_id , data , bus = None , frame_format = None ) : if not isinstance ( message_id , numbers . Number ) : try : message_id = int ( message_id , 0 ) except ValueError : raise ValueError ( "ID must be numerical" ) data = { 'id' : message_id , 'data' : data } if bus is not None : data [ 'bus' ]...
Send a raw write request to the VI .
38,402
def _massage_write_value ( cls , value ) : if not isinstance ( value , numbers . Number ) : if value == "true" : value = True elif value == "false" : value = False elif value [ 0 ] == '"' and value [ - 1 ] == '"' : value = value [ 1 : - 1 ] else : try : value = float ( value ) except ValueError : pass return value
Convert string values from command - line arguments into first - order Python boolean and float objects if applicable .
38,403
def _validate ( cls , message ) : valid = False if ( ( 'name' in message and 'value' in message ) or ( 'id' in message and 'data' in message ) ) : valid = True return valid
Confirm the validitiy of a given dict as an OpenXC message .
38,404
def value ( self , new_value ) : if self . unit != units . Undefined and new_value . unit != self . unit : raise AttributeError ( "%s must be in %s" % ( self . __class__ , self . unit ) ) self . _value = new_value
Set the value of this measurement .
38,405
def from_dict ( cls , data ) : args = [ ] if 'id' in data and 'data' in data : measurement_class = CanMessage args . append ( "Bus %s: 0x%x" % ( data . get ( 'bus' , '?' ) , data [ 'id' ] ) ) args . append ( data [ 'data' ] ) else : measurement_class = cls . _class_from_name ( data [ 'name' ] ) if measurement_class == ...
Create a new Measurement subclass instance using the given dict .
38,406
def name_from_class ( cls , measurement_class ) : if not getattr ( cls , '_measurements_initialized' , False ) : cls . _measurement_map = dict ( ( m . name , m ) for m in all_measurements ( ) ) cls . _measurements_initialized = True try : name = getattr ( measurement_class , 'name' ) except AttributeError : raise Unrec...
For a given measurement class return its generic name .
38,407
def _store_timestamp ( self , timestamp ) : if getattr ( self , 'first_timestamp' , None ) is None : self . first_timestamp = timestamp LOG . debug ( "Storing %d as the first timestamp of the trace file %s" , self . first_timestamp , self . filename )
If not already saved cache the first timestamp in the active trace file on the instance .
38,408
def read ( self ) : line = self . trace_file . readline ( ) if line == '' : if self . loop : self . _reopen_file ( ) else : self . trace_file . close ( ) self . trace_file = None raise DataSourceError ( ) message = JsonFormatter . deserialize ( line ) timestamp = message . get ( 'timestamp' , None ) if self . realtime ...
Read a line of data from the input source at a time .
38,409
def _open_file ( filename ) : if filename is None : raise DataSourceError ( "Trace filename is not defined" ) try : trace_file = open ( filename , "r" ) except IOError as e : raise DataSourceError ( "Unable to open trace file %s" % filename , e ) else : LOG . debug ( "Opened trace file %s" , filename ) return trace_fil...
Attempt to open the the file at filename for reading .
38,410
def _wait ( starting_time , first_timestamp , timestamp ) : target_time = starting_time + ( timestamp - first_timestamp ) time . sleep ( max ( target_time - time . time ( ) , 0 ) )
Given that the first timestamp in the trace file is first_timestamp and we started playing back the file at starting_time block until the current timestamp should occur .
38,411
def from_xml_node ( cls , node ) : return cls ( name = node . find ( "Name" ) . text , bit_position = int ( node . find ( "Bitposition" ) . text ) , bit_size = int ( node . find ( "Bitsize" ) . text ) , factor = float ( node . find ( "Factor" ) . text ) , offset = float ( node . find ( "Offset" ) . text ) , min_value =...
Construct a Signal instance from an XML node exported from a Vector CANoe . dbc file .
38,412
def run ( self ) : message_buffer = b"" while self . running : try : message_buffer += self . source . read_logs ( ) except DataSourceError as e : if self . running : LOG . warn ( "Can't read logs from data source -- stopping: %s" , e ) break except NotImplementedError as e : LOG . info ( "%s doesn't support logging" %...
Continuously read data from the source and attempt to parse a valid message from the buffer of bytes . When a message is parsed passes it off to the callback if one is set .
38,413
def compute ( self , t , yerr = 1.123e-12 , check_sorted = True , A = None , U = None , V = None ) : t = np . atleast_1d ( t ) if check_sorted and np . any ( np . diff ( t ) < 0.0 ) : raise ValueError ( "the input coordinates must be sorted" ) if check_sorted and len ( t . shape ) > 1 : raise ValueError ( "dimension mi...
Compute the extended form of the covariance matrix and factorize
38,414
def log_likelihood ( self , y , _const = math . log ( 2.0 * math . pi ) , quiet = False ) : y = self . _process_input ( y ) resid = y - self . mean . get_value ( self . _t ) try : self . _recompute ( ) except solver . LinAlgError : if quiet : return - np . inf raise if len ( y . shape ) > 1 : raise ValueError ( "dimens...
Compute the marginalized likelihood of the GP model
38,415
def grad_log_likelihood ( self , y , quiet = False ) : if not solver . has_autodiff ( ) : raise RuntimeError ( "celerite must be compiled with autodiff " "support to use the gradient methods" ) if not self . kernel . vector_size : return self . log_likelihood ( y , quiet = quiet ) , np . empty ( 0 ) y = self . _process...
Compute the gradient of the marginalized likelihood
38,416
def apply_inverse ( self , y ) : self . _recompute ( ) return self . solver . solve ( self . _process_input ( y ) )
Apply the inverse of the covariance matrix to a vector or matrix
38,417
def dot ( self , y , t = None , A = None , U = None , V = None , kernel = None , check_sorted = True ) : if kernel is None : kernel = self . kernel if t is not None : t = np . atleast_1d ( t ) if check_sorted and np . any ( np . diff ( t ) < 0.0 ) : raise ValueError ( "the input coordinates must be sorted" ) if check_s...
Dot the covariance matrix into a vector or matrix
38,418
def predict ( self , y , t = None , return_cov = True , return_var = False ) : y = self . _process_input ( y ) if len ( y . shape ) > 1 : raise ValueError ( "dimension mismatch" ) if t is None : xs = self . _t else : xs = np . ascontiguousarray ( t , dtype = float ) if len ( xs . shape ) > 1 : raise ValueError ( "dimen...
Compute the conditional predictive distribution of the model
38,419
def get_matrix ( self , x1 = None , x2 = None , include_diagonal = None , include_general = None ) : if x1 is None and x2 is None : if self . _t is None or not self . computed : raise RuntimeError ( "you must call 'compute' first" ) K = self . kernel . get_value ( self . _t [ : , None ] - self . _t [ None , : ] ) if in...
Get the covariance matrix at given independent coordinates
38,420
def sample ( self , size = None ) : self . _recompute ( ) if size is None : n = np . random . randn ( len ( self . _t ) ) else : n = np . random . randn ( len ( self . _t ) , size ) n = self . solver . dot_L ( n ) if size is None : return self . mean . get_value ( self . _t ) + n [ : , 0 ] return self . mean . get_valu...
Sample from the prior distribution over datasets
38,421
def get_value ( self , tau ) : tau = np . asarray ( tau ) ( alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag ) = self . coefficients k = get_kernel_value ( alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag , t...
Compute the value of the term for an array of lags
38,422
def get_psd ( self , omega ) : w = np . asarray ( omega ) ( alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag ) = self . coefficients p = get_psd_value ( alpha_real , beta_real , alpha_complex_real , alpha_complex_imag , beta_complex_real , beta_complex_imag , w . ...
Compute the PSD of the term for an array of angular frequencies
38,423
def coefficients ( self ) : vector = self . get_parameter_vector ( include_frozen = True ) pars = self . get_all_coefficients ( vector ) if len ( pars ) != 6 : raise ValueError ( "there must be 6 coefficient blocks" ) if any ( len ( p . shape ) != 1 for p in pars ) : raise ValueError ( "coefficient blocks must be 1D" )...
All of the coefficient arrays
38,424
def _determine_current_dimension_size ( self , dim_name , max_size ) : if self . dimensions [ dim_name ] is not None : return max_size def _find_dim ( h5group , dim ) : if dim not in h5group : return _find_dim ( h5group . parent , dim ) return h5group [ dim ] dim_variable = _find_dim ( self . _h5group , dim_name ) if "...
Helper method to determine the current size of a dimension .
38,425
def _create_dim_scales ( self ) : dim_order = self . _dim_order . maps [ 0 ] for dim in sorted ( dim_order , key = lambda d : dim_order [ d ] ) : if dim not in self . _h5group : size = self . _current_dim_sizes [ dim ] kwargs = { } if self . _dim_sizes [ dim ] is None : kwargs [ "maxshape" ] = ( None , ) self . _h5grou...
Create all necessary HDF5 dimension scale .
38,426
def _attach_dim_scales ( self ) : for name , var in self . variables . items ( ) : if name not in self . dimensions : for n , dim in enumerate ( var . dimensions ) : var . _h5ds . dims [ n ] . attach_scale ( self . _all_h5groups [ dim ] ) for subgroup in self . groups . values ( ) : subgroup . _attach_dim_scales ( )
Attach dimension scales to all variables .
38,427
def _detach_dim_scale ( self , name ) : for var in self . variables . values ( ) : for n , dim in enumerate ( var . dimensions ) : if dim == name : var . _h5ds . dims [ n ] . detach_scale ( self . _all_h5groups [ dim ] ) for subgroup in self . groups . values ( ) : if dim not in subgroup . _h5group : subgroup . _detach...
Detach the dimension scale corresponding to a dimension name .
38,428
def resize_dimension ( self , dimension , size ) : if self . dimensions [ dimension ] is not None : raise ValueError ( "Dimension '%s' is not unlimited and thus " "cannot be resized." % dimension ) self . _current_dim_sizes [ dimension ] = size for var in self . variables . values ( ) : new_shape = list ( var . shape )...
Resize a dimension to a certain size .
38,429
def alignVec_quat ( vec ) : alpha = np . arctan2 ( vec [ 1 ] , vec [ 0 ] ) beta = np . arccos ( vec [ 2 ] ) gamma = - alpha * vec [ 2 ] cb = np . cos ( 0.5 * beta ) sb = np . sin ( 0.5 * beta ) return np . array ( [ cb * np . cos ( 0.5 * ( alpha + gamma ) ) , sb * np . sin ( 0.5 * ( gamma - alpha ) ) , sb * np . cos ( ...
Returns a unit quaternion that will align vec with the z - axis
38,430
def rotate_in_plane ( chi , phase ) : v = chi . T sp = np . sin ( phase ) cp = np . cos ( phase ) res = 1. * v res [ 0 ] = v [ 0 ] * cp + v [ 1 ] * sp res [ 1 ] = v [ 1 ] * cp - v [ 0 ] * sp return res . T
For transforming spins between the coprecessing and coorbital frames
38,431
def transform_error_coorb_to_inertial ( vec_coorb , vec_err_coorb , orbPhase , quat_copr ) : np . random . seed ( 0 ) dist_coorb = np . array ( [ np . random . normal ( m , s , 1000 ) for m , s in zip ( vec_coorb , vec_err_coorb ) ] ) . T dist_copr = rotate_in_plane ( dist_coorb , - orbPhase ) dist_inertial = transform...
Transform error in a vector from the coorbital frame to the inertial frame . Generates distributions in the coorbital frame transforms them to inertial frame and returns 1 - simga widths in the inertial frame .
38,432
def _extra_regression_kwargs ( self ) : omega_switch_test = 0.019 extra_args = [ ] extra_args . append ( { 'omega0' : 5e-3 , 'PN_approximant' : 'SpinTaylorT4' , 'PN_dt' : 0.1 , 'PN_spin_order' : 7 , 'PN_phase_order' : 7 , 'omega_switch' : omega_switch_test , } ) extra_args . append ( { 'omega0' : 6e-3 , 'PN_approximant...
List of additional kwargs to use in regression tests .
38,433
def _evolve_spins ( self , q , chiA0 , chiB0 , omega0 , PN_approximant , PN_dt , PN_spin0 , PN_phase0 , omega0_nrsur ) : if omega0 < omega0_nrsur : chiA0_nrsur_copr , chiB0_nrsur_copr , quat0_nrsur_copr , phi0_nrsur , omega0_nrsur = evolve_pn_spins ( q , chiA0 , chiB0 , omega0 , omega0_nrsur , approximant = PN_approxim...
Evolves spins of the component BHs from an initial orbital frequency = omega0 until t = - 100 M from the peak of the waveform . If omega0 < omega0_nrsur use PN to evolve the spins until orbital frequency = omega0 . Then evolves further with the NRSur7dq2 waveform model until t = - 100M from the peak .
38,434
def _eval_wrapper ( self , fit_key , q , chiA , chiB , ** kwargs ) : chiA = np . array ( chiA ) chiB = np . array ( chiB ) allow_extrap = kwargs . pop ( 'allow_extrap' , False ) self . _check_param_limits ( q , chiA , chiB , allow_extrap ) omega0 = kwargs . pop ( 'omega0' , None ) PN_approximant = kwargs . pop ( 'PN_ap...
Evaluates the surfinBH7dq2 model .
38,435
def LoadFits ( name ) : if name not in fits_collection . keys ( ) : raise Exception ( 'Invalid fit name : %s' % name ) else : testPath = DataPath ( ) + '/' + fits_collection [ name ] . data_url . split ( '/' ) [ - 1 ] if ( not os . path . isfile ( testPath ) ) : DownloadData ( name ) fit = fits_collection [ name ] . fi...
Loads data for a fit . If data is not available downloads it before loading .
38,436
def _eval_wrapper ( self , fit_key , q , chiA , chiB , ** kwargs ) : chiA = np . array ( chiA ) chiB = np . array ( chiB ) allow_extrap = kwargs . pop ( 'allow_extrap' , False ) self . _check_param_limits ( q , chiA , chiB , allow_extrap ) self . _check_unused_kwargs ( kwargs ) x = [ q , chiA [ 2 ] , chiB [ 2 ] ] if fi...
Evaluates the surfinBH3dq8 model .
38,437
def evolve_pn_spins ( q , chiA0 , chiB0 , omega0 , omegaTimesM_final , approximant = 'SpinTaylorT4' , dt = 0.1 , spinO = 7 , phaseO = 7 ) : omega , phi , chiA , chiB , lNhat , e1 = lal_spin_evloution_wrapper ( approximant , q , omega0 , chiA0 , chiB0 , dt , spinO , phaseO ) end_idx = np . argmin ( np . abs ( omega - om...
Evolves PN spins from a starting orbital frequency and spins to a final frequency .
38,438
def qual ( obj ) : return u'{}.{}' . format ( obj . __class__ . __module__ , obj . __class__ . __name__ )
Return fully qualified name of a class .
38,439
def count ( self , txn , prefix = None ) : key_from = struct . pack ( '>H' , self . _slot ) if prefix : key_from += self . _serialize_key ( prefix ) kfl = len ( key_from ) cnt = 0 cursor = txn . _txn . cursor ( ) has_more = cursor . set_range ( key_from ) while has_more : _key = cursor . key ( ) _prefix = _key [ : kfl ...
Count number of records in the persistent map . When no prefix is given the total number of records is returned . When a prefix is given only the number of records with keys that have this prefix are counted .
38,440
def count_range ( self , txn , from_key , to_key ) : key_from = struct . pack ( '>H' , self . _slot ) + self . _serialize_key ( from_key ) to_key = struct . pack ( '>H' , self . _slot ) + self . _serialize_key ( to_key ) cnt = 0 cursor = txn . _txn . cursor ( ) has_more = cursor . set_range ( key_from ) while has_more ...
Counter number of records in the perstistent map with keys within the given range .
38,441
def _read_dict ( self , f ) : d = { } for k , item in f . items ( ) : if type ( item ) == h5py . _hl . dataset . Dataset : v = item . value if type ( v ) == np . string_ : v = str ( v ) if type ( v ) == str and v == "NONE" : d [ k ] = None elif type ( v ) == str and v == "EMPTYARR" : d [ k ] = np . array ( [ ] ) elif i...
Converts h5 groups to dictionaries
38,442
def _load_scalar_fit ( self , fit_key = None , h5file = None , fit_data = None ) : if ( fit_key is None ) ^ ( h5file is None ) : raise ValueError ( "Either specify both fit_key and h5file, or" " neither" ) if not ( ( fit_key is None ) ^ ( fit_data is None ) ) : raise ValueError ( "Specify exactly one of fit_key and fit...
Loads a single fit
38,443
def _load_vector_fit ( self , fit_key , h5file ) : vector_fit = [ ] for i in range ( len ( h5file [ fit_key ] . keys ( ) ) ) : fit_data = self . _read_dict ( h5file [ fit_key ] [ 'comp_%d' % i ] ) vector_fit . append ( self . _load_scalar_fit ( fit_data = fit_data ) ) return vector_fit
Loads a vector of fits
38,444
def _check_unused_kwargs ( self , kwargs ) : if len ( kwargs . keys ( ) ) != 0 : unused = "" for k in kwargs . keys ( ) : unused += "'%s', " % k if unused [ - 2 : ] == ", " : unused = unused [ : - 2 ] raise Exception ( 'Unused keys in kwargs: %s' % unused )
Call this at the end of call module to check if all the kwargs have been used . Assumes kwargs were extracted using pop .
38,445
def _check_param_limits ( self , q , chiA , chiB , allow_extrap ) : if q < 1 : raise ValueError ( 'Mass ratio should be >= 1.' ) chiAmag = np . sqrt ( np . sum ( chiA ** 2 ) ) chiBmag = np . sqrt ( np . sum ( chiB ** 2 ) ) if chiAmag > 1 + 1e-14 : raise ValueError ( 'Spin magnitude of BhA > 1.' ) if chiBmag > 1 + 1e-14...
Checks that params are within allowed range of paramters . Raises a warning if outside self . soft_param_lims limits and raises an error if outside self . hard_param_lims . If allow_extrap = True skips these checks .
38,446
def slot ( self , slot_index , marshal = None , unmarshal = None , build = None , cast = None , compress = False ) : def decorate ( o ) : assert isinstance ( o , PersistentMap ) name = o . __class__ . __name__ assert slot_index not in self . _index_to_slot assert name not in self . _name_to_slot o . _zlmdb_slot = slot_...
Decorator for use on classes derived from zlmdb . PersistentMap . The decorator define slots in a LMDB database schema based on persistent maps and slot configuration .
38,447
def DataPath ( ) : return os . path . abspath ( '%s/data' % ( os . path . dirname ( os . path . realpath ( __file__ ) ) ) )
Return the default path for fit data h5 files
38,448
def init_services ( service_definitions , service_context , state_db , client_authn_factory = None ) : service = { } for service_name , service_configuration in service_definitions . items ( ) : try : kwargs = service_configuration [ 'kwargs' ] except KeyError : kwargs = { } kwargs . update ( { 'service_context' : serv...
Initiates a set of services
38,449
def gather_request_args ( self , ** kwargs ) : ar_args = kwargs . copy ( ) for prop in self . msg_type . c_param . keys ( ) : if prop in ar_args : continue else : try : ar_args [ prop ] = getattr ( self . service_context , prop ) except AttributeError : try : ar_args [ prop ] = self . conf [ 'request_args' ] [ prop ] e...
Go through the attributes that the message class can contain and add values if they are missing but exists in the client info or when there are default values .
38,450
def method_args ( self , context , ** kwargs ) : try : _args = self . conf [ context ] . copy ( ) except KeyError : _args = kwargs else : _args . update ( kwargs ) return _args
Collect the set of arguments that should be used by a set of methods
38,451
def do_pre_construct ( self , request_args , ** kwargs ) : _args = self . method_args ( 'pre_construct' , ** kwargs ) post_args = { } for meth in self . pre_construct : request_args , _post_args = meth ( request_args , service = self , ** _args ) post_args . update ( _post_args ) return request_args , post_args
Will run the pre_construct methods one by one in the order given .
38,452
def do_post_construct ( self , request_args , ** kwargs ) : _args = self . method_args ( 'post_construct' , ** kwargs ) for meth in self . post_construct : request_args = meth ( request_args , service = self , ** _args ) return request_args
Will run the post_construct methods one at the time in order .
38,453
def construct ( self , request_args = None , ** kwargs ) : if request_args is None : request_args = { } request_args , post_args = self . do_pre_construct ( request_args , ** kwargs ) if 'state' in self . msg_type . c_param and 'state' in kwargs : if 'state' not in request_args : request_args [ 'state' ] = kwargs [ 'st...
Instantiate the request as a message class instance with attribute values gathered in a pre_construct method or in the gather_request_args method .
38,454
def init_authentication_method ( self , request , authn_method , http_args = None , ** kwargs ) : if http_args is None : http_args = { } if authn_method : logger . debug ( 'Client authn method: {}' . format ( authn_method ) ) return self . client_authn_factory ( authn_method ) . construct ( request , self , http_args =...
Will run the proper client authentication method . Each such method will place the necessary information in the necessary place . A method may modify the request .
38,455
def construct_request ( self , request_args = None , ** kwargs ) : if request_args is None : request_args = { } return self . construct ( request_args , ** kwargs )
The method where everything is setup for sending the request . The request information is gathered and the where and how of sending the request is decided .
38,456
def get_endpoint ( self ) : if self . endpoint : return self . endpoint else : return self . service_context . provider_info [ self . endpoint_name ]
Find the service endpoint
38,457
def get_authn_header ( self , request , authn_method , ** kwargs ) : headers = { } if authn_method : h_arg = self . init_authentication_method ( request , authn_method , ** kwargs ) try : headers = h_arg [ 'headers' ] except KeyError : pass return headers
Construct an authorization specification to be sent in the HTTP header .
38,458
def get_request_parameters ( self , request_body_type = "" , method = "" , authn_method = '' , request_args = None , http_args = None , ** kwargs ) : if not method : method = self . http_method if not authn_method : authn_method = self . get_authn_method ( ) if not request_body_type : request_body_type = self . request...
Builds the request message and constructs the HTTP headers .
38,459
def get_urlinfo ( info ) : if '?' in info or '#' in info : parts = urlparse ( info ) scheme , netloc , path , params , query , fragment = parts [ : 6 ] if query : info = query else : info = fragment return info
Pick out the fragment or query part from a URL .
38,460
def get_conf_attr ( self , attr , default = None ) : if attr in self . conf : return self . conf [ attr ] else : return default
Get the value of a attribute in the configuration
38,461
def post_parse_response ( self , response , ** kwargs ) : if "scope" not in response : try : _key = kwargs [ 'state' ] except KeyError : pass else : if _key : item = self . get_item ( oauth2 . AuthorizationRequest , 'auth_request' , _key ) try : response [ "scope" ] = item [ "scope" ] except KeyError : pass return resp...
Add scope claim to response from the request if not present in the response
38,462
def get_id_token_hint ( self , request_args = None , ** kwargs ) : request_args = self . multiple_extend_request_args ( request_args , kwargs [ 'state' ] , [ 'id_token' ] , [ 'auth_response' , 'token_response' , 'refresh_token_response' ] , orig = True ) try : request_args [ 'id_token_hint' ] = request_args [ 'id_token...
Add id_token_hint to request
38,463
def get_state ( self , key ) : _data = self . state_db . get ( key ) if not _data : raise KeyError ( key ) else : return State ( ) . from_json ( _data )
Get the state connected to a given key .
38,464
def store_item ( self , item , item_type , key ) : try : _state = self . get_state ( key ) except KeyError : _state = State ( ) try : _state [ item_type ] = item . to_json ( ) except AttributeError : _state [ item_type ] = item self . state_db . set ( key , _state . to_json ( ) )
Store a service response .
38,465
def get_iss ( self , key ) : _state = self . get_state ( key ) if not _state : raise KeyError ( key ) return _state [ 'iss' ]
Get the Issuer ID
38,466
def extend_request_args ( self , args , item_cls , item_type , key , parameters , orig = False ) : try : item = self . get_item ( item_cls , item_type , key ) except KeyError : pass else : for parameter in parameters : if orig : try : args [ parameter ] = item [ parameter ] except KeyError : pass else : try : args [ pa...
Add a set of parameters and their value to a set of request arguments .
38,467
def get_state_by_X ( self , x , xtyp ) : _state = self . state_db . get ( KEY_PATTERN [ xtyp ] . format ( x ) ) if _state : return _state else : raise KeyError ( 'Unknown {}: "{}"' . format ( xtyp , x ) )
Find the state value by providing the x value . Will raise an exception if the x value is absent from the state data base .
38,468
def import_keys ( self , keyspec ) : for where , spec in keyspec . items ( ) : if where == 'file' : for typ , files in spec . items ( ) : if typ == 'rsa' : for fil in files : _key = RSAKey ( key = import_private_rsa_key_from_file ( fil ) , use = 'sig' ) _kb = KeyBundle ( ) _kb . append ( _key ) self . keyjar . add_kb (...
The client needs it s own set of keys . It can either dynamically create them or load them from local storage . This method can also fetch other entities keys provided the URL points to a JWKS .
38,469
def assertion_jwt ( client_id , keys , audience , algorithm , lifetime = 600 ) : _now = utc_time_sans_frac ( ) at = AuthnToken ( iss = client_id , sub = client_id , aud = audience , jti = rndstr ( 32 ) , exp = _now + lifetime , iat = _now ) logger . debug ( 'AuthnToken: {}' . format ( at . to_dict ( ) ) ) return at . t...
Create a signed Json Web Token containing some information .
38,470
def valid_service_context ( service_context , when = 0 ) : eta = getattr ( service_context , 'client_secret_expires_at' , 0 ) now = when or utc_time_sans_frac ( ) if eta != 0 and eta < now : return False return True
Check if the client_secret has expired
38,471
def construct ( self , request , service = None , http_args = None , ** kwargs ) : if http_args is None : http_args = { } if "headers" not in http_args : http_args [ "headers" ] = { } try : passwd = kwargs [ "password" ] except KeyError : try : passwd = request [ "client_secret" ] except KeyError : passwd = service . s...
Construct a dictionary to be added to the HTTP request headers
38,472
def construct ( self , request , service = None , http_args = None , ** kwargs ) : _acc_token = '' for _token_type in [ 'access_token' , 'refresh_token' ] : _acc_token = find_token ( request , _token_type , service , ** kwargs ) if _acc_token : break if not _acc_token : raise KeyError ( 'No access or refresh token avai...
Will add a token to the request if not present
38,473
def choose_algorithm ( self , context , ** kwargs ) : try : algorithm = kwargs [ "algorithm" ] except KeyError : algorithm = DEF_SIGN_ALG [ context ] if not algorithm : raise AuthnFailure ( "Missing algorithm specification" ) return algorithm
Pick signing algorithm
38,474
def get_signing_key ( self , algorithm , service_context ) : return service_context . keyjar . get_signing_key ( alg2keytype ( algorithm ) , alg = algorithm )
Pick signing key based on signing algorithm to be used
38,475
def get_key_by_kid ( self , kid , algorithm , service_context ) : _key = service_context . keyjar . get_key_by_kid ( kid ) if _key : ktype = alg2keytype ( algorithm ) if _key . kty != ktype : raise NoMatchingKey ( "Wrong key type" ) else : return _key else : raise NoMatchingKey ( "No key with kid:%s" % kid )
Pick a key that matches a given key ID and signing algorithm .
38,476
def construct ( self , request , service = None , http_args = None , ** kwargs ) : if 'client_assertion' in kwargs : request [ "client_assertion" ] = kwargs [ 'client_assertion' ] if 'client_assertion_type' in kwargs : request [ 'client_assertion_type' ] = kwargs [ 'client_assertion_type' ] else : request [ "client_ass...
Constructs a client assertion and signs it with a key . The request is modified as a side effect .
38,477
def get_endpoint ( self ) : try : _iss = self . service_context . issuer except AttributeError : _iss = self . endpoint if _iss . endswith ( '/' ) : return OIDCONF_PATTERN . format ( _iss [ : - 1 ] ) else : return OIDCONF_PATTERN . format ( _iss )
Find the issuer ID and from it construct the service endpoint
38,478
def _update_service_context ( self , resp , ** kwargs ) : issuer = self . service_context . issuer if "issuer" in resp : _pcr_issuer = resp [ "issuer" ] if resp [ "issuer" ] . endswith ( "/" ) : if issuer . endswith ( "/" ) : _issuer = issuer else : _issuer = issuer + "/" else : if issuer . endswith ( "/" ) : _issuer =...
Deal with Provider Config Response . Based on the provider info response a set of parameters in different places needs to be set .
38,479
def get_http_url ( url , req , method = 'GET' ) : if method in [ "GET" , "DELETE" ] : if req . keys ( ) : _req = req . copy ( ) comp = urlsplit ( str ( url ) ) if comp . query : _req . update ( parse_qs ( comp . query ) ) _query = str ( _req . to_urlencoded ( ) ) return urlunsplit ( ( comp . scheme , comp . netloc , co...
Add a query part representing the request to a url that may already contain a query part . Only done if the HTTP method used is GET or DELETE .
38,480
def get_http_body ( req , content_type = URL_ENCODED ) : if URL_ENCODED in content_type : return req . to_urlencoded ( ) elif JSON_ENCODED in content_type : return req . to_json ( ) elif JOSE_ENCODED in content_type : return req else : raise UnSupported ( "Unsupported content type: '%s'" % content_type )
Get the message into the format that should be places in the body part of a HTTP request .
38,481
def importer ( name ) : c1 , c2 = modsplit ( name ) module = importlib . import_module ( c1 ) return getattr ( module , c2 )
Import by name
38,482
def rndstr ( size = 16 ) : _basech = string . ascii_letters + string . digits return "" . join ( [ rnd . choice ( _basech ) for _ in range ( size ) ] )
Returns a string of random ascii characters or digits
38,483
def add_redirect_uris ( request_args , service = None , ** kwargs ) : _context = service . service_context if "redirect_uris" not in request_args : try : _cbs = _context . callbacks except AttributeError : request_args [ 'redirect_uris' ] = _context . redirect_uris else : _uris = [ v for k , v in _cbs . items ( ) if no...
Add redirect_uris to the request arguments .
38,484
def match_preferences ( self , pcr = None , issuer = None ) : if not pcr : pcr = self . service_context . provider_info regreq = oidc . RegistrationRequest for _pref , _prov in PREFERENCE2PROVIDER . items ( ) : try : vals = self . service_context . client_preferences [ _pref ] except KeyError : continue try : _pvals = ...
Match the clients preferences against what the provider can do . This is to prepare for later client registration and or what functionality the client actually will use . In the client configuration the client preferences are expressed . These are then compared with the Provider Configuration information . If the Provi...
38,485
def soundexCode ( self , char ) : lang = get_language ( char ) try : if lang == "en_US" : return _soundex_map [ "soundex_en" ] [ charmap [ lang ] . index ( char ) ] else : return _soundex_map [ "soundex" ] [ charmap [ lang ] . index ( char ) ] except : pass return 0
Return the soundex code for given character
38,486
def soundex ( self , name , length = 8 ) : sndx = [ ] fc = name [ 0 ] for c in name [ 1 : ] . lower ( ) : d = str ( self . soundexCode ( c ) ) if d == '0' : continue if len ( sndx ) == 0 : sndx . append ( d ) elif d != sndx [ - 1 ] : sndx . append ( d ) sndx . insert ( 0 , fc ) if get_language ( name [ 0 ] ) == 'en_US'...
Calculate soundex of given string
38,487
def compare ( self , string1 , string2 ) : if string1 == string2 : return 0 string1_lang = get_language ( string1 [ 0 ] ) string2_lang = get_language ( string2 [ 0 ] ) if ( string1_lang == 'en_US' and string2_lang != 'en_US' ) or ( string1_lang != 'en_US' and string2_lang == 'en_US' ) : return - 1 soundex1 = self . sou...
Compare soundex of given strings
38,488
def get_response_for_url ( self , url ) : if not url or "//" not in url : raise ValueError ( "Missing or invalid url: %s" % url ) render_url = self . BASE_URL + url headers = { 'X-Prerender-Token' : self . token , } r = self . session . get ( render_url , headers = headers , allow_redirects = False ) assert r . status_...
Accepts a fully - qualified url . Returns an HttpResponse passing through all headers and the status code .
38,489
def update_url ( self , url = None , regex = None ) : if not url and not regex : raise ValueError ( "Neither a url or regex was provided to update_url." ) headers = { 'X-Prerender-Token' : self . token , 'Content-Type' : 'application/json' , } data = { 'prerenderToken' : settings . PRERENDER_TOKEN , } if url : data [ "...
Accepts a fully - qualified url or regex . Returns True if successful False if not successful .
38,490
def update_url ( self , url = None ) : if not url : raise ValueError ( "Neither a url or regex was provided to update_url." ) post_url = "%s%s" % ( self . BASE_URL , url ) r = self . session . post ( post_url ) return int ( r . status_code ) < 500
Accepts a fully - qualified url . Returns True if successful False if not successful .
38,491
def create ( self , validated_data ) : if 'user' not in validated_data : validated_data [ 'user' ] = self . context [ 'request' ] . user return super ( RefreshTokenSerializer , self ) . create ( validated_data )
Override create to provide a user via request . user by default .
38,492
def has_object_permission ( self , request , view , obj ) : user = request . user if not user . is_authenticated : return False elif user . is_staff or user . is_superuser : return True return user == obj . user
Allow staff or superusers and the owner of the object itself .
38,493
def clear ( self ) : with self . _cond : to_notify = self . _initial - self . _value self . _value = self . _initial self . _cond . notify ( to_notify )
Release the semaphore of all of its bounds setting the internal counter back to its original bind limit . Notify an equivalent amount of threads that they can run .
38,494
def _api_wrapper ( fn ) : def _convert ( value ) : if isinstance ( value , _datetime . date ) : return value . strftime ( '%s' ) return value @ _six . wraps ( fn ) def _fn ( self , command , ** params ) : with self . startup_lock : if self . timer . ident is None : self . timer . setDaemon ( True ) self . timer . start...
API function decorator that performs rate limiting and error checking .
38,495
def returnOrderBook ( self , currencyPair = 'all' , depth = '50' ) : return self . _public ( 'returnOrderBook' , currencyPair = currencyPair , depth = depth )
Returns the order book for a given market as well as a sequence number for use with the Push API and an indicator specifying whether the market is frozen . You may set currencyPair to all to get the order books of all markets .
38,496
def returnDepositsWithdrawals ( self , start = 0 , end = 2 ** 32 - 1 ) : return self . _private ( 'returnDepositsWithdrawals' , start = start , end = end )
Returns your deposit and withdrawal history within a range specified by the start and end POST parameters both of which should be given as UNIX timestamps .
38,497
def buy ( self , currencyPair , rate , amount , fillOrKill = None , immediateOrCancel = None , postOnly = None ) : return self . _private ( 'buy' , currencyPair = currencyPair , rate = rate , amount = amount , fillOrKill = fillOrKill , immediateOrCancel = immediateOrCancel , postOnly = postOnly )
Places a limit buy order in a given market . Required POST parameters are currencyPair rate and amount . If successful the method will return the order number . You may optionally set fillOrKill immediateOrCancel postOnly to 1 . A fill - or - kill order will either fill in its entirety or be completely aborted . An imm...
38,498
def moveOrder ( self , orderNumber , rate , amount = None , postOnly = None , immediateOrCancel = None ) : return self . _private ( 'moveOrder' , orderNumber = orderNumber , rate = rate , amount = amount , postOnly = postOnly , immediateOrCancel = immediateOrCancel )
Cancels an order and places a new one of the same type in a single atomic transaction meaning either both operations will succeed or both will fail . Required POST parameters are orderNumber and rate ; you may optionally specify amount if you wish to change the amount of the new order . postOnly or immediateOrCancel ma...
38,499
def withdraw ( self , currency , amount , address , paymentId = None ) : return self . _private ( 'withdraw' , currency = currency , amount = amount , address = address , paymentId = paymentId )
Immediately places a withdrawal for a given currency with no email confirmation . In order to use this method the withdrawal privilege must be enabled for your API key . Required POST parameters are currency amount and address . For XMR withdrawals you may optionally specify paymentId .