idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
21,200 | def plot_projections ( x , relative_to = None , autolim = True , axes = None , subplots_kwargs = dict ( ) , labels = None , plot_function = None , ** kwargs ) : x = np . array ( x , copy = True ) ndim = x . shape [ 0 ] if axes is None : axes = _get_axes ( dim = ndim , subplots_kwargs = subplots_kwargs ) if relative_to is not None : x -= relative_to plot_fn_name = plot_function . __name__ if autolim : lims = [ ] for i in range ( ndim ) : max_ , min_ = np . max ( x [ i ] ) , np . min ( x [ i ] ) delta = max_ - min_ if delta == 0. : delta = 1. lims . append ( [ min_ - delta * 0.02 , max_ + delta * 0.02 ] ) k = 0 for i in range ( ndim ) : for j in range ( ndim ) : if i >= j : continue plot_func = getattr ( axes [ k ] , plot_fn_name ) plot_func ( x [ i ] , x [ j ] , ** kwargs ) if labels is not None : axes [ k ] . set_xlabel ( labels [ i ] ) axes [ k ] . set_ylabel ( labels [ j ] ) if autolim : axes [ k ] . set_xlim ( lims [ i ] ) axes [ k ] . set_ylim ( lims [ j ] ) k += 1 axes [ 0 ] . figure . tight_layout ( ) return axes [ 0 ] . figure | Given N - dimensional quantity x make a figure containing 2D projections of all combinations of the axes . |
21,201 | def angmom ( x ) : return np . array ( [ x [ 1 ] * x [ 5 ] - x [ 2 ] * x [ 4 ] , x [ 2 ] * x [ 3 ] - x [ 0 ] * x [ 5 ] , x [ 0 ] * x [ 4 ] - x [ 1 ] * x [ 3 ] ] ) | returns angular momentum vector of phase - space point x |
21,202 | 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 |
21,203 | 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 ) ) if usys is None : usys = [ ] try : omega = potential . parameters [ 'omega' ] . reshape ( _new_omega_shape ) . decompose ( usys ) . value except AttributeError : 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 . |
21,204 | def step ( self , t , w , dt ) : 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 ] ) 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 . |
21,205 | 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 |
21,206 | 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 |
21,207 | 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 ] , [ - 1 , 1. ] , [ - 1 , 1. ] ] 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 . |
21,208 | 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 ) ) 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 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 . |
21,209 | def integrate_orbit ( self , ** time_spec ) : 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 ) 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 . |
21,210 | 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 . |
21,211 | def get_xyz ( self , xyz_axis = 0 ) : 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 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 . |
21,212 | 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 . |
21,213 | 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 . |
21,214 | 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 . |
21,215 | 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 . |
21,216 | 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." ) 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 . |
21,217 | def _plot_prepare ( self , components , units ) : if components is None : components = self . pos . components n_comps = len ( components ) if units is not None : if isinstance ( units , u . UnitBase ) : units = [ units ] * n_comps 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 = '' 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 . |
21,218 | 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 |
21,219 | 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 |
21,220 | 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 |
21,221 | 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 |
21,222 | 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 |
21,223 | 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 |
21,224 | 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 |
21,225 | 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 |
21,226 | 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 |
21,227 | 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 |
21,228 | 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 |
21,229 | 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 |
21,230 | 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 |
21,231 | 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 |
21,232 | 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 |
21,233 | 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 |
21,234 | 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 . |
21,235 | def create_team ( self , name ) : request = self . _get_request ( ) return request . post ( self . TEAM_CREATE_URL , { "name" : name } ) | Creates a new Team |
21,236 | def update_team_name ( self , name ) : request = self . _get_request ( ) return request . post ( self . TEAM_UPDATE_URL , { "name" : name } ) | Updates a Team s name |
21,237 | def destroy_team ( self ) : request = self . _get_request ( ) request . post ( url = self . TEAM_DESTROY_URL , get_json = False ) | Delete your Team |
21,238 | 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 |
21,239 | 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 |
21,240 | 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 |
21,241 | 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 |
21,242 | 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 |
21,243 | 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 . |
21,244 | 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 |
21,245 | 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 |
21,246 | def _check_required_fields ( self , fields = None , either_fields = None ) : for ( key , value ) in fields . items ( ) : 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 |
21,247 | 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_payload = HSFormat . format_file_params ( files ) file_urls_payload = HSFormat . format_file_url_params ( file_urls ) signers_payload = HSFormat . format_dict_list ( signers , 'signers' ) cc_email_addresses_payload = HSFormat . format_param_list ( cc_email_addresses , 'cc_email_addresses' ) 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 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 |
21,248 | 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_payload = HSFormat . format_dict_list ( signers , 'signers' , 'role_name' ) ccs_payload = HSFormat . format_dict_list ( ccs , 'ccs' , 'role_name' ) custom_fields_payload = HSFormat . format_custom_fields ( custom_fields ) metadata_payload = HSFormat . format_single_dict ( metadata , 'metadata' ) 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 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 |
21,249 | 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 |
21,250 | 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 |
21,251 | 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 ) } files_payload = HSFormat . format_file_params ( files ) file_urls_payload = HSFormat . format_file_url_params ( file_urls ) signer_roles_payload = HSFormat . format_dict_list ( signer_roles , 'signer_roles' ) ccs_payload = HSFormat . format_param_list ( cc_roles , 'cc_roles' ) merge_fields_payload = { 'merge_fields' : json . dumps ( merge_fields ) } 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 . |
21,252 | 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 ) : 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 ) } 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 ) 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 ) 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 . |
21,253 | 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 : 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 |
21,254 | 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 : 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 |
21,255 | 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 |
21,256 | 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 |
21,257 | 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 |
21,258 | def _check_error ( self , response , json_response = None ) : 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 ) except TypeError : raise err_cls ( "%s error: %s" % ( response . status_code , json_response [ "error_description" ] ) , response . status_code ) return True | Check for HTTP error code from the response raise exception if there s any |
21,259 | 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 |
21,260 | 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' ) ) | Builds a new HSAccessTokenAuth straight from response data |
21,261 | 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 . |
21,262 | 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 |
21,263 | 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 |
21,264 | 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 |
21,265 | 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 |
21,266 | 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 |
21,267 | def format_custom_fields ( list_of_custom_fields ) : output_payload = { } if list_of_custom_fields : 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 |
21,268 | 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 . |
21,269 | 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 . |
21,270 | 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 . |
21,271 | 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 |
21,272 | 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 |
21,273 | def flaskrun ( app , default_host = "127.0.0.1" , default_port = "8000" ) : 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 , ) 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 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 . |
21,274 | 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 |
21,275 | 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 |
21,276 | 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 |
21,277 | def recommend ( self , client_data , limit , extra_data = { } ) : preinstalled_addon_ids = client_data . get ( "installed_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 ) 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 ) 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 . |
21,278 | def _recommend ( self , client_data , limit , extra_data = { } ) : self . logger . info ( "Ensemble recommend invoked" ) preinstalled_addon_ids = client_data . get ( "installed_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 ) flattened_results . sort ( key = lambda item : item [ 0 ] ) 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 ) 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 . |
21,279 | 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 . |
21,280 | def hashed_download ( url , temp , digest ) : def opener ( ) : opener = build_opener ( HTTPSHandler ( ) ) 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 . |
21,281 | 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 : return None self . num_donors = len ( _donors_pool ) 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 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 . |
21,282 | 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 . |
21,283 | 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 : return None except Exception as e : 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 |
21,284 | 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 ) ) ) : 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 . |
21,285 | 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 . |
21,286 | 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 . |
21,287 | 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 . |
21,288 | 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 . |
21,289 | 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 . |
21,290 | 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 ) : 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 . |
21,291 | 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 . |
21,292 | 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 . |
21,293 | 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 . |
21,294 | 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 . |
21,295 | 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 . |
21,296 | 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 . |
21,297 | 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 . |
21,298 | 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 ) ) : self . __active_states [ name ] = int ( value ) elif ( isinstance ( self . __active_states [ name ] , float ) and isinstance ( value , str ) ) : self . __active_states [ name ] = float ( value ) else : self . __active_states [ name ] = value | Set active state . |
21,299 | def add_command ( self , cmd_name , * args ) : self . __commands . append ( Command ( cmd_name , args ) ) | Add command to action . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.