idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
21,100
def flip_coords ( X , loop ) : if ( loop [ 0 ] == 1 ) : return np . array ( map ( lambda i : np . array ( [ i [ 2 ] , i [ 1 ] , i [ 0 ] , i [ 5 ] , i [ 4 ] , i [ 3 ] ] ) , X ) ) else : return X
Align circulation with z - axis
75
7
21,101
def harmonic_oscillator_to_aa ( w , potential ) : usys = potential . units if usys is not None : x = w . xyz . decompose ( usys ) . value v = w . v_xyz . decompose ( usys ) . value else : x = w . xyz . value v = w . v_xyz . value _new_omega_shape = ( 3 , ) + tuple ( [ 1 ] * ( len ( x . shape ) - 1 ) ) # compute actions -- just energy (hamiltonian) over frequency if usys is None : usys = [ ] try : omega = potential . parameters [ 'omega' ] . reshape ( _new_omega_shape ) . decompose ( usys ) . value except AttributeError : # not a Quantity omega = potential . parameters [ 'omega' ] . reshape ( _new_omega_shape ) action = ( v ** 2 + ( omega * x ) ** 2 ) / ( 2. * omega ) angle = np . arctan ( - v / omega / x ) angle [ x == 0 ] = - np . sign ( v [ x == 0 ] ) * np . pi / 2. angle [ x < 0 ] += np . pi freq = potential . parameters [ 'omega' ] . decompose ( usys ) . value if usys is not None and usys : a_unit = ( 1 * usys [ 'angular momentum' ] / usys [ 'mass' ] ) . decompose ( usys ) . unit f_unit = ( 1 * usys [ 'frequency' ] ) . decompose ( usys ) . unit return action * a_unit , ( angle % ( 2. * np . pi ) ) * u . radian , freq * f_unit else : return action * u . one , ( angle % ( 2. * np . pi ) ) * u . one , freq * u . one
Transform the input cartesian position and velocity to action - angle coordinates for the Harmonic Oscillator potential .
425
22
21,102
def step ( self , t , w , dt ) : # Runge-Kutta Fehlberg formulas (see: Numerical Recipes) F = lambda t , w : self . F ( t , w , * self . _func_args ) K = np . zeros ( ( 6 , ) + w . shape ) K [ 0 ] = dt * F ( t , w ) K [ 1 ] = dt * F ( t + A [ 1 ] * dt , w + B [ 1 ] [ 0 ] * K [ 0 ] ) K [ 2 ] = dt * F ( t + A [ 2 ] * dt , w + B [ 2 ] [ 0 ] * K [ 0 ] + B [ 2 ] [ 1 ] * K [ 1 ] ) K [ 3 ] = dt * F ( t + A [ 3 ] * dt , w + B [ 3 ] [ 0 ] * K [ 0 ] + B [ 3 ] [ 1 ] * K [ 1 ] + B [ 3 ] [ 2 ] * K [ 2 ] ) K [ 4 ] = dt * F ( t + A [ 4 ] * dt , w + B [ 4 ] [ 0 ] * K [ 0 ] + B [ 4 ] [ 1 ] * K [ 1 ] + B [ 4 ] [ 2 ] * K [ 2 ] + B [ 4 ] [ 3 ] * K [ 3 ] ) K [ 5 ] = dt * F ( t + A [ 5 ] * dt , w + B [ 5 ] [ 0 ] * K [ 0 ] + B [ 5 ] [ 1 ] * K [ 1 ] + B [ 5 ] [ 2 ] * K [ 2 ] + B [ 5 ] [ 3 ] * K [ 3 ] + B [ 5 ] [ 4 ] * K [ 4 ] ) # shift dw = np . zeros_like ( w ) for i in range ( 6 ) : dw = dw + C [ i ] * K [ i ] return w + dw
Step forward the vector w by the given timestep .
428
12
21,103
def check_each_direction ( n , angs , ifprint = True ) : checks = np . array ( [ ] ) P = np . array ( [ ] ) if ( ifprint ) : print ( "\nChecking modes:\n====" ) for k , i in enumerate ( n ) : N_matrix = np . linalg . norm ( i ) X = np . dot ( angs , i ) if ( np . abs ( np . max ( X ) - np . min ( X ) ) < 2. * np . pi ) : if ( ifprint ) : print ( "Need a longer integration window for mode " , i ) checks = np . append ( checks , i ) P = np . append ( P , ( 2. * np . pi - np . abs ( np . max ( X ) - np . min ( X ) ) ) ) elif ( np . abs ( np . max ( X ) - np . min ( X ) ) / len ( X ) > np . pi ) : if ( ifprint ) : print ( "Need a finer sampling for mode " , i ) checks = np . append ( checks , i ) P = np . append ( P , ( 2. * np . pi - np . abs ( np . max ( X ) - np . min ( X ) ) ) ) if ( ifprint ) : print ( "====\n" ) return checks , P
returns a list of the index of elements of n which do not have adequate toy angle coverage . The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n
301
46
21,104
def unroll_angles ( A , sign ) : n = np . array ( [ 0 , 0 , 0 ] ) P = np . zeros ( np . shape ( A ) ) P [ 0 ] = A [ 0 ] for i in range ( 1 , len ( A ) ) : n = n + ( ( A [ i ] - A [ i - 1 ] + 0.5 * sign * np . pi ) * sign < 0 ) * np . ones ( 3 ) * 2. * np . pi P [ i ] = A [ i ] + sign * n return P
Unrolls the angles A so they increase continuously
123
10
21,105
def compute_coeffs ( density_func , nmax , lmax , M , r_s , args = ( ) , skip_odd = False , skip_even = False , skip_m = False , S_only = False , progress = False , * * nquad_opts ) : from gala . _cconfig import GSL_ENABLED if not GSL_ENABLED : raise ValueError ( "Gala was compiled without GSL and so this function " "will not work. See the gala documentation for more " "information about installing and using GSL with " "gala: http://gala.adrian.pw/en/latest/install.html" ) lmin = 0 lstride = 1 if skip_odd or skip_even : lstride = 2 if skip_even : lmin = 1 Snlm = np . zeros ( ( nmax + 1 , lmax + 1 , lmax + 1 ) ) Snlm_e = np . zeros ( ( nmax + 1 , lmax + 1 , lmax + 1 ) ) Tnlm = np . zeros ( ( nmax + 1 , lmax + 1 , lmax + 1 ) ) Tnlm_e = np . zeros ( ( nmax + 1 , lmax + 1 , lmax + 1 ) ) nquad_opts . setdefault ( 'limit' , 256 ) nquad_opts . setdefault ( 'epsrel' , 1E-10 ) limits = [ [ 0 , 2 * np . pi ] , # phi [ - 1 , 1. ] , # X (cos(theta)) [ - 1 , 1. ] ] # xsi nlms = [ ] for n in range ( nmax + 1 ) : for l in range ( lmin , lmax + 1 , lstride ) : for m in range ( l + 1 ) : if skip_m and m > 0 : continue nlms . append ( ( n , l , m ) ) if progress : try : from tqdm import tqdm except ImportError as e : raise ImportError ( 'tqdm is not installed - you can install it ' 'with `pip install tqdm`.\n' + str ( e ) ) iterfunc = tqdm else : iterfunc = lambda x : x for n , l , m in iterfunc ( nlms ) : Snlm [ n , l , m ] , Snlm_e [ n , l , m ] = si . nquad ( Snlm_integrand , ranges = limits , args = ( density_func , n , l , m , M , r_s , args ) , opts = nquad_opts ) if not S_only : Tnlm [ n , l , m ] , Tnlm_e [ n , l , m ] = si . nquad ( Tnlm_integrand , ranges = limits , args = ( density_func , n , l , m , M , r_s , args ) , opts = nquad_opts ) return ( Snlm , Snlm_e ) , ( Tnlm , Tnlm_e )
Compute the expansion coefficients for representing the input density function using a basis function expansion .
692
17
21,106
def compute_coeffs_discrete ( xyz , mass , nmax , lmax , r_s , skip_odd = False , skip_even = False , skip_m = False , compute_var = False ) : lmin = 0 lstride = 1 if skip_odd or skip_even : lstride = 2 if skip_even : lmin = 1 Snlm = np . zeros ( ( nmax + 1 , lmax + 1 , lmax + 1 ) ) Tnlm = np . zeros ( ( nmax + 1 , lmax + 1 , lmax + 1 ) ) if compute_var : Snlm_var = np . zeros ( ( nmax + 1 , lmax + 1 , lmax + 1 ) ) Tnlm_var = np . zeros ( ( nmax + 1 , lmax + 1 , lmax + 1 ) ) # positions and masses of point masses xyz = np . ascontiguousarray ( np . atleast_2d ( xyz ) ) mass = np . ascontiguousarray ( np . atleast_1d ( mass ) ) r = np . sqrt ( np . sum ( xyz ** 2 , axis = - 1 ) ) s = r / r_s phi = np . arctan2 ( xyz [ : , 1 ] , xyz [ : , 0 ] ) X = xyz [ : , 2 ] / r for n in range ( nmax + 1 ) : for l in range ( lmin , lmax + 1 , lstride ) : for m in range ( l + 1 ) : if skip_m and m > 0 : continue # logger.debug("Computing coefficients (n,l,m)=({},{},{})".format(n,l,m)) Snlm [ n , l , m ] , Tnlm [ n , l , m ] = STnlm_discrete ( s , phi , X , mass , n , l , m ) if compute_var : Snlm_var [ n , l , m ] , Tnlm_var [ n , l , m ] = STnlm_var_discrete ( s , phi , X , mass , n , l , m ) if compute_var : return ( Snlm , Snlm_var ) , ( Tnlm , Tnlm_var ) else : return Snlm , Tnlm
Compute the expansion coefficients for representing the density distribution of input points as a basis function expansion . The points xyz are assumed to be samples from the density distribution .
529
33
21,107
def integrate_orbit ( self , * * time_spec ) : # Prepare the initial conditions pos = self . w0 . xyz . decompose ( self . units ) . value vel = self . w0 . v_xyz . decompose ( self . units ) . value w0 = np . ascontiguousarray ( np . vstack ( ( pos , vel ) ) . T ) # Prepare the time-stepping array t = parse_time_specification ( self . units , * * time_spec ) ws = _direct_nbody_dop853 ( w0 , t , self . _ext_ham , self . particle_potentials ) pos = np . rollaxis ( np . array ( ws [ ... , : 3 ] ) , axis = 2 ) vel = np . rollaxis ( np . array ( ws [ ... , 3 : ] ) , axis = 2 ) orbits = Orbit ( pos = pos * self . units [ 'length' ] , vel = vel * self . units [ 'length' ] / self . units [ 'time' ] , t = t * self . units [ 'time' ] ) return orbits
Integrate the initial conditions in the combined external potential plus N - body forces .
247
16
21,108
def _apply ( self , method , * args , * * kwargs ) : if callable ( method ) : apply_method = lambda array : method ( array , * args , * * kwargs ) else : apply_method = operator . methodcaller ( method , * args , * * kwargs ) return self . __class__ ( [ apply_method ( getattr ( self , component ) ) for component in self . components ] , copy = False )
Create a new representation with method applied to the arrays .
100
11
21,109
def get_xyz ( self , xyz_axis = 0 ) : # Add new axis in x, y, z so one can concatenate them around it. # NOTE: just use np.stack once our minimum numpy version is 1.10. result_ndim = self . ndim + 1 if not - result_ndim <= xyz_axis < result_ndim : raise IndexError ( 'xyz_axis {0} out of bounds [-{1}, {1})' . format ( xyz_axis , result_ndim ) ) if xyz_axis < 0 : xyz_axis += result_ndim # Get components to the same units (very fast for identical units) # since np.concatenate cannot deal with quantity. unit = self . _x1 . unit sh = self . shape sh = sh [ : xyz_axis ] + ( 1 , ) + sh [ xyz_axis : ] components = [ getattr ( self , '_' + name ) . reshape ( sh ) . to ( unit ) . value for name in self . attr_classes ] xs_value = np . concatenate ( components , axis = xyz_axis ) return u . Quantity ( xs_value , unit = unit , copy = False )
Return a vector array of the x y and z coordinates .
278
12
21,110
def _get_c_valid_arr ( self , x ) : orig_shape = x . shape x = np . ascontiguousarray ( x . reshape ( orig_shape [ 0 ] , - 1 ) . T ) return orig_shape , x
Warning! Interpretation of axes is different for C code .
55
12
21,111
def _validate_prepare_time ( self , t , pos_c ) : if hasattr ( t , 'unit' ) : t = t . decompose ( self . units ) . value if not isiterable ( t ) : t = np . atleast_1d ( t ) t = np . ascontiguousarray ( t . ravel ( ) ) if len ( t ) > 1 : if len ( t ) != pos_c . shape [ 0 ] : raise ValueError ( "If passing in an array of times, it must have a shape " "compatible with the input position(s)." ) return t
Make sure that t is a 1D array and compatible with the C position array .
135
17
21,112
def get_components ( self , which ) : mappings = self . representation_mappings . get ( getattr ( self , which ) . __class__ , [ ] ) old_to_new = dict ( ) for name in getattr ( self , which ) . components : for m in mappings : if isinstance ( m , RegexRepresentationMapping ) : pattr = re . match ( m . repr_name , name ) old_to_new [ name ] = m . new_name . format ( * pattr . groups ( ) ) elif m . repr_name == name : old_to_new [ name ] = m . new_name mapping = OrderedDict ( ) for name in getattr ( self , which ) . components : mapping [ old_to_new . get ( name , name ) ] = name return mapping
Get the component name dictionary for the desired object .
184
10
21,113
def to_frame ( self , frame , current_frame = None , * * kwargs ) : from . . potential . frame . builtin import transformations as frame_trans if ( ( inspect . isclass ( frame ) and issubclass ( frame , coord . BaseCoordinateFrame ) ) or isinstance ( frame , coord . BaseCoordinateFrame ) ) : import warnings warnings . warn ( "This function now expects a " "`gala.potential.FrameBase` instance. To transform to" " an Astropy coordinate frame, use the " "`.to_coord_frame()` method instead." , DeprecationWarning ) return self . to_coord_frame ( frame = frame , * * kwargs ) if self . frame is None and current_frame is None : raise ValueError ( "If no frame was specified when this {} was " "initialized, you must pass the current frame in " "via the current_frame argument to transform to a " "new frame." ) elif self . frame is not None and current_frame is None : current_frame = self . frame name1 = current_frame . __class__ . __name__ . rstrip ( 'Frame' ) . lower ( ) name2 = frame . __class__ . __name__ . rstrip ( 'Frame' ) . lower ( ) func_name = "{}_to_{}" . format ( name1 , name2 ) if not hasattr ( frame_trans , func_name ) : raise ValueError ( "Unsupported frame transformation: {} to {}" . format ( current_frame , frame ) ) else : trans_func = getattr ( frame_trans , func_name ) pos , vel = trans_func ( current_frame , frame , self , * * kwargs ) return PhaseSpacePosition ( pos = pos , vel = vel , frame = frame )
Transform to a new reference frame .
395
7
21,114
def to_coord_frame ( self , frame , galactocentric_frame = None , * * kwargs ) : if self . ndim != 3 : raise ValueError ( "Can only change representation for " "ndim=3 instances." ) if galactocentric_frame is None : galactocentric_frame = coord . Galactocentric ( ) if 'vcirc' in kwargs or 'vlsr' in kwargs : import warnings warnings . warn ( "Instead of passing in 'vcirc' and 'vlsr', specify " "these parameters to the input Galactocentric frame " "using the `galcen_v_sun` argument." , DeprecationWarning ) pos_keys = list ( self . pos_components . keys ( ) ) vel_keys = list ( self . vel_components . keys ( ) ) if ( getattr ( self , pos_keys [ 0 ] ) . unit == u . one or getattr ( self , vel_keys [ 0 ] ) . unit == u . one ) : raise u . UnitConversionError ( "Position and velocity must have " "dimensioned units to convert to a " "coordinate frame." ) # first we need to turn the position into a Galactocentric instance gc_c = galactocentric_frame . realize_frame ( self . pos . with_differentials ( self . vel ) ) c = gc_c . transform_to ( frame ) return c
Transform the orbit from Galactocentric cartesian coordinates to Heliocentric coordinates in the specified Astropy coordinate frame .
319
25
21,115
def _plot_prepare ( self , components , units ) : # components to plot if components is None : components = self . pos . components n_comps = len ( components ) # if units not specified, get units from the components if units is not None : if isinstance ( units , u . UnitBase ) : units = [ units ] * n_comps # global unit elif len ( units ) != n_comps : raise ValueError ( 'You must specify a unit for each axis, or a ' 'single unit for all axes.' ) labels = [ ] x = [ ] for i , name in enumerate ( components ) : val = getattr ( self , name ) if units is not None : val = val . to ( units [ i ] ) unit = units [ i ] else : unit = val . unit if val . unit != u . one : uu = unit . to_string ( format = 'latex_inline' ) unit_str = ' [{}]' . format ( uu ) else : unit_str = '' # Figure out how to fancy display the component name if name . startswith ( 'd_' ) : dot = True name = name [ 2 : ] else : dot = False if name in _greek_letters : name = r"\{}" . format ( name ) if dot : name = "\dot{{{}}}" . format ( name ) labels . append ( '${}$' . format ( name ) + unit_str ) x . append ( val . value ) return x , labels
Prepare the PhaseSpacePosition or subclass for passing to a plotting routine to plot all projections of the object .
331
22
21,116
def get_account_info ( self ) : request = self . _get_request ( ) response = request . get ( self . ACCOUNT_INFO_URL ) self . account . json_data = response [ "account" ] return self . account
Get current account information
53
4
21,117
def update_account_info ( self ) : request = self . _get_request ( ) return request . post ( self . ACCOUNT_UPDATE_URL , { 'callback_url' : self . account . callback_url } )
Update current account information
50
4
21,118
def verify_account ( self , email_address ) : request = self . _get_request ( ) resp = request . post ( self . ACCOUNT_VERIFY_URL , { 'email_address' : email_address } ) return ( 'account' in resp )
Verify whether a HelloSign Account exists
59
8
21,119
def get_signature_request ( self , signature_request_id , ux_version = None ) : request = self . _get_request ( ) parameters = None if ux_version is not None : parameters = { 'ux_version' : ux_version } return request . get ( self . SIGNATURE_REQUEST_INFO_URL + signature_request_id , parameters = parameters )
Get a signature request by its ID
87
7
21,120
def get_signature_request_list ( self , page = 1 , ux_version = None ) : request = self . _get_request ( ) parameters = { "page" : page } if ux_version is not None : parameters [ 'ux_version' ] = ux_version return request . get ( self . SIGNATURE_REQUEST_LIST_URL , parameters = parameters )
Get a list of SignatureRequest that you can access
86
10
21,121
def get_signature_request_file ( self , signature_request_id , path_or_file = None , file_type = None , filename = None ) : request = self . _get_request ( ) url = self . SIGNATURE_REQUEST_DOWNLOAD_PDF_URL + signature_request_id if file_type : url += '?file_type=%s' % file_type return request . get_file ( url , path_or_file or filename )
Download the PDF copy of the current documents
106
8
21,122
def send_signature_request ( self , test_mode = False , files = None , file_urls = None , title = None , subject = None , message = None , signing_redirect_url = None , signers = None , cc_email_addresses = None , form_fields_per_document = None , use_text_tags = False , hide_text_tags = False , metadata = None , ux_version = None , allow_decline = False ) : self . _check_required_fields ( { "signers" : signers } , [ { "files" : files , "file_urls" : file_urls } ] ) params = { 'test_mode' : test_mode , 'files' : files , 'file_urls' : file_urls , 'title' : title , 'subject' : subject , 'message' : message , 'signing_redirect_url' : signing_redirect_url , 'signers' : signers , 'cc_email_addresses' : cc_email_addresses , 'form_fields_per_document' : form_fields_per_document , 'use_text_tags' : use_text_tags , 'hide_text_tags' : hide_text_tags , 'metadata' : metadata , 'allow_decline' : allow_decline } if ux_version is not None : params [ 'ux_version' ] = ux_version return self . _send_signature_request ( * * params )
Creates and sends a new SignatureRequest with the submitted documents
339
12
21,123
def send_signature_request_with_template ( self , test_mode = False , template_id = None , template_ids = None , title = None , subject = None , message = None , signing_redirect_url = None , signers = None , ccs = None , custom_fields = None , metadata = None , ux_version = None , allow_decline = False ) : self . _check_required_fields ( { "signers" : signers } , [ { "template_id" : template_id , "template_ids" : template_ids } ] ) params = { 'test_mode' : test_mode , 'template_id' : template_id , 'template_ids' : template_ids , 'title' : title , 'subject' : subject , 'message' : message , 'signing_redirect_url' : signing_redirect_url , 'signers' : signers , 'ccs' : ccs , 'custom_fields' : custom_fields , 'metadata' : metadata , 'allow_decline' : allow_decline } if ux_version is not None : params [ 'ux_version' ] = ux_version return self . _send_signature_request_with_template ( * * params )
Creates and sends a new SignatureRequest based off of a Template
284
13
21,124
def remind_signature_request ( self , signature_request_id , email_address ) : request = self . _get_request ( ) return request . post ( self . SIGNATURE_REQUEST_REMIND_URL + signature_request_id , data = { "email_address" : email_address } )
Sends an email to the signer reminding them to sign the signature request
69
15
21,125
def cancel_signature_request ( self , signature_request_id ) : request = self . _get_request ( ) request . post ( url = self . SIGNATURE_REQUEST_CANCEL_URL + signature_request_id , get_json = False )
Cancels a SignatureRequest
59
6
21,126
def get_template ( self , template_id ) : request = self . _get_request ( ) return request . get ( self . TEMPLATE_GET_URL + template_id )
Gets a Template which includes a list of Accounts that can access it
42
14
21,127
def get_template_list ( self , page = 1 , page_size = None , account_id = None , query = None ) : request = self . _get_request ( ) parameters = { 'page' : page , 'page_size' : page_size , 'account_id' : account_id , 'query' : query } return request . get ( self . TEMPLATE_GET_LIST_URL , parameters = parameters )
Lists your Templates
97
5
21,128
def add_user_to_template ( self , template_id , account_id = None , email_address = None ) : return self . _add_remove_user_template ( self . TEMPLATE_ADD_USER_URL , template_id , account_id , email_address )
Gives the specified Account access to the specified Template
65
10
21,129
def remove_user_from_template ( self , template_id , account_id = None , email_address = None ) : return self . _add_remove_user_template ( self . TEMPLATE_REMOVE_USER_URL , template_id , account_id , email_address )
Removes the specified Account s access to the specified Template
67
11
21,130
def delete_template ( self , template_id ) : url = self . TEMPLATE_DELETE_URL request = self . _get_request ( ) response = request . post ( url + template_id , get_json = False ) return response
Deletes the specified template
56
5
21,131
def get_template_files ( self , template_id , filename ) : url = self . TEMPLATE_GET_FILES_URL + template_id request = self . _get_request ( ) return request . get_file ( url , filename )
Download a PDF copy of a template s original files
56
10
21,132
def create_embedded_template_draft ( self , client_id , signer_roles , test_mode = False , files = None , file_urls = None , title = None , subject = None , message = None , cc_roles = None , merge_fields = None , use_preexisting_fields = False ) : params = { 'test_mode' : test_mode , 'client_id' : client_id , 'files' : files , 'file_urls' : file_urls , 'title' : title , 'subject' : subject , 'message' : message , 'signer_roles' : signer_roles , 'cc_roles' : cc_roles , 'merge_fields' : merge_fields , 'use_preexisting_fields' : use_preexisting_fields } return self . _create_embedded_template_draft ( * * params )
Creates an embedded Template draft for further editing .
209
10
21,133
def create_team ( self , name ) : request = self . _get_request ( ) return request . post ( self . TEAM_CREATE_URL , { "name" : name } )
Creates a new Team
42
5
21,134
def update_team_name ( self , name ) : request = self . _get_request ( ) return request . post ( self . TEAM_UPDATE_URL , { "name" : name } )
Updates a Team s name
43
6
21,135
def destroy_team ( self ) : request = self . _get_request ( ) request . post ( url = self . TEAM_DESTROY_URL , get_json = False )
Delete your Team
40
3
21,136
def add_team_member ( self , account_id = None , email_address = None ) : return self . _add_remove_team_member ( self . TEAM_ADD_MEMBER_URL , email_address , account_id )
Add or invite a user to your Team
53
8
21,137
def remove_team_member ( self , account_id = None , email_address = None ) : return self . _add_remove_team_member ( self . TEAM_REMOVE_MEMBER_URL , email_address , account_id )
Remove a user from your Team
55
6
21,138
def get_embedded_object ( self , signature_id ) : request = self . _get_request ( ) return request . get ( self . EMBEDDED_OBJECT_GET_URL + signature_id )
Retrieves a embedded signing object
49
7
21,139
def get_template_edit_url ( self , template_id ) : request = self . _get_request ( ) return request . get ( self . EMBEDDED_TEMPLATE_EDIT_URL + template_id )
Retrieves a embedded template for editing
52
8
21,140
def get_oauth_data ( self , code , client_id , client_secret , state ) : request = self . _get_request ( ) response = request . post ( self . OAUTH_TOKEN_URL , { "state" : state , "code" : code , "grant_type" : "authorization_code" , "client_id" : client_id , "client_secret" : client_secret } ) return HSAccessTokenAuth . from_response ( response )
Get Oauth data from HelloSign
111
7
21,141
def refresh_access_token ( self , refresh_token ) : request = self . _get_request ( ) response = request . post ( self . OAUTH_TOKEN_URL , { "grant_type" : "refresh_token" , "refresh_token" : refresh_token } ) self . auth = HSAccessTokenAuth . from_response ( response ) return self . auth . access_token
Refreshes the current access token .
92
8
21,142
def _get_request ( self , auth = None ) : self . request = HSRequest ( auth or self . auth , self . env ) self . request . response_callback = self . response_callback return self . request
Return an http request object
47
5
21,143
def _authenticate ( self , email_address = None , password = None , api_key = None , access_token = None , access_token_type = None ) : if access_token_type and access_token : return HSAccessTokenAuth ( access_token , access_token_type ) elif api_key : return HTTPBasicAuth ( api_key , '' ) elif email_address and password : return HTTPBasicAuth ( email_address , password ) else : raise NoAuthMethod ( "No authentication information found!" )
Create authentication object to send requests
116
6
21,144
def _check_required_fields ( self , fields = None , either_fields = None ) : for ( key , value ) in fields . items ( ) : # If value is a dict, one of the fields in the dict is required -> # exception if all are None if not value : raise HSException ( "Field '%s' is required." % key ) if either_fields is not None : for field in either_fields : if not any ( field . values ( ) ) : raise HSException ( "One of the following fields is required: %s" % ", " . join ( field . keys ( ) ) )
Check the values of the fields
132
6
21,145
def _send_signature_request ( self , test_mode = False , client_id = None , files = None , file_urls = None , title = None , subject = None , message = None , signing_redirect_url = None , signers = None , cc_email_addresses = None , form_fields_per_document = None , use_text_tags = False , hide_text_tags = False , metadata = None , ux_version = None , allow_decline = False ) : # Files files_payload = HSFormat . format_file_params ( files ) # File URLs file_urls_payload = HSFormat . format_file_url_params ( file_urls ) # Signers signers_payload = HSFormat . format_dict_list ( signers , 'signers' ) # CCs cc_email_addresses_payload = HSFormat . format_param_list ( cc_email_addresses , 'cc_email_addresses' ) # Metadata metadata_payload = HSFormat . format_single_dict ( metadata , 'metadata' ) payload = { "test_mode" : self . _boolean ( test_mode ) , "client_id" : client_id , "title" : title , "subject" : subject , "message" : message , "signing_redirect_url" : signing_redirect_url , "form_fields_per_document" : form_fields_per_document , "use_text_tags" : self . _boolean ( use_text_tags ) , "hide_text_tags" : self . _boolean ( hide_text_tags ) , "allow_decline" : self . _boolean ( allow_decline ) } if ux_version is not None : payload [ 'ux_version' ] = ux_version # remove attributes with none value payload = HSFormat . strip_none_values ( payload ) url = self . SIGNATURE_REQUEST_CREATE_URL if client_id : url = self . SIGNATURE_REQUEST_CREATE_EMBEDDED_URL data = { } data . update ( payload ) data . update ( signers_payload ) data . update ( cc_email_addresses_payload ) data . update ( file_urls_payload ) data . update ( metadata_payload ) request = self . _get_request ( ) response = request . post ( url , data = data , files = files_payload ) return response
To share the same logic between send_signature_request & send_signature_request_embedded functions
556
23
21,146
def _send_signature_request_with_template ( self , test_mode = False , client_id = None , template_id = None , template_ids = None , title = None , subject = None , message = None , signing_redirect_url = None , signers = None , ccs = None , custom_fields = None , metadata = None , ux_version = None , allow_decline = False ) : # Signers signers_payload = HSFormat . format_dict_list ( signers , 'signers' , 'role_name' ) # CCs ccs_payload = HSFormat . format_dict_list ( ccs , 'ccs' , 'role_name' ) # Custom fields custom_fields_payload = HSFormat . format_custom_fields ( custom_fields ) # Metadata metadata_payload = HSFormat . format_single_dict ( metadata , 'metadata' ) # Template ids template_ids_payload = { } if template_ids : for i in range ( len ( template_ids ) ) : template_ids_payload [ "template_ids[%s]" % i ] = template_ids [ i ] payload = { "test_mode" : self . _boolean ( test_mode ) , "client_id" : client_id , "template_id" : template_id , "title" : title , "subject" : subject , "message" : message , "signing_redirect_url" : signing_redirect_url , "allow_decline" : self . _boolean ( allow_decline ) } if ux_version is not None : payload [ 'ux_version' ] = ux_version # remove attributes with empty value payload = HSFormat . strip_none_values ( payload ) url = self . SIGNATURE_REQUEST_CREATE_WITH_TEMPLATE_URL if client_id : url = self . SIGNATURE_REQUEST_CREATE_EMBEDDED_WITH_TEMPLATE_URL data = payload . copy ( ) data . update ( signers_payload ) data . update ( ccs_payload ) data . update ( custom_fields_payload ) data . update ( metadata_payload ) data . update ( template_ids_payload ) request = self . _get_request ( ) response = request . post ( url , data = data ) return response
To share the same logic between send_signature_request_with_template and send_signature_request_embedded_with_template
533
30
21,147
def _add_remove_user_template ( self , url , template_id , account_id = None , email_address = None ) : if not email_address and not account_id : raise HSException ( "No email address or account_id specified" ) data = { } if account_id is not None : data = { "account_id" : account_id } else : data = { "email_address" : email_address } request = self . _get_request ( ) response = request . post ( url + template_id , data ) return response
Add or Remove user from a Template
123
7
21,148
def _add_remove_team_member ( self , url , email_address = None , account_id = None ) : if not email_address and not account_id : raise HSException ( "No email address or account_id specified" ) data = { } if account_id is not None : data = { "account_id" : account_id } else : data = { "email_address" : email_address } request = self . _get_request ( ) response = request . post ( url , data ) return response
Add or Remove a team member
115
6
21,149
def _create_embedded_template_draft ( self , client_id , signer_roles , test_mode = False , files = None , file_urls = None , title = None , subject = None , message = None , cc_roles = None , merge_fields = None , use_preexisting_fields = False ) : url = self . TEMPLATE_CREATE_EMBEDDED_DRAFT_URL payload = { 'test_mode' : self . _boolean ( test_mode ) , 'client_id' : client_id , 'title' : title , 'subject' : subject , 'message' : message , 'use_preexisting_fields' : self . _boolean ( use_preexisting_fields ) } # Prep files files_payload = HSFormat . format_file_params ( files ) file_urls_payload = HSFormat . format_file_url_params ( file_urls ) # Prep Signer Roles signer_roles_payload = HSFormat . format_dict_list ( signer_roles , 'signer_roles' ) # Prep CCs ccs_payload = HSFormat . format_param_list ( cc_roles , 'cc_roles' ) # Prep Merge Fields merge_fields_payload = { 'merge_fields' : json . dumps ( merge_fields ) } # Assemble data for sending data = { } data . update ( payload ) data . update ( file_urls_payload ) data . update ( signer_roles_payload ) data . update ( ccs_payload ) if ( merge_fields is not None ) : data . update ( merge_fields_payload ) data = HSFormat . strip_none_values ( data ) request = self . _get_request ( ) response = request . post ( url , data = data , files = files_payload ) return response
Helper method for creating embedded template drafts . See public function for params .
430
14
21,150
def _create_embedded_unclaimed_draft_with_template ( self , test_mode = False , client_id = None , is_for_embedded_signing = False , template_id = None , template_ids = None , requester_email_address = None , title = None , subject = None , message = None , signers = None , ccs = None , signing_redirect_url = None , requesting_redirect_url = None , metadata = None , custom_fields = None , allow_decline = False ) : #single params payload = { "test_mode" : self . _boolean ( test_mode ) , "client_id" : client_id , "is_for_embedded_signing" : self . _boolean ( is_for_embedded_signing ) , "template_id" : template_id , "requester_email_address" : requester_email_address , "title" : title , "subject" : subject , "message" : message , "signing_redirect_url" : signing_redirect_url , "requesting_redirect_url" : requesting_redirect_url , "allow_decline" : self . _boolean ( allow_decline ) } #format multi params template_ids_payload = HSFormat . format_param_list ( template_ids , 'template_ids' ) signers_payload = HSFormat . format_dict_list ( signers , 'signers' , 'role_name' ) ccs_payload = HSFormat . format_dict_list ( ccs , 'ccs' , 'role_name' ) metadata_payload = HSFormat . format_single_dict ( metadata , 'metadata' ) custom_fields_payload = HSFormat . format_custom_fields ( custom_fields ) #assemble payload data = { } data . update ( payload ) data . update ( template_ids_payload ) data . update ( signers_payload ) data . update ( ccs_payload ) data . update ( metadata_payload ) data . update ( custom_fields_payload ) data = HSFormat . strip_none_values ( data ) #send call url = self . UNCLAIMED_DRAFT_CREATE_EMBEDDED_WITH_TEMPLATE_URL request = self . _get_request ( ) response = request . post ( url , data = data ) return response
Helper method for creating unclaimed drafts from templates See public function for params .
542
15
21,151
def get_file ( self , url , path_or_file = None , headers = None , filename = None ) : path_or_file = path_or_file or filename if self . debug : print ( "GET FILE: %s, headers=%s" % ( url , headers ) ) self . headers = self . _get_default_headers ( ) if headers is not None : self . headers . update ( headers ) response = requests . get ( url , headers = self . headers , auth = self . auth , verify = self . verify_ssl ) self . http_status_code = response . status_code try : # No need to check for warnings here self . _check_error ( response ) try : path_or_file . write ( response . content ) except AttributeError : fd = os . open ( path_or_file , os . O_CREAT | os . O_RDWR ) with os . fdopen ( fd , "w+b" ) as f : f . write ( response . content ) except : return False return True
Get a file from a url and save it as filename
232
11
21,152
def get ( self , url , headers = None , parameters = None , get_json = True ) : if self . debug : print ( "GET: %s, headers=%s" % ( url , headers ) ) self . headers = self . _get_default_headers ( ) get_parameters = self . parameters if get_parameters is None : # In case self.parameters is still empty get_parameters = { } if headers is not None : self . headers . update ( headers ) if parameters is not None : get_parameters . update ( parameters ) response = requests . get ( url , headers = self . headers , params = get_parameters , auth = self . auth , verify = self . verify_ssl ) json_response = self . _process_json_response ( response ) return json_response if get_json is True else response
Send a GET request with custome headers and parameters
185
10
21,153
def post ( self , url , data = None , files = None , headers = None , get_json = True ) : if self . debug : print ( "POST: %s, headers=%s" % ( url , headers ) ) self . headers = self . _get_default_headers ( ) if headers is not None : self . headers . update ( headers ) response = requests . post ( url , headers = self . headers , data = data , auth = self . auth , files = files , verify = self . verify_ssl ) json_response = self . _process_json_response ( response ) return json_response if get_json is True else response
Make POST request to a url
142
6
21,154
def _get_json_response ( self , resp ) : if resp is not None and resp . text is not None : try : text = resp . text . strip ( '\n' ) if len ( text ) > 0 : return json . loads ( text ) except ValueError as e : if self . debug : print ( "Could not decode JSON response: \"%s\"" % resp . text ) raise e
Parse a JSON response
88
5
21,155
def _process_json_response ( self , response ) : json_response = self . _get_json_response ( response ) if self . response_callback is not None : json_response = self . response_callback ( json_response ) response . _content = json . dumps ( json_response ) self . http_status_code = response . status_code self . _check_error ( response , json_response ) self . _check_warnings ( json_response ) return json_response
Process a given response
107
4
21,156
def _check_error ( self , response , json_response = None ) : # If status code is 4xx or 5xx, that should be an error if response . status_code >= 400 : json_response = json_response or self . _get_json_response ( response ) err_cls = self . _check_http_error_code ( response . status_code ) try : raise err_cls ( "%s error: %s" % ( response . status_code , json_response [ "error" ] [ "error_msg" ] ) , response . status_code ) # This is to catch error when we post get oauth data except TypeError : raise err_cls ( "%s error: %s" % ( response . status_code , json_response [ "error_description" ] ) , response . status_code ) # Return True if everything is OK return True
Check for HTTP error code from the response raise exception if there s any
194
14
21,157
def _check_warnings ( self , json_response ) : self . warnings = None if json_response : self . warnings = json_response . get ( 'warnings' ) if self . debug and self . warnings : for w in self . warnings : print ( "WARNING: %s - %s" % ( w [ 'warning_name' ] , w [ 'warning_msg' ] ) )
Extract warnings from the response to make them accessible
87
10
21,158
def from_response ( self , response_data ) : return HSAccessTokenAuth ( response_data [ 'access_token' ] , response_data [ 'token_type' ] , response_data [ 'refresh_token' ] , response_data [ 'expires_in' ] , response_data . get ( 'state' ) # Not always here )
Builds a new HSAccessTokenAuth straight from response data
80
13
21,159
def find_response_component ( self , api_id = None , signature_id = None ) : if not api_id and not signature_id : raise ValueError ( 'At least one of api_id and signature_id is required' ) components = list ( ) if self . response_data : for component in self . response_data : if ( api_id and component [ 'api_id' ] ) == api_id or ( signature_id and component [ 'signature_id' ] == signature_id ) : components . append ( component ) return components
Find one or many repsonse components .
122
8
21,160
def find_signature ( self , signature_id = None , signer_email_address = None ) : if self . signatures : for signature in self . signatures : if signature . signature_id == signature_id or signature . signer_email_address == signer_email_address : return signature
Return a signature for the given parameters
65
7
21,161
def _uncamelize ( self , s ) : res = '' if s : for i in range ( len ( s ) ) : if i > 0 and s [ i ] . lower ( ) != s [ i ] : res += '_' res += s [ i ] . lower ( ) return res
Convert a camel - cased string to using underscores
64
11
21,162
def format_file_params ( files ) : files_payload = { } if files : for idx , filename in enumerate ( files ) : files_payload [ "file[" + str ( idx ) + "]" ] = open ( filename , 'rb' ) return files_payload
Utility method for formatting file parameters for transmission
64
9
21,163
def format_file_url_params ( file_urls ) : file_urls_payload = { } if file_urls : for idx , fileurl in enumerate ( file_urls ) : file_urls_payload [ "file_url[" + str ( idx ) + "]" ] = fileurl return file_urls_payload
Utility method for formatting file URL parameters for transmission
81
10
21,164
def format_single_dict ( dictionary , output_name ) : output_payload = { } if dictionary : for ( k , v ) in dictionary . items ( ) : output_payload [ output_name + '[' + k + ']' ] = v return output_payload
Currently used for metadata fields
61
5
21,165
def format_custom_fields ( list_of_custom_fields ) : output_payload = { } if list_of_custom_fields : # custom_field: {"name": value} for custom_field in list_of_custom_fields : for key , value in custom_field . items ( ) : output_payload [ "custom_fields[" + key + "]" ] = value return output_payload
Custom fields formatting for submission
91
5
21,166
def read ( fname , fail_silently = False ) : try : filepath = os . path . join ( os . path . dirname ( __file__ ) , fname ) with io . open ( filepath , 'rt' , encoding = 'utf8' ) as f : return f . read ( ) except : if not fail_silently : raise return ''
Read the content of the given file . The path is evaluated from the directory containing this file .
80
19
21,167
def pass_verbosity ( f ) : def new_func ( * args , * * kwargs ) : kwargs [ 'verbosity' ] = click . get_current_context ( ) . verbosity return f ( * args , * * kwargs ) return update_wrapper ( new_func , f )
Marks a callback as wanting to receive the verbosity as a keyword argument .
69
16
21,168
def run_from_argv ( self , argv ) : try : return self . main ( args = argv [ 2 : ] , standalone_mode = False ) except click . ClickException as e : if getattr ( e . ctx , 'traceback' , False ) : raise e . show ( ) sys . exit ( e . exit_code )
Called when run from the command line .
77
9
21,169
def encrypt ( data , key ) : data = __tobytes ( data ) data_len = len ( data ) data = ffi . from_buffer ( data ) key = ffi . from_buffer ( __tobytes ( key ) ) out_len = ffi . new ( 'size_t *' ) result = lib . xxtea_encrypt ( data , data_len , key , out_len ) ret = ffi . buffer ( result , out_len [ 0 ] ) [ : ] lib . free ( result ) return ret
encrypt the data with the key
119
7
21,170
def decrypt ( data , key ) : data_len = len ( data ) data = ffi . from_buffer ( data ) key = ffi . from_buffer ( __tobytes ( key ) ) out_len = ffi . new ( 'size_t *' ) result = lib . xxtea_decrypt ( data , data_len , key , out_len ) ret = ffi . buffer ( result , out_len [ 0 ] ) [ : ] lib . free ( result ) return ret
decrypt the data with the key
110
7
21,171
def flaskrun ( app , default_host = "127.0.0.1" , default_port = "8000" ) : # Set up the command-line options parser = optparse . OptionParser ( ) parser . add_option ( "-H" , "--host" , help = "Hostname of the Flask app " + "[default %s]" % default_host , default = default_host , ) parser . add_option ( "-P" , "--port" , help = "Port for the Flask app " + "[default %s]" % default_port , default = default_port , ) # Two options useful for debugging purposes, but # a bit dangerous so not exposed in the help message. parser . add_option ( "-d" , "--debug" , action = "store_true" , dest = "debug" , help = optparse . SUPPRESS_HELP ) parser . add_option ( "-p" , "--profile" , action = "store_true" , dest = "profile" , help = optparse . SUPPRESS_HELP , ) options , _ = parser . parse_args ( ) # If the user selects the profiling option, then we need # to do a little extra setup if options . profile : from werkzeug . contrib . profiler import ProfilerMiddleware app . config [ "PROFILE" ] = True app . wsgi_app = ProfilerMiddleware ( app . wsgi_app , restrictions = [ 30 ] ) options . debug = True app . run ( debug = options . debug , host = options . host , port = int ( options . port ) )
Takes a flask . Flask instance and runs it . Parses command - line flags to configure the app .
354
22
21,172
def get_randomized_guid_sample ( self , item_count ) : dataset = self . get_whitelist ( ) random . shuffle ( dataset ) return dataset [ : item_count ]
Fetch a subset of randomzied GUIDs from the whitelist
43
14
21,173
def can_recommend ( self , client_data , extra_data = { } ) : self . logger . info ( "Curated can_recommend: {}" . format ( True ) ) return True
The Curated recommender will always be able to recommend something
44
12
21,174
def recommend ( self , client_data , limit , extra_data = { } ) : guids = self . _curated_wl . get_randomized_guid_sample ( limit ) results = [ ( guid , 1.0 ) for guid in guids ] log_data = ( client_data [ "client_id" ] , str ( guids ) ) self . logger . info ( "Curated recommendations client_id: [%s], guids: [%s]" % log_data ) return results
Curated recommendations are just random selections
112
7
21,175
def recommend ( self , client_data , limit , extra_data = { } ) : preinstalled_addon_ids = client_data . get ( "installed_addons" , [ ] ) # Compute an extended limit by adding the length of # the list of any preinstalled addons. extended_limit = limit + len ( preinstalled_addon_ids ) ensemble_suggestions = self . _ensemble_recommender . recommend ( client_data , extended_limit , extra_data ) curated_suggestions = self . _curated_recommender . recommend ( client_data , extended_limit , extra_data ) # Generate a set of results from each of the composite # recommenders. We select one item from each recommender # sequentially so that we do not bias one recommender over the # other. merged_results = set ( ) while ( len ( merged_results ) < limit and len ( ensemble_suggestions ) > 0 and len ( curated_suggestions ) > 0 ) : r1 = ensemble_suggestions . pop ( ) if r1 [ 0 ] not in [ temp [ 0 ] for temp in merged_results ] : merged_results . add ( r1 ) # Terminate early if we have an odd number for the limit if not ( len ( merged_results ) < limit and len ( ensemble_suggestions ) > 0 and len ( curated_suggestions ) > 0 ) : break r2 = curated_suggestions . pop ( ) if r2 [ 0 ] not in [ temp [ 0 ] for temp in merged_results ] : merged_results . add ( r2 ) if len ( merged_results ) < limit : msg = ( "Defaulting to empty results. Insufficient recommendations found for client: %s" % client_data [ "client_id" ] ) self . logger . info ( msg ) return [ ] sorted_results = sorted ( list ( merged_results ) , key = op . itemgetter ( 1 ) , reverse = True ) log_data = ( client_data [ "client_id" ] , str ( [ r [ 0 ] for r in sorted_results ] ) ) self . logger . info ( "Hybrid recommendations client_id: [%s], guids: [%s]" % log_data ) return sorted_results
Hybrid recommendations simply select half recommendations from the ensemble recommender and half from the curated one .
489
19
21,176
def _recommend ( self , client_data , limit , extra_data = { } ) : self . logger . info ( "Ensemble recommend invoked" ) preinstalled_addon_ids = client_data . get ( "installed_addons" , [ ] ) # Compute an extended limit by adding the length of # the list of any preinstalled addons. extended_limit = limit + len ( preinstalled_addon_ids ) flattened_results = [ ] ensemble_weights = self . _weight_cache . getWeights ( ) for rkey in self . RECOMMENDER_KEYS : recommender = self . _recommender_map [ rkey ] if recommender . can_recommend ( client_data ) : raw_results = recommender . recommend ( client_data , extended_limit , extra_data ) reweighted_results = [ ] for guid , weight in raw_results : item = ( guid , weight * ensemble_weights [ rkey ] ) reweighted_results . append ( item ) flattened_results . extend ( reweighted_results ) # Sort the results by the GUID flattened_results . sort ( key = lambda item : item [ 0 ] ) # group by the guid, sum up the weights for recurring GUID # suggestions across all recommenders guid_grouper = itertools . groupby ( flattened_results , lambda item : item [ 0 ] ) ensemble_suggestions = [ ] for ( guid , guid_group ) in guid_grouper : weight_sum = sum ( [ v for ( g , v ) in guid_group ] ) item = ( guid , weight_sum ) ensemble_suggestions . append ( item ) # Sort in reverse order (greatest weight to least) ensemble_suggestions . sort ( key = lambda x : - x [ 1 ] ) filtered_ensemble_suggestions = [ ( guid , weight ) for ( guid , weight ) in ensemble_suggestions if guid not in preinstalled_addon_ids ] results = filtered_ensemble_suggestions [ : limit ] log_data = ( client_data [ "client_id" ] , str ( ensemble_weights ) , str ( [ r [ 0 ] for r in results ] ) , ) self . logger . info ( "client_id: [%s], ensemble_weight: [%s], guids: [%s]" % log_data ) return results
Ensemble recommendations are aggregated from individual recommenders . The ensemble recommender applies a weight to the recommendation outputs of each recommender to reorder the recommendations to be a better fit .
515
37
21,177
def get ( self , transform = None ) : if not self . has_expired ( ) and self . _cached_copy is not None : return self . _cached_copy , False return self . _refresh_cache ( transform ) , True
Return the JSON defined at the S3 location in the constructor .
55
13
21,178
def hashed_download ( url , temp , digest ) : # Based on pip 1.4.1's URLOpener but with cert verification removed def opener ( ) : opener = build_opener ( HTTPSHandler ( ) ) # Strip out HTTPHandler to prevent MITM spoof: for handler in opener . handlers : if isinstance ( handler , HTTPHandler ) : opener . handlers . remove ( handler ) return opener def read_chunks ( response , chunk_size ) : while True : chunk = response . read ( chunk_size ) if not chunk : break yield chunk response = opener ( ) . open ( url ) path = join ( temp , urlparse ( url ) . path . split ( '/' ) [ - 1 ] ) actual_hash = sha256 ( ) with open ( path , 'wb' ) as file : for chunk in read_chunks ( response , 4096 ) : file . write ( chunk ) actual_hash . update ( chunk ) actual_digest = actual_hash . hexdigest ( ) if actual_digest != digest : raise HashError ( url , path , actual_digest , digest ) return path
Download url to temp make sure it has the SHA - 256 digest and return its path .
240
18
21,179
def _build_features_caches ( self ) : _donors_pool = self . _donors_pool . get ( ) [ 0 ] _lr_curves = self . _lr_curves . get ( ) [ 0 ] if _donors_pool is None or _lr_curves is None : # We need to have both donors_pool and lr_curves defined # to reconstruct the matrices return None self . num_donors = len ( _donors_pool ) # Build a numpy matrix cache for the continuous features. self . continuous_features = np . zeros ( ( self . num_donors , len ( CONTINUOUS_FEATURES ) ) ) for idx , d in enumerate ( _donors_pool ) : features = [ d . get ( specified_key ) for specified_key in CONTINUOUS_FEATURES ] self . continuous_features [ idx ] = features # Build the cache for categorical features. self . categorical_features = np . zeros ( ( self . num_donors , len ( CATEGORICAL_FEATURES ) ) , dtype = "object" ) for idx , d in enumerate ( _donors_pool ) : features = [ d . get ( specified_key ) for specified_key in CATEGORICAL_FEATURES ] self . categorical_features [ idx ] = np . array ( [ features ] , dtype = "object" ) self . logger . info ( "Reconstructed matrices for similarity recommender" )
This function build two feature cache matrices .
334
9
21,180
def recommend ( self , client_id , limit , extra_data = { } ) : if client_id in TEST_CLIENT_IDS : data = self . _whitelist_data . get ( ) [ 0 ] random . shuffle ( data ) samples = data [ : limit ] self . logger . info ( "Test ID detected [{}]" . format ( client_id ) ) return [ ( s , 1.1 ) for s in samples ] if client_id in EMPTY_TEST_CLIENT_IDS : self . logger . info ( "Empty Test ID detected [{}]" . format ( client_id ) ) return [ ] client_info = self . profile_fetcher . get ( client_id ) if client_info is None : self . logger . info ( "Defaulting to empty results. No client info fetched from dynamo." ) return [ ] results = self . _ensemble_recommender . recommend ( client_info , limit , extra_data ) return results
Return recommendations for the given client .
214
7
21,181
def get_client_profile ( self , client_id ) : try : response = self . _table . get_item ( Key = { 'client_id' : client_id } ) compressed_bytes = response [ 'Item' ] [ 'json_payload' ] . value json_byte_data = zlib . decompress ( compressed_bytes ) json_str_data = json_byte_data . decode ( 'utf8' ) return json . loads ( json_str_data ) except KeyError : # No client ID found - not really an error return None except Exception as e : # Return None on error. The caller in ProfileFetcher will # handle error logging msg = "Error loading client data for {}. Error: {}" self . logger . debug ( msg . format ( client_id , str ( e ) ) ) return None
This fetches a single client record out of DynamoDB
182
11
21,182
def clean_promoted_guids ( raw_promoted_guids ) : valid = True for row in raw_promoted_guids : if len ( row ) != 2 : valid = False break if not ( ( isinstance ( row [ 0 ] , str ) or isinstance ( row [ 0 ] , unicode ) ) and ( isinstance ( row [ 1 ] , int ) or isinstance ( row [ 1 ] , float ) ) # noqa ) : valid = False break if valid : return raw_promoted_guids return [ ]
Verify that the promoted GUIDs are formatted correctly otherwise strip it down into an empty list .
118
19
21,183
def login ( self ) : if self . __logged_in : return login = { 'userId' : self . __username , 'userPassword' : self . __password } header = BASE_HEADERS . copy ( ) request = requests . post ( BASE_URL + 'login' , data = login , headers = header , timeout = 10 ) try : result = request . json ( ) except ValueError as error : raise Exception ( "Not a valid result for login, " + "protocol error: " + request . status_code + ' - ' + request . reason + "(" + str ( error ) + ")" ) if 'error' in result . keys ( ) : raise Exception ( "Could not login: " + result [ 'error' ] ) if request . status_code != 200 : raise Exception ( "Could not login, HTTP code: " + str ( request . status_code ) + ' - ' + request . reason ) if 'success' not in result . keys ( ) or not result [ 'success' ] : raise Exception ( "Could not login, no success" ) cookie = request . headers . get ( "set-cookie" ) if cookie is None : raise Exception ( "Could not login, no cookie set" ) self . __cookie = cookie self . __logged_in = True return self . __logged_in
Login to Tahoma API .
289
6
21,184
def get_user ( self ) : header = BASE_HEADERS . copy ( ) header [ 'Cookie' ] = self . __cookie request = requests . get ( BASE_URL + 'getEndUser' , headers = header , timeout = 10 ) if request . status_code != 200 : self . __logged_in = False self . login ( ) self . get_user ( ) return try : result = request . json ( ) except ValueError : raise Exception ( "Not a valid result for getEndUser, protocol error!" ) return result [ 'endUser' ]
Get the user informations from the server .
123
9
21,185
def _get_setup ( self , result ) : self . __devices = { } if ( 'setup' not in result . keys ( ) or 'devices' not in result [ 'setup' ] . keys ( ) ) : raise Exception ( "Did not find device definition." ) for device_data in result [ 'setup' ] [ 'devices' ] : device = Device ( self , device_data ) self . __devices [ device . url ] = device self . __location = result [ 'setup' ] [ 'location' ] self . __gateway = result [ 'setup' ] [ 'gateways' ]
Internal method which process the results from the server .
131
10
21,186
def apply_actions ( self , name_of_action , actions ) : header = BASE_HEADERS . copy ( ) header [ 'Cookie' ] = self . __cookie actions_serialized = [ ] for action in actions : actions_serialized . append ( action . serialize ( ) ) data = { "label" : name_of_action , "actions" : actions_serialized } json_data = json . dumps ( data , indent = None , sort_keys = True ) request = requests . post ( BASE_URL + "apply" , headers = header , data = json_data , timeout = 10 ) if request . status_code != 200 : self . __logged_in = False self . login ( ) self . apply_actions ( name_of_action , actions ) return try : result = request . json ( ) except ValueError as error : raise Exception ( "Not a valid result for applying an " + "action, protocol error: " + request . status_code + ' - ' + request . reason + " (" + error + ")" ) if 'execId' not in result . keys ( ) : raise Exception ( "Could not run actions, missing execId." ) return result [ 'execId' ]
Start to execute an action or a group of actions .
265
11
21,187
def get_events ( self ) : header = BASE_HEADERS . copy ( ) header [ 'Cookie' ] = self . __cookie request = requests . post ( BASE_URL + 'getEvents' , headers = header , timeout = 10 ) if request . status_code != 200 : self . __logged_in = False self . login ( ) self . get_events ( ) return try : result = request . json ( ) except ValueError as error : raise Exception ( "Not a valid result for getEvent," + " protocol error: " + error ) return self . _get_events ( result )
Return a set of events .
130
6
21,188
def _get_events ( self , result ) : events = [ ] for event_data in result : event = Event . factory ( event_data ) if event is not None : events . append ( event ) if isinstance ( event , DeviceStateChangedEvent ) : # change device state if self . __devices [ event . device_url ] is None : raise Exception ( "Received device change " + "state for unknown device '" + event . device_url + "'" ) self . __devices [ event . device_url ] . set_active_states ( event . states ) return events
Internal method for being able to run unit tests .
126
10
21,189
def get_current_executions ( self ) : header = BASE_HEADERS . copy ( ) header [ 'Cookie' ] = self . __cookie request = requests . get ( BASE_URL + 'getCurrentExecutions' , headers = header , timeout = 10 ) if request . status_code != 200 : self . __logged_in = False self . login ( ) self . get_current_executions ( ) return try : result = request . json ( ) except ValueError as error : raise Exception ( "Not a valid result for" + "get_current_executions, protocol error: " + error ) if 'executions' not in result . keys ( ) : return None executions = [ ] for execution_data in result [ 'executions' ] : exe = Execution ( execution_data ) executions . append ( exe ) return executions
Get all current running executions .
183
6
21,190
def get_action_groups ( self ) : header = BASE_HEADERS . copy ( ) header [ 'Cookie' ] = self . __cookie request = requests . get ( BASE_URL + "getActionGroups" , headers = header , timeout = 10 ) if request . status_code != 200 : self . __logged_in = False self . login ( ) self . get_action_groups ( ) return try : result = request . json ( ) except ValueError : raise Exception ( "get_action_groups: Not a valid result for " ) if 'actionGroups' not in result . keys ( ) : return None groups = [ ] for group_data in result [ 'actionGroups' ] : group = ActionGroup ( group_data ) groups . append ( group ) return groups
Get all Action Groups .
171
5
21,191
def launch_action_group ( self , action_id ) : header = BASE_HEADERS . copy ( ) header [ 'Cookie' ] = self . __cookie request = requests . get ( BASE_URL + 'launchActionGroup?oid=' + action_id , headers = header , timeout = 10 ) if request . status_code != 200 : self . __logged_in = False self . login ( ) self . launch_action_group ( action_id ) return try : result = request . json ( ) except ValueError as error : raise Exception ( "Not a valid result for launch" + "action group, protocol error: " + request . status_code + ' - ' + request . reason + " (" + error + ")" ) if 'actionGroup' not in result . keys ( ) : raise Exception ( "Could not launch action" + "group, missing execId." ) return result [ 'actionGroup' ] [ 0 ] [ 'execId' ]
Start action group .
208
4
21,192
def get_states ( self , devices ) : header = BASE_HEADERS . copy ( ) header [ 'Cookie' ] = self . __cookie json_data = self . _create_get_state_request ( devices ) request = requests . post ( BASE_URL + 'getStates' , headers = header , data = json_data , timeout = 10 ) if request . status_code != 200 : self . __logged_in = False self . login ( ) self . get_states ( devices ) return try : result = request . json ( ) except ValueError as error : raise Exception ( "Not a valid result for" + "getStates, protocol error:" + error ) self . _get_states ( result )
Get States of Devices .
155
5
21,193
def _create_get_state_request ( self , given_devices ) : dev_list = [ ] if isinstance ( given_devices , list ) : devices = given_devices else : devices = [ ] for dev_name , item in self . __devices . items ( ) : if item : devices . append ( self . __devices [ dev_name ] ) for device in devices : states = [ ] for state_name in sorted ( device . active_states . keys ( ) ) : states . append ( { 'name' : state_name } ) dev_list . append ( { 'deviceURL' : device . url , 'states' : states } ) return json . dumps ( dev_list , indent = None , sort_keys = True , separators = ( ',' , ': ' ) )
Create state request .
173
4
21,194
def _get_states ( self , result ) : if 'devices' not in result . keys ( ) : return for device_states in result [ 'devices' ] : device = self . __devices [ device_states [ 'deviceURL' ] ] try : device . set_active_states ( device_states [ 'states' ] ) except KeyError : pass
Get states of devices .
77
5
21,195
def refresh_all_states ( self ) : header = BASE_HEADERS . copy ( ) header [ 'Cookie' ] = self . __cookie request = requests . get ( BASE_URL + "refreshAllStates" , headers = header , timeout = 10 ) if request . status_code != 200 : self . __logged_in = False self . login ( ) self . refresh_all_states ( ) return
Update all states .
90
4
21,196
def set_active_state ( self , name , value ) : if name not in self . __active_states . keys ( ) : raise ValueError ( "Can not set unknown state '" + name + "'" ) if ( isinstance ( self . __active_states [ name ] , int ) and isinstance ( value , str ) ) : # we get an update as str but current value is # an int, try to convert self . __active_states [ name ] = int ( value ) elif ( isinstance ( self . __active_states [ name ] , float ) and isinstance ( value , str ) ) : # we get an update as str but current value is # a float, try to convert self . __active_states [ name ] = float ( value ) else : self . __active_states [ name ] = value
Set active state .
179
4
21,197
def add_command ( self , cmd_name , * args ) : self . __commands . append ( Command ( cmd_name , args ) )
Add command to action .
32
5
21,198
def serialize ( self ) : commands = [ ] for cmd in self . commands : commands . append ( cmd . serialize ( ) ) out = { 'commands' : commands , 'deviceURL' : self . __device_url } return out
Serialize action .
53
4
21,199
def factory ( data ) : if data [ 'name' ] is "DeviceStateChangedEvent" : return DeviceStateChangedEvent ( data ) elif data [ 'name' ] is "ExecutionStateChangedEvent" : return ExecutionStateChangedEvent ( data ) elif data [ 'name' ] is "CommandExecutionStateChangedEvent" : return CommandExecutionStateChangedEvent ( data ) else : raise ValueError ( "Unknown event '" + data [ 'name' ] + "' occurred." )
Tahoma Event factory .
105
6