signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def editorial_reviews ( self ) : """Editorial Review . Returns a list of all editorial reviews . : return : A list containing : Editorial Review ( string )"""
result = [ ] reviews_node = self . _safe_get_element ( 'EditorialReviews' ) if reviews_node is not None : for review_node in reviews_node . iterchildren ( ) : content_node = getattr ( review_node , 'Content' ) if content_node is not None : result . append ( content_node . text ) return r...
def associate_address ( self , instance_id , public_ip = None , allocation_id = None ) : """Associate an Elastic IP address with a currently running instance . This requires one of ` ` public _ ip ` ` or ` ` allocation _ id ` ` depending on if you ' re associating a VPC address or a plain EC2 address . : type...
params = { 'InstanceId' : instance_id } if public_ip is not None : params [ 'PublicIp' ] = public_ip elif allocation_id is not None : params [ 'AllocationId' ] = allocation_id return self . get_status ( 'AssociateAddress' , params , verb = 'POST' )
def schedule_forced_svc_check ( self , service , check_time ) : """Schedule a forced check on a service Format of the line that triggers function call : : SCHEDULE _ FORCED _ SVC _ CHECK ; < host _ name > ; < service _ description > ; < check _ time > : param service : service to check : type service : alig...
service . schedule ( self . daemon . hosts , self . daemon . services , self . daemon . timeperiods , self . daemon . macromodulations , self . daemon . checkmodulations , self . daemon . checks , force = True , force_time = check_time ) self . send_an_element ( service . get_update_status_brok ( ) )
def _sigma_2 ( gam , eps ) : """gam and eps in units of m _ e c ^ 2 Eq . A3 of Baring et al . ( 1999) Return in units of cm2 / mec2"""
s0 = r0 ** 2 * alpha / ( 3 * eps ) / mec2_unit s1_1 = 16 * ( 1 - eps + eps ** 2 ) * np . log ( gam / eps ) s1_2 = - 1 / eps ** 2 + 3 / eps - 4 - 4 * eps - 8 * eps ** 2 s1_3 = - 2 * ( 1 - 2 * eps ) * np . log ( 1 - 2 * eps ) s1_4 = 1 / ( 4 * eps ** 3 ) - 1 / ( 2 * eps ** 2 ) + 3 / eps - 2 + 4 * eps s1 = s1_1 + s1_2 + s1...
def _bn ( editor , force = False ) : """Go to next buffer ."""
eb = editor . window_arrangement . active_editor_buffer if not force and eb . has_unsaved_changes : editor . show_message ( _NO_WRITE_SINCE_LAST_CHANGE_TEXT ) else : editor . window_arrangement . go_to_next_buffer ( )
def interpreter ( self ) : """Launch an AML interpreter session for testing"""
while True : message = input ( '[#] ' ) if message . lower ( ) . strip ( ) == 'exit' : break reply = self . get_reply ( '#interpreter#' , message ) if not reply : print ( 'No reply received.' , end = '\n\n' ) continue # typewrite ( reply , end = ' \ n \ n ' ) TODO print (...
def _maybe_strip_extension ( number ) : """Strip extension from the end of a number string . Strips any extension ( as in , the part of the number dialled after the call is connected , usually indicated with extn , ext , x or similar ) from the end of the number , and returns it . Arguments : number - - t...
match = _EXTN_PATTERN . search ( number ) # If we find a potential extension , and the number preceding this is a # viable number , we assume it is an extension . if match and _is_viable_phone_number ( number [ : match . start ( ) ] ) : # The numbers are captured into groups in the regular expression . for group in...
def get_hw_platform ( self , udi ) : """Return th HW platform information from the device ."""
platform = None try : pid = udi [ 'pid' ] if pid == '' : self . log ( "Empty PID. Use the hw family from the platform string." ) return self . raw_family match = re . search ( self . pid2platform_re , pid ) if match : platform = match . group ( 1 ) except KeyError : pass retu...
def render_source ( output_dir , package_spec ) : """Render and output to a directory given a package specification ."""
path , name = package_spec . filepath destination_filename = "%s/%s.h" % ( output_dir , name ) py_template = JENV . get_template ( MESSAGES_TEMPLATE_NAME ) with open ( destination_filename , 'w' ) as f : f . write ( py_template . render ( msgs = package_spec . definitions , pkg_name = name , filepath = "/" . join (...
def init_console_logging ( conf ) : """Log to console ."""
# define a Handler which writes messages to the sys . stderr console = find_console_handler ( logging . getLogger ( ) ) if not console : console = logging . StreamHandler ( ) logging_level = log_level ( conf ) console . setLevel ( logging_level ) # set a format which is simpler for console use formatter = _get_debu...
def verify_pop ( pop : ProofOfPossession , ver_key : VerKey , gen : Generator ) -> bool : """Verifies the proof of possession and returns true - if signature valid or false otherwise . : param : pop - Proof of possession : param : ver _ key - Verification key : param : gen - Generator point : return : true ...
logger = logging . getLogger ( __name__ ) logger . debug ( "Bls::verify_pop: >>> pop: %r, ver_key: %r, gen: %r" , pop , ver_key , gen ) valid = c_bool ( ) do_call ( 'indy_crypto_bsl_verify_pop' , pop . c_instance , ver_key . c_instance , gen . c_instance , byref ( valid ) ) res = valid logger . debug ( "Bls::verify_pop...
def _evaluate_rhs ( cls , funcs , nodes , problem ) : """Compute the value of the right - hand side of the system of ODEs . Parameters basis _ funcs : list ( function ) nodes : numpy . ndarray problem : TwoPointBVPLike Returns evaluated _ rhs : list ( float )"""
evald_funcs = cls . _evaluate_functions ( funcs , nodes ) evald_rhs = problem . rhs ( nodes , * evald_funcs , ** problem . params ) return evald_rhs
def isin_alone ( elems , line ) : """Check if an element from a list is the only element of a string . : type elems : list : type line : str"""
found = False for e in elems : if line . strip ( ) . lower ( ) == e . lower ( ) : found = True break return found
def run ( self ) : """Runs until stopEvent is notified , and notify observers of all reader insertion / removal ."""
while not self . stopEvent . isSet ( ) : try : # no need to monitor if no observers if 0 < self . observable . countObservers ( ) : currentReaders = self . readerProc ( ) addedReaders = [ ] removedReaders = [ ] if currentReaders != self . readers : ...
def toggle_freq ( self ) : """Enable and disable frequency domain options ."""
freq = self . frequency export_full_on = freq [ 'export_full' ] . get_value ( ) export_band_on = freq [ 'export_band' ] . get_value ( ) freq_on = asarray ( [ export_full_on , export_band_on , freq [ 'plot_on' ] . get_value ( ) , freq [ 'fooof_on' ] . get_value ( ) ] ) . any ( ) freq [ 'box_param' ] . setEnabled ( freq_...
def plot_free_energy ( xall , yall , weights = None , ax = None , nbins = 100 , ncontours = 100 , offset = - 1 , avoid_zero_count = False , minener_zero = True , kT = 1.0 , vmin = None , vmax = None , cmap = 'nipy_spectral' , cbar = True , cbar_label = 'free energy / kT' , cax = None , levels = None , legacy = True , n...
if legacy : _warn ( 'Legacy mode is deprecated is will be removed in the' ' next major release. Until then use legacy=False' , DeprecationWarning ) cmap = _get_cmap ( cmap ) if offset != - 1 : _warn ( 'Parameter offset is deprecated and will be ignored' , DeprecationWarning ) if ncountours is no...
def hexagonal ( a : float , c : float ) : """Convenience constructor for a hexagonal lattice . Args : a ( float ) : * a * lattice parameter of the hexagonal cell . c ( float ) : * c * lattice parameter of the hexagonal cell . Returns : Hexagonal lattice of dimensions a x a x c ."""
return Lattice . from_parameters ( a , a , c , 90 , 90 , 120 )
def value ( self , units = None ) : """Return the pressure in the specified units ."""
if units is None : return self . _value if not units . upper ( ) in CustomPressure . legal_units : raise UnitsError ( "unrecognized pressure unit: '" + units + "'" ) units = units . upper ( ) if units == self . _units : return self . _value if self . _units == "IN" : mb_value = self . _value * 33.86398 ...
def cmd_serial ( self , args ) : '''serial control commands'''
usage = "Usage: serial <lock|unlock|set|send>" if len ( args ) < 1 : print ( usage ) return if args [ 0 ] == "lock" : self . serial_lock ( True ) elif args [ 0 ] == "unlock" : self . serial_lock ( False ) elif args [ 0 ] == "set" : self . serial_settings . command ( args [ 1 : ] ) elif args [ 0 ] ==...
def client_unenroll ( self , client ) : """Unenroll a client . Uses DELETE to / clients / < client > interface . : Args : * * client * : ( str ) Client ' s ID"""
client = self . _client_id ( client ) response = self . _delete ( url . clients_id . format ( id = client ) ) self . _check_response ( response , 204 )
def V_horiz_conical ( D , L , a , h , headonly = False ) : r'''Calculates volume of a tank with conical ends , according to [ 1 ] _ . . . math : : V _ f = A _ fL + \ frac { 2aR ^ 2 } { 3 } K , \ ; \ ; 0 \ le h < R \ \ . . math : : V _ f = A _ fL + \ frac { 2aR ^ 2 } { 3 } \ pi / 2 , \ ; \ ; h = R \ \ . . ...
R = D / 2. Af = R * R * acos ( ( R - h ) / R ) - ( R - h ) * ( 2 * R * h - h * h ) ** 0.5 M = abs ( ( R - h ) / R ) if h == R : Vf = a * R * R / 3. * pi else : K = acos ( M ) + M * M * M * acosh ( 1. / M ) - 2. * M * ( 1. - M * M ) ** 0.5 if 0. <= h < R : Vf = 2. * a * R * R / 3 * K elif R < h <...
def from_git ( self , path = None , prefer_daily = False ) : """Use Git to determine the package version . This routine uses the _ _ file _ _ value of the caller to determine which Git repository root to use ."""
if self . _version is None : frame = caller ( 1 ) path = frame . f_globals . get ( '__file__' ) or '.' providers = ( [ git_day , git_version ] if prefer_daily else [ git_version , git_day ] ) for provider in providers : if self . _version is not None : break try : ...
def parse_form_request ( api_secret , request ) : """> > > parse _ form _ request ( " 123456 " , { " nonce " : 1451122677 , " msg " : " helllo " , " code " : 0 , " sign " : " DB30F4D1112C20DFA736F65458F89C64 " } ) < Storage { ' nonce ' : 1451122677 , ' msg ' : ' helllo ' , ' code ' : 0 , ' sign ' : ' DB30F4D1112C...
if not check_sign ( api_secret , request ) : raise SignError ( u"message sign error" ) return Storage ( request )
def getClassPath ( ) : """Get the full java class path . Includes user added paths and the environment CLASSPATH ."""
global _CLASSPATHS global _SEP out = [ ] for path in _CLASSPATHS : if path == '' : continue if path . endswith ( '*' ) : paths = _glob . glob ( path + ".jar" ) if len ( path ) == 0 : continue out . extend ( paths ) else : out . append ( path ) return _SEP ...
def _crossProduct ( self , ls ) : """Internal method to generate the cross product of all parameter values , creating the parameter space for the experiment . : param ls : an array of parameter names : returns : list of dicts"""
p = ls [ 0 ] ds = [ ] if len ( ls ) == 1 : # last parameter , convert range to a dict for i in self . _parameters [ p ] : dp = dict ( ) dp [ p ] = i ds . append ( dp ) else : # for other parameters , create a dict combining each value in # the range to a copy of the dict of other parameters ...
def _get_notmuch_thread ( self , tid ) : """returns : class : ` notmuch . database . Thread ` with given id"""
query = self . query ( 'thread:' + tid ) try : return next ( query . search_threads ( ) ) except StopIteration : errmsg = 'no thread with id %s exists!' % tid raise NonexistantObjectError ( errmsg )
def divides ( self ) : """List of indices of divisions between the constituent chunks ."""
acc = [ 0 ] for s in self . chunks : acc . append ( acc [ - 1 ] + len ( s ) ) return acc
def list_books ( self ) : '''Return the list of book names'''
names = [ ] try : for n in self . cur . execute ( "SELECT name FROM book;" ) . fetchall ( ) : names . extend ( n ) except : self . error ( "ERROR: cannot find database table 'book'" ) return ( names )
def restart ( self , key ) : """Restart a previously finished entry ."""
if key in self . queue : if self . queue [ key ] [ 'status' ] in [ 'failed' , 'done' ] : new_entry = { 'command' : self . queue [ key ] [ 'command' ] , 'path' : self . queue [ key ] [ 'path' ] } self . add_new ( new_entry ) self . write ( ) return True return False
def update_template_component ( component , custom_template_dir = None , hazard = None , exposure = None ) : """Get a component based on custom qpt if exists : param component : Component as dictionary . : type component : dict : param custom _ template _ dir : The directory where the custom template stored ....
copy_component = deepcopy ( component ) # get the default template component from the original map report component default_component_keys = [ ] for component in copy_component [ 'components' ] : default_component_keys . append ( component [ 'key' ] ) if not custom_template_dir : # noinspection PyArgumentList c...
def ConsultarTiposCategoriaEmisor ( self , sep = "||" ) : "Obtener el código y descripción para tipos de categorías de emisor"
ret = self . client . consultarTiposCategoriaEmisor ( authRequest = { 'token' : self . Token , 'sign' : self . Sign , 'cuitRepresentada' : self . Cuit , } , ) [ 'consultarCategoriasEmisorReturn' ] self . __analizar_errores ( ret ) array = ret . get ( 'arrayCategoriasEmisor' , [ ] ) lista = [ it [ 'codigoDescripcionStri...
def transformer_ffn_layer ( x , hparams , pad_remover = None , conv_padding = "LEFT" , nonpadding_mask = None , losses = None , cache = None , decode_loop_step = None , readout_filter_size = 0 , layer_collection = None ) : """Feed - forward layer in the transformer . Args : x : a Tensor of shape [ batch _ size ...
ffn_layer = hparams . ffn_layer relu_dropout_broadcast_dims = ( common_layers . comma_separated_string_to_integer_list ( getattr ( hparams , "relu_dropout_broadcast_dims" , "" ) ) ) if ffn_layer == "conv_hidden_relu" : # Backwards compatibility ffn_layer = "dense_relu_dense" if ffn_layer == "dense_relu_dense" : # I...
def mode_mapping_bynumber ( mav_type ) : '''return dictionary mapping mode numbers to name , or None if unknown'''
map = None if mav_type in [ mavlink . MAV_TYPE_QUADROTOR , mavlink . MAV_TYPE_HELICOPTER , mavlink . MAV_TYPE_HEXAROTOR , mavlink . MAV_TYPE_OCTOROTOR , mavlink . MAV_TYPE_COAXIAL , mavlink . MAV_TYPE_TRICOPTER ] : map = mode_mapping_acm if mav_type == mavlink . MAV_TYPE_FIXED_WING : map = mode_mapping_apm if m...
def calculate_sources ( self , targets ) : """Generate a set of source files from the given targets ."""
sources = set ( ) for target in targets : sources . update ( source for source in target . sources_relative_to_buildroot ( ) if source . endswith ( self . _PYTHON_SOURCE_EXTENSION ) ) return sources
def manifold_embedding ( X , y = None , ax = None , manifold = "lle" , n_neighbors = 10 , colors = None , target = AUTO , alpha = 0.7 , random_state = None , ** kwargs ) : """Quick method for Manifold visualizer . The Manifold visualizer provides high dimensional visualization for feature analysis by embedding ...
# Instantiate the visualizer viz = Manifold ( ax = ax , manifold = manifold , n_neighbors = n_neighbors , colors = colors , target = target , alpha = alpha , random_state = random_state , ** kwargs ) # Fit and poof ( calls draw ) viz . fit ( X , y ) viz . poof ( ) # Return the axes object return viz . ax
def reduce_fit ( interface , state , label , inp ) : """Function joins all partially calculated matrices ETE and ETDe , aggregates them and it calculates final parameters ."""
import numpy as np out = interface . output ( 0 ) sum_etde = 0 sum_ete = [ 0 for _ in range ( len ( state [ "X_indices" ] ) + 1 ) ] for key , value in inp : if key == "etde" : sum_etde += value else : sum_ete [ key ] += value sum_ete += np . true_divide ( np . eye ( len ( sum_ete ) ) , state [ "...
def set_value ( self , value , addr , size , offset , ** kwargs ) : '''Writing a value of any arbitrary size ( max . unsigned int 64 ) and offset to a register Parameters value : int , str The register value ( int , long , bit string ) to be written . addr : int The register address . size : int Bit s...
div_offset , mod_offset = divmod ( offset , 8 ) div_size , mod_size = divmod ( size + mod_offset , 8 ) if mod_size : div_size += 1 if mod_offset == 0 and mod_size == 0 : reg = BitLogic . from_value ( 0 , size = div_size * 8 ) else : ret = self . _intf . read ( self . _base_addr + addr + div_offset , size = ...
def pp_file_to_dataframe ( pp_filename ) : """read a pilot point file to a pandas Dataframe Parameters pp _ filename : str pilot point file Returns df : pandas . DataFrame a dataframe with pp _ utils . PP _ NAMES for columns"""
df = pd . read_csv ( pp_filename , delim_whitespace = True , header = None , names = PP_NAMES , usecols = [ 0 , 1 , 2 , 3 , 4 ] ) df . loc [ : , "name" ] = df . name . apply ( str ) . apply ( str . lower ) return df
def clazz ( clazz , parent_clazz , description , link , params_string , init_super_args = None ) : """Live template for pycharm : y = clazz ( clazz = " $ clazz $ " , parent _ clazz = " % parent $ " , description = " $ description $ " , link = " $ lnk $ " , params _ string = " $ first _ param $ " )"""
variables_needed = [ ] variables_optional = [ ] imports = set ( ) for param in params_string . split ( "\n" ) : variable = parse_param_types ( param ) # any variable . types has always _ is _ value = > lenght must be 1. assert ( not any ( [ type_ . always_is_value is not None for type_ in variable . types ]...
def transpose ( self ) -> 'AnnData' : """Transpose whole object . Data matrix is transposed , observations and variables are interchanged ."""
if not self . isbacked : X = self . _X else : X = self . file [ 'X' ] if self . isview : raise ValueError ( 'You\'re trying to transpose a view of an `AnnData`, which is currently not implemented. ' 'Call `.copy()` before transposing.' ) layers = { k : ( v . T . tocsr ( ) if sparse . isspmatrix_csr ( v ) el...
def load ( self , data_dir , tf_input_var = None , tf_predict_var = None ) : """Load graph and weight data . Args : data _ dir ( : obj : ` str ` ) : location of tensorflow checkpoint data . We ' ll need the . meta file to reconstruct the graph and the data ( checkpoint ) files to fill in the weights of the ...
# find newest ckpt and meta files try : latest_ckpt_fn = max ( filter ( # exclude index and meta files which may have earlier # timestamps lambda x : os . path . splitext ( x ) [ - 1 ] . startswith ( '.meta' ) or os . path . splitext ( x ) [ - 1 ] . startswith ( '.index' ) , glob . glob ( os . path . join (...
def parse_list ( cls , data ) : """Parse a list of JSON objects into a result set of model instances ."""
results = ResultSet ( ) data = data or [ ] for obj in data : if obj : results . append ( cls . parse ( obj ) ) return results
def parse_date ( val , zone = 'default' ) : val = parse_isodate ( val , None ) '''date has no ISO zone information'''
if not val . tzinfo : val = timezone [ zone ] . localize ( val ) return val
def _handle_successor ( self , job , successor , successors ) : """Returns a new CFGJob instance for further analysis , or None if there is no immediate state to perform the analysis on . : param CFGJob job : The current job ."""
state = successor all_successor_states = successors addr = job . addr # The PathWrapper instance to return pw = None job . successor_status [ state ] = "" new_state = state . copy ( ) suc_jumpkind = state . history . jumpkind suc_exit_stmt_idx = state . scratch . exit_stmt_idx suc_exit_ins_addr = state . scratch . exit...
def record_timestamp ( pathname_full ) : """Record the timestamp of running in a dotfile ."""
if Settings . test or Settings . list_only or not Settings . record_timestamp : return if not Settings . follow_symlinks and os . path . islink ( pathname_full ) : if Settings . verbose : print ( 'Not setting timestamp because not following symlinks' ) return if not os . path . isdir ( pathname_full...
def get_point_from_bins_and_idx ( self , chi1_bin , chi2_bin , idx ) : """Find masses and spins given bin numbers and index . Given the chi1 bin , chi2 bin and an index , return the masses and spins of the point at that index . Will fail if no point exists there . Parameters chi1 _ bin : int The bin numbe...
mass1 = self . massbank [ chi1_bin ] [ chi2_bin ] [ 'mass1s' ] [ idx ] mass2 = self . massbank [ chi1_bin ] [ chi2_bin ] [ 'mass2s' ] [ idx ] spin1z = self . massbank [ chi1_bin ] [ chi2_bin ] [ 'spin1s' ] [ idx ] spin2z = self . massbank [ chi1_bin ] [ chi2_bin ] [ 'spin2s' ] [ idx ] return mass1 , mass2 , spin1z , sp...
def _displayFeatures ( self , fig , features , minX , maxX , offsetAdjuster ) : """Add the given C { features } to the figure in C { fig } . @ param fig : A matplotlib figure . @ param features : A C { FeatureList } instance . @ param minX : The smallest x coordinate . @ param maxX : The largest x coordinat...
frame = None labels = [ ] for feature in features : start = offsetAdjuster ( feature . start ) end = offsetAdjuster ( feature . end ) if feature . subfeature : subfeatureFrame = start % 3 if subfeatureFrame == frame : # Move overlapping subfeatures down a little to make them # visibl...
def solve_recaptcha ( self , google_key , page_url , timeout = 15 * 60 ) : '''Solve a recaptcha on page ` page _ url ` with the input value ` google _ key ` . Timeout is ` timeout ` seconds , defaulting to 60 seconds . Return value is either the ` g - recaptcha - response ` value , or an exceptionj is raised ...
proxy = SocksProxy . ProxyLauncher ( [ TWOCAPTCHA_IP ] ) try : captcha_id = self . doGet ( 'input' , { 'key' : self . api_key , 'method' : "userrecaptcha" , 'googlekey' : google_key , 'pageurl' : page_url , 'proxy' : proxy . get_wan_address ( ) , 'proxytype' : "SOCKS5" , 'json' : True , } ) # Allow 15 minutes f...
def create_post_history ( raw_data ) : '''Create the history of certain post .'''
uid = tools . get_uuid ( ) TabPostHist . create ( uid = uid , title = raw_data . title , post_id = raw_data . uid , user_name = raw_data . user_name , cnt_md = raw_data . cnt_md , time_update = tools . timestamp ( ) , logo = raw_data . logo , ) return True
def get_online_date ( self , ** kwargs ) : """Get the online date from the meta creation date ."""
qualifier = kwargs . get ( 'qualifier' , '' ) content = kwargs . get ( 'content' , '' ) # Handle meta - creation - date element . if qualifier == 'metadataCreationDate' : date_match = META_CREATION_DATE_REGEX . match ( content ) ( year , month , day ) = date_match . groups ( '' ) # Create the date . cre...
def _load_cdll ( name ) : """Helper function to load a shared library built during installation with ctypes . : type name : str : param name : Name of the library to load ( e . g . ' mseed ' ) . : rtype : : class : ` ctypes . CDLL `"""
# our custom defined part of the extension file name libname = _get_lib_name ( name ) libdir = os . path . join ( os . path . dirname ( __file__ ) , 'lib' ) libpath = os . path . join ( libdir , libname ) static_fftw = os . path . join ( libdir , 'libfftw3-3.dll' ) static_fftwf = os . path . join ( libdir , 'libfftw3f-...
def withdraw ( self , account_id , ** params ) : """https : / / developers . coinbase . com / api / v2 # withdraw - funds"""
for required in [ 'payment_method' , 'amount' , 'currency' ] : if required not in params : raise ValueError ( "Missing required parameter: %s" % required ) response = self . _post ( 'v2' , 'accounts' , account_id , 'withdrawals' , data = params ) return self . _make_api_object ( response , Withdrawal )
def plot ( self , * args , ** kwargs ) : """NAME : plot PURPOSE : plot the angles vs . each other , to check whether the isochrone approximation is good INPUT : Either : a ) R , vR , vT , z , vz : floats : phase - space value for single object b ) Orbit instance type = ( ' araz ' ) type of plot ...
# Kwargs type = kwargs . pop ( 'type' , 'araz' ) deperiod = kwargs . pop ( 'deperiod' , False ) downsample = kwargs . pop ( 'downsample' , False ) # Parse input R , vR , vT , z , vz , phi = self . _parse_args ( 'a' in type , False , * args ) # Use self . _ aAI to calculate the actions and angles in the isochrone potent...
def canClose ( self ) : """Checks to see if the view widget can close by checking all of its sub - views to make sure they ' re ok to close . : return < bool >"""
for view in self . findChildren ( XView ) : if not view . canClose ( ) : return False return True
def convert_effsize ( ef , input_type , output_type , nx = None , ny = None ) : """Conversion between effect sizes . Parameters ef : float Original effect size input _ type : string Effect size type of ef . Must be ' r ' or ' d ' . output _ type : string Desired effect size type . Available methods ...
it = input_type . lower ( ) ot = output_type . lower ( ) # Check input and output type for input in [ it , ot ] : if not _check_eftype ( input ) : err = "Could not interpret input '{}'" . format ( input ) raise ValueError ( err ) if it not in [ 'r' , 'cohen' ] : raise ValueError ( "Input type mu...
def compute_gradient ( self ) : """Compute the gradient of the current model using the training set"""
delta = self . predict ( self . X ) - self . y return delta . dot ( self . X ) / len ( self . X )
def validate_args ( args ) : """Basic option validation . Returns False if the options are not valid , True otherwise . : param args : the command line options : type args : map : param brokers _ num : the number of brokers"""
if not args . minutes and not args . start_time : print ( "Error: missing --minutes or --start-time" ) return False if args . minutes and args . start_time : print ( "Error: --minutes shouldn't be specified if --start-time is used" ) return False if args . end_time and not args . start_time : print ...
def module_imports_on_top_of_file ( logical_line , indent_level , checker_state , noqa ) : r"""Place imports at the top of the file . Always put imports at the top of the file , just after any module comments and docstrings , and before module globals and constants . Okay : import os Okay : # this is a comm...
def is_string_literal ( line ) : if line [ 0 ] in 'uUbB' : line = line [ 1 : ] if line and line [ 0 ] in 'rR' : line = line [ 1 : ] return line and ( line [ 0 ] == '"' or line [ 0 ] == "'" ) allowed_try_keywords = ( 'try' , 'except' , 'else' , 'finally' ) if indent_level : # Allow imports in...
def DEBUG_ON_RESPONSE ( self , statusCode , responseHeader , data ) : '''Update current frame with response Current frame index will be attached to responseHeader'''
if self . DEBUG_FLAG : # pragma no branch ( Flag always set in tests ) self . _frameBuffer [ self . _frameCount ] [ 1 : 4 ] = [ statusCode , responseHeader , data ] responseHeader [ self . DEBUG_HEADER_KEY ] = self . _frameCount
def upgrade ( * pkgs ) : '''Runs an update operation on the specified packages , or all packages if none is specified . : type pkgs : list ( str ) : param pkgs : List of packages to update : return : The upgraded packages . Example element : ` ` [ ' libxslt - 1.1.0 ' , ' libxslt - 1.1.10 ' ] ` ` : rtype :...
cmd = _quietnix ( ) cmd . append ( '--upgrade' ) cmd . extend ( pkgs ) out = _run ( cmd ) upgrades = [ _format_upgrade ( s . split ( maxsplit = 1 ) [ 1 ] ) for s in out [ 'stderr' ] . splitlines ( ) if s . startswith ( 'upgrading' ) ] return [ [ _strip_quotes ( s_ ) for s_ in s ] for s in upgrades ]
def _backtick_columns ( cols ) : """Quote the column names"""
def bt ( s ) : b = '' if s == '*' or not s else '`' return [ _ for _ in [ b + ( s or '' ) + b ] if _ ] formatted = [ ] for c in cols : if c [ 0 ] == '#' : formatted . append ( c [ 1 : ] ) elif c . startswith ( '(' ) and c . endswith ( ')' ) : # WHERE ( column _ a , column _ b ) IN ( ( 1,10 ) , (...
def ensure_clean ( self ) : """Make sure the working tree is clean ( contains no changes to tracked files ) . : raises : : exc : ` ~ vcs _ repo _ mgr . exceptions . WorkingTreeNotCleanError ` when the working tree contains changes to tracked files ."""
if not self . is_clean : raise WorkingTreeNotCleanError ( compact ( """ The repository's local working tree ({local}) contains changes to tracked files! """ , local = format_path ( self . local ) ) )
def enu_to_ecef_vector ( east , north , up , glat , glong ) : """Converts vector from East , North , Up components to ECEF Position of vector in geospace may be specified in either geocentric or geodetic coordinates , with corresponding expression of the vector using radial or ellipsoidal unit vectors . Par...
# convert lat and lon in degrees to radians rlat = np . radians ( glat ) rlon = np . radians ( glong ) x = - east * np . sin ( rlon ) - north * np . cos ( rlon ) * np . sin ( rlat ) + up * np . cos ( rlon ) * np . cos ( rlat ) y = east * np . cos ( rlon ) - north * np . sin ( rlon ) * np . sin ( rlat ) + up * np . sin ...
def preprocess_for_eval ( image , image_size = 224 , normalize = True ) : """Preprocesses the given image for evaluation . Args : image : ` Tensor ` representing an image of arbitrary size . image _ size : int , how large the output image should be . normalize : bool , if True the image is normalized . Re...
if normalize : image = tf . to_float ( image ) / 255.0 image = _do_scale ( image , image_size + 32 ) if normalize : image = _normalize ( image ) image = _center_crop ( image , image_size ) image = tf . reshape ( image , [ image_size , image_size , 3 ] ) return image
def merge_pot1_files ( self , delete_source = True ) : """This method is called when all the q - points have been computed . It runs ` mrgdvdb ` in sequential on the local machine to produce the final DVDB file in the outdir of the ` Work ` . Args : delete _ source : True if POT1 files should be removed aft...
natom = len ( self [ 0 ] . input . structure ) max_pertcase = 3 * natom pot1_files = [ ] for task in self : if not isinstance ( task , DfptTask ) : continue paths = task . outdir . list_filepaths ( wildcard = "*_POT*" ) for path in paths : # Include only atomic perturbations i . e . files whose ext ...
def add_option ( self , value , text , selected = False ) : """Add option to select : param value : The value that the option represent . : param text : The text that should be displayer in dropdown : param selected : True if the option should be the default value ."""
option = { "value" : value , "text" : text , "selected" : selected } self . options += [ option ] if selected : self . selected_options += [ option ] self . _value . append ( value ) if self . _persist_value : self . settings . store_value ( "selected_options" , self . selected_options )
def mat2d_window_from_indices ( mat , row_indices = None , col_indices = None , copy = False ) : """Select an area / " window " inside of a 2D array / matrix ` mat ` specified by either a sequence of row indices ` row _ indices ` and / or a sequence of column indices ` col _ indices ` . Returns the specified ar...
if not isinstance ( mat , np . ndarray ) or mat . ndim != 2 : raise ValueError ( '`mat` must be a 2D NumPy array' ) if mat . shape [ 0 ] == 0 or mat . shape [ 1 ] == 0 : raise ValueError ( 'invalid shape for `mat`: %s' % mat . shape ) if row_indices is None : row_indices = slice ( None ) # a " : " slice...
def metadata ( self ) : """Retrieves the remote database metadata dictionary . : returns : Dictionary containing database metadata details"""
resp = self . r_session . get ( self . database_url ) resp . raise_for_status ( ) return response_to_json_dict ( resp )
def ToABMag ( self , wave , flux , ** kwargs ) : """Convert to ` ` abmag ` ` . . . math : : \\ textnormal { AB } _ { \\ nu } = - 2.5 \\ ; \\ log ( h \\ lambda \\ ; \\ textnormal { photlam } ) - 48.6 where : math : ` h ` is as defined in : ref : ` pysynphot - constants ` . Parameters wave , flux : number o...
arg = H * flux * wave return - 1.085736 * N . log ( arg ) + ABZERO
def p_route ( self , p ) : """route : ROUTE route _ name route _ version route _ io route _ deprecation NL INDENT docsection attrssection DEDENT | ROUTE route _ name route _ version route _ io route _ deprecation NL"""
p [ 0 ] = AstRouteDef ( self . path , p . lineno ( 1 ) , p . lexpos ( 1 ) , p [ 2 ] , p [ 3 ] , p [ 5 ] , * p [ 4 ] ) if len ( p ) > 7 : p [ 0 ] . set_doc ( p [ 8 ] ) if p [ 9 ] : keys = set ( ) for attr in p [ 9 ] : if attr . name in keys : msg = "Attribute '%s' defi...
def _handle_ticker ( self , ts , chan_id , data ) : """Adds received ticker data to self . tickers dict , filed under its channel id . : param ts : timestamp , declares when data was received by the client : param chan _ id : int , channel id : param data : tuple or list of data received via wss : return ...
pair = self . channel_labels [ chan_id ] [ 1 ] [ 'pair' ] entry = ( * data , ts ) self . data_q . put ( ( 'ticker' , pair , entry ) )
def _get_last_modification_date ( url ) : """Get the last modification date of the ontology ."""
request = requests . head ( url ) date_string = request . headers [ "last-modified" ] parsed = time . strptime ( date_string , "%a, %d %b %Y %H:%M:%S %Z" ) return datetime ( * ( parsed ) [ 0 : 6 ] )
def gen ( self , init_state = None ) : """Starting either with a naive BEGIN state , or the provided ` init _ state ` ( as a tuple ) , return a generator that will yield successive items until the chain reaches the END state ."""
state = init_state or ( BEGIN , ) * self . state_size while True : next_word = self . move ( state ) if next_word == END : break yield next_word state = tuple ( state [ 1 : ] ) + ( next_word , )
def clean ( self ) : """Validate that the submited : attr : ` username ` and : attr : ` password ` are valid : raises django . forms . ValidationError : if the : attr : ` username ` and : attr : ` password ` are not valid . : return : The cleaned POST data : rtype : dict"""
cleaned_data = super ( UserCredential , self ) . clean ( ) if "username" in cleaned_data and "password" in cleaned_data : auth = utils . import_attr ( settings . CAS_AUTH_CLASS ) ( cleaned_data [ "username" ] ) if auth . test_password ( cleaned_data [ "password" ] ) : cleaned_data [ "username" ] = auth ...
def first_key ( res ) : """Returns the first result for the given command . If more then 1 result is returned then a ` RedisClusterException ` is raised ."""
if not isinstance ( res , dict ) : raise ValueError ( 'Value should be of dict type' ) if len ( res . keys ( ) ) != 1 : raise RedisClusterException ( "More then 1 result from command" ) return list ( res . values ( ) ) [ 0 ]
def via_find_packages ( self ) : # type : ( ) - > List [ str ] """Use find _ packages code to find modules . Can find LOTS of modules . : return :"""
packages = [ ] # type : List [ str ] source = self . setup_py_source ( ) if not source : return packages for row in source . split ( "\n" ) : if "find_packages" in row : logger . debug ( row ) if "find_packages()" in row : packages = find_packages ( ) else : try :...
def format_choicefield_nodes ( field_name , field , field_id , state , lineno ) : """Create a section node that documents a ChoiceField config field . Parameters field _ name : ` str ` Name of the configuration field ( the attribute name of on the config class ) . field : ` ` lsst . pex . config . ChoiceF...
# Create a definition list for the choices choice_dl = nodes . definition_list ( ) for choice_value , choice_doc in field . allowed . items ( ) : item = nodes . definition_list_item ( ) item_term = nodes . term ( ) item_term += nodes . literal ( text = repr ( choice_value ) ) item += item_term item_...
def _check_args ( self , source ) : '''Validate the argument section . Args may be either a dict or a list ( to allow multiple positional args ) .'''
path = [ source ] args = self . parsed_yaml . get ( 'args' , { } ) self . _assert_struct_type ( args , 'args' , ( dict , list ) , path ) path . append ( 'args' ) if isinstance ( args , dict ) : for argn , argattrs in args . items ( ) : self . _check_one_arg ( path , argn , argattrs ) else : # must be list -...
def parse_setup ( ) -> Tuple [ PackagesType , PackagesType , Set [ str ] , Set [ str ] ] : """Parse all dependencies out of the setup . py script ."""
essential_packages : PackagesType = { } test_packages : PackagesType = { } essential_duplicates : Set [ str ] = set ( ) test_duplicates : Set [ str ] = set ( ) with open ( 'setup.py' ) as setup_file : contents = setup_file . read ( ) # Parse out essential packages . package_string = re . search ( r"""install_requir...
def name ( class_name : str , chain_class : Type [ BaseChain ] ) -> Type [ BaseChain ] : """Assign the given name to the chain class ."""
return chain_class . configure ( __name__ = class_name )
def mau ( dataframe , target_day , past_days = 28 , future_days = 10 , date_format = "%Y%m%d" ) : """Compute Monthly Active Users ( MAU ) from the Executive Summary dataset . See https : / / bugzilla . mozilla . org / show _ bug . cgi ? id = 1240849"""
target_day_date = datetime . strptime ( target_day , date_format ) # Compute activity over ` past _ days ` days leading up to target _ day min_activity_date = target_day_date - timedelta ( past_days ) min_activity = unix_time_nanos ( min_activity_date ) max_activity = unix_time_nanos ( target_day_date + timedelta ( 1 )...
def query_bulk ( names ) : """Query server with multiple entries ."""
answers = [ __threaded_query ( name ) for name in names ] while True : if all ( [ a . done ( ) for a in answers ] ) : break sleep ( 1 ) return [ answer . result ( ) for answer in answers ]
def managed ( name , table , data , record = None ) : '''Ensures that the specified columns of the named record have the specified values . Args : name : The name of the record . table : The name of the table to which the record belongs . data : Dictionary containing a mapping from column names to the des...
ret = { 'name' : name , 'changes' : { } , 'result' : False , 'comment' : '' } if record is None : record = name current_data = { column : __salt__ [ 'openvswitch.db_get' ] ( table , record , column ) for column in data } # Comment and change messages comment_changes = 'Columns have been updated.' comment_no_changes...
def scale_meta_data_according_state ( models_dict , rel_pos = None , as_template = False , fill_up = False ) : # TODO Documentation needed . . . . """Scale elements in dict to fit into dict state key element . If elements are already small enough no resize is performed ."""
# TODO check about positions of input - data - and output - data - or scoped variable - ports is needed # TODO adjustments of data ports positions are not sufficient - > origin state size is maybe needed for that # TODO consistency check on boundary and scale parameter for every if else case if 'states' in models_dict ...
def _reset_values ( self , instance ) : """Reset all associated values and clean up dictionary items"""
self . value = None self . reference . value = None instance . __dict__ . pop ( self . field_name , None ) instance . __dict__ . pop ( self . reference . field_name , None ) self . reference . delete_cached_value ( instance )
def _load_ini ( path ) : """Load an INI file from * path * ."""
cfg = RawConfigParser ( ) with codecs . open ( path , mode = "r" , encoding = "utf-8" ) as f : try : cfg . read_file ( f ) except AttributeError : cfg . readfp ( f ) return cfg
def login_handler ( self , config = None , prefix = None , ** args ) : """OAuth starts here , redirect user to Google ."""
params = { 'response_type' : 'code' , 'client_id' : self . google_api_client_id , 'redirect_uri' : self . scheme_host_port_prefix ( 'http' , config . host , config . port , prefix ) + '/home' , 'scope' : self . google_api_scope , 'state' : self . request_args_get ( 'next' , default = '' ) , } url = self . google_oauth2...
def _check_security_groups ( self , names ) : """Raise an exception if any of the named security groups does not exist . : param List [ str ] groups : List of security group names : raises : ` SecurityGroupError ` if group does not exist"""
self . _init_os_api ( ) log . debug ( "Checking existence of security group(s) %s ..." , names ) try : # python - novaclient < 8.0.0 security_groups = self . nova_client . security_groups . list ( ) existing = set ( sg . name for sg in security_groups ) except AttributeError : security_groups = self . neutr...
def remove ( self , path , recursive = True , skip_trash = True ) : """Removes the given mockfile . skip _ trash doesn ' t have any meaning ."""
if recursive : to_delete = [ ] for s in self . get_all_data ( ) . keys ( ) : if s . startswith ( path ) : to_delete . append ( s ) for s in to_delete : self . get_all_data ( ) . pop ( s ) else : self . get_all_data ( ) . pop ( path )
def cutadapt_length_trimmed_plot ( self ) : """Generate the trimming length plot"""
description = 'This plot shows the number of reads with certain lengths of adapter trimmed. \n\ Obs/Exp shows the raw counts divided by the number expected due to sequencing errors. A defined peak \n\ may be related to adapter length. See the \n\ <a href="http://cutadapt.readthedocs.org/en/lates...
def move ( self , path , dest ) : """Use snakebite . rename , if available . : param path : source file ( s ) : type path : either a string or sequence of strings : param dest : destination file ( single input ) or directory ( multiple ) : type dest : string : return : list of renamed items"""
parts = dest . rstrip ( '/' ) . split ( '/' ) if len ( parts ) > 1 : dir_path = '/' . join ( parts [ 0 : - 1 ] ) if not self . exists ( dir_path ) : self . mkdir ( dir_path , parents = True ) return list ( self . get_bite ( ) . rename ( self . list_path ( path ) , dest ) )
def guess_entity_type ( self , entity_id : EntityId ) -> Optional [ EntityType ] : r"""Guess : class : ` ~ . entity . EntityType ` from the given : class : ` ~ . entity . EntityId ` . It could return : const : ` None ` when it fails to guess . . . note : : It always fails to guess when : attr : ` entity _ t...
if not self . entity_type_guess : return None if entity_id [ 0 ] == 'Q' : return EntityType . item elif entity_id [ 0 ] == 'P' : return EntityType . property return None
def _exclude_files_parser ( cls , key ) : """Returns a parser function to make sure field inputs are not files . Parses a value after getting the key so error messages are more informative . : param key : : rtype : callable"""
def parser ( value ) : exclude_directive = 'file:' if value . startswith ( exclude_directive ) : raise ValueError ( 'Only strings are accepted for the {0} field, ' 'files are not accepted' . format ( key ) ) return value return parser
def _load_into_numpy ( sf , np_array , start , end , strides = None , shape = None ) : """Loads into numpy array from SFrame , assuming SFrame stores data flattened"""
np_array [ : ] = 0.0 np_array_2d = np_array . reshape ( ( np_array . shape [ 0 ] , np_array . shape [ 1 ] * np_array . shape [ 2 ] ) ) _extensions . sframe_load_to_numpy ( sf , np_array . ctypes . data , np_array_2d . strides , np_array_2d . shape , start , end )
def calcTransM ( self , gamma = None ) : """calculate transport matrix : param gamma : electron energy measured by mc ^ 2 : return : transport matrix : rtype : numpy array"""
sconf = self . getConfig ( type = 'simu' ) if 'l' in sconf : l = float ( sconf [ 'l' ] ) else : l = 0 self . transM = mathutils . transDrift ( l , gamma ) self . transM_flag = True return self . transM
def print_ldamodel_distribution ( distrib , row_labels , val_labels , top_n = 10 ) : """Print ` n _ top ` top values from a LDA model ' s distribution ` distrib ` . Can be used for topic - word distributions and document - topic distributions ."""
df_values = top_n_from_distribution ( distrib , top_n = top_n , row_labels = row_labels , val_labels = None ) df_labels = top_n_from_distribution ( distrib , top_n = top_n , row_labels = row_labels , val_labels = val_labels ) for i , ( ind , row ) in enumerate ( df_labels . iterrows ( ) ) : print ( ind ) for j ...
def process_buffer ( buffer , n_channels ) : """Merge the read blocks and resample if necessary . Args : buffer ( list ) : A list of blocks of samples . n _ channels ( int ) : The number of channels of the input data . Returns : np . array : The samples"""
samples = np . concatenate ( buffer ) if n_channels > 1 : samples = samples . reshape ( ( - 1 , n_channels ) ) . T samples = librosa . to_mono ( samples ) return samples
def remove ( self , value , session = None ) : '''Remove * value * , an instance of ` ` self . model ` ` from the set of elements contained by the field .'''
s , instance = self . session_instance ( 'remove' , value , session ) # update state so that the instance does look persistent instance . get_state ( iid = instance . pkvalue ( ) , action = 'update' ) return s . delete ( instance )
def _filter_sources ( self , sources ) : """Remove sources with errors and return ordered by host success . : param sources : List of potential sources to connect to . : type sources : list : returns : Sorted list of potential sources without errors . : rtype : list"""
filtered , hosts = [ ] , [ ] for source in sources : if 'error' in source : continue filtered . append ( source ) hosts . append ( source [ 'host_name' ] ) return sorted ( filtered , key = lambda s : self . _hosts_by_success ( hosts ) . index ( s [ 'host_name' ] ) )
def fetch_s3_package ( self , config ) : """Make a remote S3 archive available for local use . Args : config ( dict ) : git config dictionary"""
extractor_map = { '.tar.gz' : TarGzipExtractor , '.tar' : TarExtractor , '.zip' : ZipExtractor } extractor = None for suffix , klass in extractor_map . items ( ) : if config [ 'key' ] . endswith ( suffix ) : extractor = klass ( ) logger . debug ( "Using extractor %s for S3 object \"%s\" in " "bucket...