signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def p_formula_atom ( self , p ) : """formula : ATOM | TRUE | FALSE"""
if p [ 1 ] == Symbols . TRUE . value : p [ 0 ] = PLTrue ( ) elif p [ 1 ] == Symbols . FALSE . value : p [ 0 ] = PLFalse ( ) else : p [ 0 ] = PLAtomic ( Symbol ( p [ 1 ] ) )
def create_db_entry ( self , release ) : """Create a db entry for releasefile of the given release Set _ releasedbentry and _ commentdbentry of the given release file This is inteded to be used in a action unit . : param release : the release with the releasefile and comment : type release : : class : ` Rel...
log . info ( "Create database entry with comment: %s" , release . comment ) tfi = release . _releasefile . get_obj ( ) tf , note = tfi . create_db_entry ( release . comment ) release . _releasedbentry = tf release . _commentdbentry = note return ActionStatus ( ActionStatus . SUCCESS , msg = "Created database entry for ...
def undo ( self ) : """Raises IndexError if more than one group is open , otherwise closes it and invokes undo _ nested _ group ."""
if self . grouping_level ( ) == 1 : self . end_grouping ( ) if self . _open : raise IndexError self . undo_nested_group ( ) self . notify ( )
def horner ( coeffs , x ) : r'''Evaluates a polynomial defined by coefficienfs ` coeffs ` at a specified scalar ` x ` value , using the horner method . This is the most efficient formula to evaluate a polynomial ( assuming non - zero coefficients for all terms ) . This has been added to the ` fluids ` library...
tot = 0.0 for c in coeffs : tot = tot * x + c return tot
def _set_clear_mpls_auto_bandwidth_statistics_all ( self , v , load = False ) : """Setter method for clear _ mpls _ auto _ bandwidth _ statistics _ all , mapped from YANG variable / brocade _ mpls _ rpc / clear _ mpls _ auto _ bandwidth _ statistics _ all ( rpc ) If this variable is read - only ( config : false )...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = clear_mpls_auto_bandwidth_statistics_all . clear_mpls_auto_bandwidth_statistics_all , is_leaf = True , yang_name = "clear-mpls-auto-bandwidth-statistics-all" , rest_name = "clear-mpls-auto-bandwidth-statistics-all" , parent =...
def allow_migrate ( self , db , app_label , model_name = None , ** hints ) : """Don ' t attempt to sync SF models to non SF databases and vice versa ."""
if model_name : model = apps . get_model ( app_label , model_name ) else : # hints are used with less priority , because many hints are dynamic # models made by migrations on a ' _ _ fake _ _ ' module which are not # SalesforceModels model = hints . get ( 'model' ) if hasattr ( model , '_salesforce_object' ) : ...
def _legacy_request ( self , method , table , ** kwargs ) : """Returns a : class : ` LegacyRequest ` object , compatible with Client . query and Client . insert : param method : HTTP method : param table : Table to operate on : return : - : class : ` LegacyRequest ` object"""
warnings . warn ( "`%s` is deprecated and will be removed in a future release. " "Please use `resource()` instead." % inspect . stack ( ) [ 1 ] [ 3 ] , DeprecationWarning ) return LegacyRequest ( method , table , request_params = self . request_params , raise_on_empty = self . raise_on_empty , session = self . session ...
def sync_nodes ( self , clusters ) : """Syncs the enabled / disabled status of nodes existing in HAProxy based on the given clusters . This is used to inform HAProxy of up / down nodes without necessarily doing a restart of the process ."""
logger . info ( "Syncing HAProxy backends." ) current_nodes , enabled_nodes = self . get_current_nodes ( clusters ) for cluster_name , nodes in six . iteritems ( current_nodes ) : for node in nodes : if node [ "svname" ] in enabled_nodes [ cluster_name ] : command = self . control . enable_node ...
def split_grad_list ( grad_list ) : """Args : grad _ list : K x N x 2 Returns : K x N : gradients K x N : variables"""
g = [ ] v = [ ] for tower in grad_list : g . append ( [ x [ 0 ] for x in tower ] ) v . append ( [ x [ 1 ] for x in tower ] ) return g , v
def _ResolveContext ( self , context , name , raw_data , path = None ) : """Returns the config options active under this context ."""
if path is None : path = [ ] for element in context : if element not in self . valid_contexts : raise InvalidContextError ( "Invalid context specified: %s" % element ) if element in raw_data : context_raw_data = raw_data [ element ] value = context_raw_data . get ( name ) if ...
def main ( ) : """Get arguments and call the execution function"""
prog = sys . argv [ 0 ] arg_parser = create_parser ( prog ) opts = parse_cmdline ( arg_parser ) print ( 'Parameters: server=%s\n username=%s\n namespace=%s\n' ' classname=%s\n max_pull_size=%s\n use_pull=%s' % ( opts . server , opts . user , opts . namespace , opts . classname , opts . max_object_count , opts . usepull...
def getView ( self , lv ) : """Determine the detector view starting with a G4LogicalVolume"""
view = None if str ( lv . GetName ( ) ) [ - 1 ] == 'X' : return 'X' elif str ( lv . GetName ( ) ) [ - 1 ] == 'Y' : return 'Y' self . log . error ( 'Cannot determine view for %s' , lv . GetName ( ) ) raise 'Cannot determine view for %s' % lv . GetName ( ) return view
def shape ( self ) -> Tuple [ int , ... ] : """The shape of array | anntools . SeasonalANN . ratios | ."""
return tuple ( int ( sub ) for sub in self . ratios . shape )
def get_recurrence ( self , config ) : '''Calculates the recurrence model for the given settings as an instance of the openquake . hmtk . models . IncrementalMFD : param dict config : Configuration settings of the magnitude frequency distribution .'''
model = MFD_MAP [ config [ 'Model_Name' ] ] ( ) model . setUp ( config ) model . get_mmax ( config , self . msr , self . rake , self . area ) model . mmax = model . mmax + ( self . msr_sigma * model . mmax_sigma ) # As the Anderson & Luco arbitrary model requires the input of the # displacement to length ratio if 'Ande...
def get_predictions_under_minimal_repair ( instance , repair_options , optimum ) : '''Computes the set of signs on edges / vertices that can be cautiously derived from [ instance ] , minus those that are a direct consequence of obs _ [ ev ] label predicates'''
inst = instance . to_file ( ) repops = repair_options . to_file ( ) prg = [ inst , repops , prediction_core_prg , repair_cardinality_prg ] options = '--project --enum-mode cautious --opt-mode=optN --opt-bound=' + str ( optimum ) solver = GringoClasp ( clasp_options = options ) models = solver . run ( prg , collapseTerm...
def _monitor_pbc_status ( self ) : """Monitor the PBC status ."""
LOG . info ( 'Starting to Monitor PBC status.' ) inspect = celery . current_app . control . inspect ( ) workers = inspect . ping ( ) start_time = time . time ( ) while workers is None : time . sleep ( 0.1 ) elapsed = time . time ( ) - start_time if elapsed > 20.0 : LOG . warning ( 'PBC not found!' )...
def _validate_empty ( self , empty , field , value ) : """{ ' type ' : ' boolean ' }"""
if isinstance ( value , Iterable ) and len ( value ) == 0 : self . _drop_remaining_rules ( 'allowed' , 'forbidden' , 'items' , 'minlength' , 'maxlength' , 'regex' , 'validator' ) if not empty : self . _error ( field , errors . EMPTY_NOT_ALLOWED )
def eval_valid ( self , feval = None ) : """Evaluate for validation data . Parameters feval : callable or None , optional ( default = None ) Customized evaluation function . Should accept two parameters : preds , train _ data , and return ( eval _ name , eval _ result , is _ higher _ better ) or list of s...
return [ item for i in range_ ( 1 , self . __num_dataset ) for item in self . __inner_eval ( self . name_valid_sets [ i - 1 ] , i , feval ) ]
def filenames_to_uniq ( names , new_delim = '.' ) : '''Given a set of file names , produce a list of names consisting of the uniq parts of the names . This works from the end of the name . Chunks of the name are split on ' . ' and ' - ' . For example : A . foo . bar . txt B . foo . bar . txt returns : [...
name_words = [ ] maxlen = 0 for name in names : name_words . append ( name . replace ( '.' , ' ' ) . replace ( '-' , ' ' ) . strip ( ) . split ( ) ) name_words [ - 1 ] . reverse ( ) if len ( name_words [ - 1 ] ) > maxlen : maxlen = len ( name_words [ - 1 ] ) common = [ False , ] * maxlen for i in ra...
def cron ( cronline , venusian_category = 'irc3.plugins.cron' ) : """main decorator"""
def wrapper ( func ) : def callback ( context , name , ob ) : obj = context . context crons = obj . get_plugin ( Crons ) if info . scope == 'class' : callback = getattr ( obj . get_plugin ( ob ) , func . __name__ ) else : callback = irc3 . utils . wraps_with_c...
def reload ( self , index ) : """Reload file from disk"""
finfo = self . data [ index ] txt , finfo . encoding = encoding . read ( finfo . filename ) finfo . lastmodified = QFileInfo ( finfo . filename ) . lastModified ( ) position = finfo . editor . get_position ( 'cursor' ) finfo . editor . set_text ( txt ) finfo . editor . document ( ) . setModified ( False ) finfo . edito...
def write_variableattrs ( self , variableAttrs ) : """Writes a variable ' s attributes , provided the variable already exists . Parameters variableAttrs : dict Variable attribute name and its entry value pair ( s ) . The entry value is also a dictionary of variable id and value pair ( s ) . Variable id ca...
if not ( isinstance ( variableAttrs , dict ) ) : print ( 'Variable attribute(s) not in dictionary form.... Stop' ) return dataType = None numElems = None with self . path . open ( 'rb+' ) as f : f . seek ( 0 , 2 ) # EOF ( appending ) for attr , attrs in variableAttrs . items ( ) : if not ( i...
def account_search ( self , q , limit = None , following = False ) : """Fetch matching accounts . Will lookup an account remotely if the search term is in the username @ domain format and not yet in the database . Set ` following ` to True to limit the search to users the logged - in user follows . Returns a ...
params = self . __generate_params ( locals ( ) ) if params [ "following" ] == False : del params [ "following" ] return self . __api_request ( 'GET' , '/api/v1/accounts/search' , params )
def redirect_logging ( tqdm_obj , logger = logging . getLogger ( ) ) : """Context manager to redirect logging to a TqdmLoggingHandler object and then restore the original ."""
# remove current handler assert ( len ( logger . handlers ) == 1 ) prev_handler = logger . handlers [ 0 ] logger . removeHandler ( prev_handler ) # add tqdm handler tqdm_handler = TqdmLoggingHandler ( tqdm_obj ) if prev_handler . formatter is not None : tqdm_handler . setFormatter ( prev_handler . formatter ) logge...
def context ( type_config = 'float' , ** kw ) : """CPU Context ."""
backends = [ 'cpu:float' ] if type_config == 'half' : backends = [ 'cpu:half' , 'cpu:float' ] elif type_config == 'float' : pass else : raise ValueError ( "Unknown data type config is given %s" % type_config ) return nn . Context ( backends , array_classes ( ) [ 0 ] , '' )
def check_key ( self , key ) : """Checks key and add key _ prefix ."""
return _check_key ( key , allow_unicode_keys = self . allow_unicode_keys , key_prefix = self . key_prefix )
def _raise_error ( self , status_code , raw_data ) : """Locate appropriate exception and raise it ."""
error_message = raw_data additional_info = None try : additional_info = json . loads ( raw_data ) error_message = additional_info . get ( 'error' , error_message ) if isinstance ( error_message , dict ) and 'type' in error_message : error_message = error_message [ 'type' ] except : pass raise HT...
def iter_conditions ( condition ) : """Yield all conditions within the given condition . If the root condition is and / or / not , it is not yielded ( unless a cyclic reference to it is found ) ."""
conditions = list ( ) visited = set ( ) # Has to be split out , since we don ' t want to visit the root ( for cyclic conditions ) # but we don ' t want to yield it ( if it ' s non - cyclic ) because this only yields inner conditions if condition . operation in { "and" , "or" } : conditions . extend ( reversed ( con...
def hasvar ( obj , var ) : """Checks if object , obj has a variable var return True or False"""
if hasattr ( obj , var ) : return not callable ( getattr ( obj , var ) ) return False
def instruction_BHS ( self , opcode , ea ) : """CC bits " HNZVC " : - - - - - case 0x4 : cond = ! ( REG _ CC & CC _ C ) ; break ; / / BCC , BHS , LBCC , LBHS"""
if self . C == 0 : # log . info ( " $ % x BHS / BCC / LBHS / LBCC branch to $ % x , because C = = 0 \ t | % s " % ( # self . program _ counter , ea , self . cfg . mem _ info . get _ shortest ( ea ) self . program_counter . set ( ea )
def ensure_one_opt ( opt , parser , opt_list ) : """Check that one and only one in the opt _ list is defined in opt Parameters opt : object Result of option parsing parser : object OptionParser instance . opt _ list : list of strings"""
the_one = None for name in opt_list : attr = name [ 2 : ] . replace ( '-' , '_' ) if hasattr ( opt , attr ) and ( getattr ( opt , attr ) is not None ) : if the_one is None : the_one = name else : parser . error ( "%s and %s are mutually exculsive" % ( the_one , name ) ) i...
def list_vrf ( arg , opts , shell_opts ) : """List VRFs matching a search criteria"""
search_string = '' if type ( arg ) == list or type ( arg ) == tuple : search_string = ' ' . join ( arg ) offset = 0 limit = 100 while True : res = VRF . smart_search ( search_string , { 'offset' : offset , 'max_result' : limit } ) if offset == 0 : if shell_opts . show_interpretation : pr...
def cric__ridge ( ) : """Ridge Regression"""
model = sklearn . linear_model . LogisticRegression ( penalty = "l2" ) # we want to explain the raw probability outputs of the trees model . predict = lambda X : model . predict_proba ( X ) [ : , 1 ] return model
def is_active ( self , timeout = 2 ) : """: param timeout : int : return : boolean"""
try : result = Result ( * self . perform_request ( 'HEAD' , '/' , params = { 'request_timeout' : timeout } ) ) except ConnectionError : return False except TransportError : return False if result . response . status_code == 200 : return True return False
def bench_voluptuous ( ) : """Benchmark for 1000 objects with 2 fields ."""
schema = Schema ( { Required ( 'attr_1' ) : str , Required ( 'attr_2' ) : int } ) return [ schema ( obj ) for obj in object_loader ( ) ]
def all_macro_systems ( network , state , do_blackbox = False , do_coarse_grain = False , time_scales = None ) : """Generator over all possible macro - systems for the network ."""
if time_scales is None : time_scales = [ 1 ] def blackboxes ( system ) : # Returns all blackboxes to evaluate if not do_blackbox : return [ None ] return all_blackboxes ( system ) def coarse_grains ( blackbox , system ) : # Returns all coarse - grains to test if not do_coarse_grain : ret...
def rename_slide_parts ( self , rIds ) : """Assign incrementing partnames like ` ` / ppt / slides / slide9 . xml ` ` to the slide parts identified by * rIds * , in the order their id appears in that sequence . The name portion is always ` ` slide ` ` . The number part forms a continuous sequence starting at 1...
for idx , rId in enumerate ( rIds ) : slide_part = self . related_parts [ rId ] slide_part . partname = PackURI ( '/ppt/slides/slide%d.xml' % ( idx + 1 ) )
def post_shared_file ( self , image_file = None , source_link = None , shake_id = None , title = None , description = None ) : """Upload an image . TODO : Don ' t have a pro account to test ( or even write ) code to upload a shared filed to a particular shake . Args : image _ file ( str ) : path to an ima...
if image_file and source_link : raise Exception ( 'You can only specify an image file or ' 'a source link, not both.' ) if not image_file and not source_link : raise Exception ( 'You must specify an image file or a source link' ) content_type = self . _get_image_type ( image_file ) if not title : title = os...
def copy ( self , invert = False ) : """Return a copy of the current instance Parameters invert : bool The copy will be inverted w . r . t . the original"""
if invert : inverted = not self . inverted else : inverted = self . inverted return PolygonFilter ( axes = self . axes , points = self . points , name = self . name , inverted = inverted )
def _get_u16 ( self , msb , lsb ) : """Convert 2 bytes into an unsigned int ."""
buf = struct . pack ( '>BB' , self . _get_u8 ( msb ) , self . _get_u8 ( lsb ) ) return int ( struct . unpack ( '>H' , buf ) [ 0 ] )
def on ( self , name , _callback = None ) : """Add a callback to the event named ' name ' . Returns callback object for decorationable calls ."""
# this is being used as a decorator if _callback is None : return lambda cb : self . on ( name , cb ) if not ( callable ( _callback ) or isawaitable ( _callback ) ) : msg = "Callback not callable: {0!r}" . format ( _callback ) raise ValueError ( msg ) self . _event_list [ name ] . append ( _callback ) retur...
def rebin2x2 ( a ) : """Wrapper around rebin that actually rebins 2 by 2"""
inshape = np . array ( a . shape ) if not ( inshape % 2 == np . zeros ( 2 ) ) . all ( ) : # Modulo check to see if size is even raise RuntimeError , "I want even image shapes !" return rebin ( a , inshape / 2 )
def top3_reduced ( votes ) : """Description : Top 3 alternatives 16 moment conditions values calculation Parameters : votes : ordinal preference data ( numpy ndarray of integers )"""
res = np . zeros ( 16 ) for vote in votes : # the top ranked alternative is in vote [ 0 ] [ 0 ] , second in vote [ 1 ] [ 0] if vote [ 0 ] [ 0 ] == 0 : # i . e . the first alt is ranked first res [ 0 ] += 1 if vote [ 1 ] [ 0 ] == 2 : res [ 4 ] += 1 elif vote [ 1 ] [ 0 ] == 3 : ...
def clear ( self ) : """Remove all nodes from the list ."""
node = self . _first while node is not None : next_node = node . _next node . _list = node . _prev = node . _next = None node = next_node self . _size = 0
def list_storages ( self ) : '''Returns a list of existing stores . The returned names can then be used to call get _ storage ( ) .'''
# Filter out any storages used by xbmcswift2 so caller doesn ' t corrupt # them . return [ name for name in os . listdir ( self . storage_path ) if not name . startswith ( '.' ) ]
def checkDGEOFile ( filenames ) : """Verify that input file has been updated with NPOLFILE This function checks for the presence of ' NPOLFILE ' kw in the primary header when ' DGEOFILE ' kw is present and valid ( i . e . ' DGEOFILE ' is not blank or ' N / A ' ) . It handles the case of science files download...
msg = """ A 'DGEOFILE' keyword is present in the primary header but 'NPOLFILE' keyword was not found. This version of the software uses a new format for the residual distortion DGEO files. Please consult the instrument web pages for which reference files to download. A sm...
def fit ( self , users , items , user_features = None , item_features = None ) : """Fit the user / item id and feature name mappings . Calling fit the second time will reset existing mappings . Parameters users : iterable of user ids items : iterable of item ids user _ features : iterable of user features...
self . _user_id_mapping = { } self . _item_id_mapping = { } self . _user_feature_mapping = { } self . _item_feature_mapping = { } return self . fit_partial ( users , items , user_features , item_features )
def unroll ( self , length , inputs , begin_state = None , layout = 'NTC' , merge_outputs = None ) : """Unroll an RNN cell across time steps . Parameters length : int Number of steps to unroll . inputs : Symbol , list of Symbol , or None If ` inputs ` is a single Symbol ( usually the output of Embedding...
self . reset ( ) inputs , _ = _normalize_sequence ( length , inputs , layout , False ) if begin_state is None : begin_state = self . begin_state ( ) states = begin_state outputs = [ ] for i in range ( length ) : output , states = self ( inputs [ i ] , states ) outputs . append ( output ) outputs , _ = _norm...
def get_gpio_pin ( self , pin_number , dest_addr_long = None ) : """Get a gpio pin setting ."""
frame = self . _send_and_wait ( command = const . IO_PIN_COMMANDS [ pin_number ] , dest_addr_long = dest_addr_long ) value = frame [ "parameter" ] return const . GPIO_SETTINGS [ value ]
def helical_turbulent_fd_Mori_Nakayama ( Re , Di , Dc ) : r'''Calculates Darcy friction factor for a fluid flowing inside a curved pipe such as a helical coil under turbulent conditions , using the method of Mori and Nakayama [ 1 ] _ , also shown in [ 2 ] _ and [ 3 ] _ . . . math : : f _ { curv } = 0.3 \ le...
term = ( Re * ( Di / Dc ) ** 2 ) ** - 0.2 return 0.3 * ( Dc / Di ) ** - 0.5 * term * ( 1. + 0.112 * term )
def do_random ( context , seq ) : """Return a random item from the sequence ."""
try : return random . choice ( seq ) except IndexError : return context . environment . undefined ( 'No random item, sequence was empty.' )
def list_all_commands ( self ) : """Returns a list of all the Workbench commands"""
commands = [ name for name , _ in inspect . getmembers ( self , predicate = inspect . isroutine ) if not name . startswith ( '_' ) ] return commands
def collect ( self ) : """Create some concurrent workers that process the tasks simultaneously ."""
collected = super ( Command , self ) . collect ( ) if self . faster : self . worker_spawn_method ( ) self . post_processor ( ) return collected
def fetch_uri ( self , directory , uri ) : """Use ` ` urllib . urlretrieve ` ` to download package to file in sandbox dir . @ param directory : directory to download to @ type directory : string @ param uri : uri to download @ type uri : string @ returns : 0 = success or 1 for failed download"""
filename = os . path . basename ( urlparse ( uri ) [ 2 ] ) if os . path . exists ( filename ) : self . logger . error ( "ERROR: File exists: " + filename ) return 1 try : downloaded_filename , headers = urlretrieve ( uri , filename ) self . logger . info ( "Downloaded ./" + filename ) except IOError as ...
def delete_handler ( Model , name = None , ** kwds ) : """This factory returns an action handler that deletes a new instance of the specified model when a delete action is recieved , assuming the action follows nautilus convetions . Args : Model ( nautilus . BaseModel ) : The model to delete when the action...
# necessary imports from nautilus . database import db async def action_handler ( service , action_type , payload , props , notify = True , ** kwds ) : # if the payload represents a new instance of ` model ` if action_type == get_crud_action ( 'delete' , name or Model ) : try : # the props of the message ...
def round ( value , decimal = 7 , digits = None ) : """ROUND TO GIVEN NUMBER OF DIGITS , OR GIVEN NUMBER OF DECIMAL PLACES decimal - NUMBER OF DIGITS AFTER DECIMAL POINT ( NEGATIVE IS VALID ) digits - NUMBER OF SIGNIFICANT DIGITS ( LESS THAN 1 IS INVALID )"""
if value == None : return None else : value = float ( value ) if digits != None : if digits <= 0 : if value == 0 : return int ( _round ( value , digits ) ) try : m = pow ( 10 , math_ceil ( math_log10 ( abs ( value ) ) ) ) return int ( _round ( value / m , ...
def apply_colormap ( image , colormap , contig = True ) : """Return palette - colored image . The image values are used to index the colormap on axis 1 . The returned image is of shape image . shape + colormap . shape [ 0 ] and dtype colormap . dtype . Parameters image : numpy . ndarray Indexes into the c...
image = numpy . take ( colormap , image , axis = 1 ) image = numpy . rollaxis ( image , 0 , image . ndim ) if contig : image = numpy . ascontiguousarray ( image ) return image
def escape ( s , fold_newlines = True ) : """Escapes a string to make it usable in LaTeX text mode . Will replace special characters as well as newlines . Some problematic characters like ` ` [ ` ` and ` ` ] ` ` are escaped into groups ( e . g . ` ` { [ } ` ` ) , because they tend to cause problems when mixed...
def sub ( m ) : c = m . group ( ) if c in CHAR_ESCAPE : return CHAR_ESCAPE [ c ] if c . isspace ( ) : if fold_newlines : return r'\\' return r'\\[{}\baselineskip]' . format ( len ( c ) ) return ESCAPE_RE . sub ( sub , s )
def fix_norm_and_length ( vector ) : """Create a normalized and zero padded version of vector . : param 1darray vector : a vector with at least one nonzero component . : return : a vector that is the normalized version of vector , padded at the end with the smallest number of 0s necessary to make the length...
# normalize norm_vector = vector / np . linalg . norm ( vector ) # pad with zeros num_bits = get_bits_needed ( len ( vector ) ) state_vector = np . zeros ( 2 ** num_bits , dtype = complex ) for i in range ( len ( vector ) ) : state_vector [ i ] = norm_vector [ i ] return state_vector
def p_data ( p ) : """statement : DATA arguments"""
label_ = make_label ( gl . DATA_PTR_CURRENT , lineno = p . lineno ( 1 ) ) datas_ = [ ] funcs = [ ] if p [ 2 ] is None : p [ 0 ] = None return for d in p [ 2 ] . children : value = d . value if is_static ( value ) : datas_ . append ( d ) continue new_lbl = '__DATA__FUNCPTR__{0}' . for...
def _ndefs ( f ) : '''number of any default values for positional or keyword parameters'''
if isinstance ( f , Function ) : return f . ndefs spec = inspect . getfullargspec ( f ) if spec . defaults is None : return 0 return len ( spec . defaults )
def setUp ( self ) : """Prepare to run test case . Start harness service , init golden devices , reset DUT and open browser ."""
if self . __class__ is HarnessCase : return logger . info ( 'Setting up' ) # clear files logger . info ( 'Deleting all .pdf' ) os . system ( 'del /q "%HOMEDRIVE%%HOMEPATH%\\Downloads\\NewPdf_*.pdf"' ) logger . info ( 'Deleting all .xlsx' ) os . system ( 'del /q "%HOMEDRIVE%%HOMEPATH%\\Downloads\\ExcelReport*.xlsx"'...
def actually_start_agent ( self , descriptor , ** kwargs ) : """This method will be run only on the master agency ."""
factory = IAgentFactory ( applications . lookup_agent ( descriptor . type_name ) ) if factory . standalone : return self . start_standalone_agent ( descriptor , factory , ** kwargs ) else : return self . start_agent_locally ( descriptor , ** kwargs )
def dumps ( self , obj , * , max_nested_level = 100 ) : """Returns a string representing a JSON - encoding of ` ` obj ` ` . The second optional ` ` max _ nested _ level ` ` argument controls the maximum allowed recursion / nesting level . See class description for details ."""
self . _max_nested_level = max_nested_level return self . _encode ( obj )
def has_values ( self , name , tmin , tmax ) : """A basic fit equality checker compares name and bounds of 2 fits @ param : name - > name of the other fit @ param : tmin - > lower bound of the other fit @ param : tmax - > upper bound of the other fit @ return : boolean comaparing 2 fits"""
return str ( self . name ) == str ( name ) and str ( self . tmin ) == str ( tmin ) and str ( self . tmax ) == str ( tmax )
def reset ( self ) : """Totally reset the cache"""
[ a ( ) . remove_observer ( self , self . on_cache_changed ) if ( a ( ) is not None ) else None for [ a , _ ] in self . cached_input_ids . values ( ) ] self . order = collections . deque ( ) self . cached_inputs = { } # point from cache _ ids to a list of [ ind _ ids ] , which where used in cache cache _ id # point fro...
def file_to_attachment ( filename , filehandler = None ) : """Convert a file to attachment"""
if filehandler : return { '_name' : filename , 'content' : base64 . b64encode ( filehandler . read ( ) ) } with open ( filename , 'rb' ) as _file : return { '_name' : filename , 'content' : base64 . b64encode ( _file . read ( ) ) }
def _prepare_for_cross_validation ( self , corr , clf ) : """Prepare data for voxelwise cross validation . If the classifier is sklearn . svm . SVC with precomputed kernel , the kernel matrix of each voxel is computed , otherwise do nothing . Parameters corr : 3D array in shape [ num _ processed _ voxels , ...
time1 = time . time ( ) ( num_processed_voxels , num_epochs , _ ) = corr . shape if isinstance ( clf , sklearn . svm . SVC ) and clf . kernel == 'precomputed' : # kernel matrices should be computed kernel_matrices = np . zeros ( ( num_processed_voxels , num_epochs , num_epochs ) , np . float32 , order = 'C' ) f...
def get_metadata ( did ) : """Get metadata of a particular asset tags : - metadata parameters : - name : did in : path description : DID of the asset . required : true type : string responses : 200: description : successful operation . 404: description : This asset DID is not in OceanDB ."...
try : asset_record = dao . get ( did ) metadata = _get_metadata ( asset_record [ 'service' ] ) return Response ( _sanitize_record ( metadata ) , 200 , content_type = 'application/json' ) except Exception as e : logger . error ( e ) return f'{did} asset DID is not in OceanDB' , 404
def item_details ( item_id , lang = "en" ) : """This resource returns a details about a single item . : param item _ id : The item to query for . : param lang : The language to display the texts in . The response is an object with at least the following properties . Note that the availability of some proper...
params = { "item_id" : item_id , "lang" : lang } cache_name = "item_details.%(item_id)s.%(lang)s.json" % params return get_cached ( "item_details.json" , cache_name , params = params )
def ignores ( self , * args ) : """: param args : Event objects : returns : None Any event that is ignored is acceptable but discarded"""
for event in args : self . _ignored . add ( event . name )
def _finish_pending_requests ( self ) -> None : """Process any requests that were completed by the last call to multi . socket _ action ."""
while True : num_q , ok_list , err_list = self . _multi . info_read ( ) for curl in ok_list : self . _finish ( curl ) for curl , errnum , errmsg in err_list : self . _finish ( curl , errnum , errmsg ) if num_q == 0 : break self . _process_queue ( )
def update_profile ( self , about_me = None , display_name = None , email = None , first_name = None , gender = None , last_name = None , mobile_number = None , relationship_status = None , title = None , where_am_i = None , scope = 'profile/write' ) : """Update the Mxit user ' s profile User authentication requi...
data = { } if about_me : data [ 'AboutMe' ] = about_me if display_name : data [ 'DisplayName' ] = display_name if email : data [ 'Email' ] = email if first_name : data [ 'FirstName' ] = first_name if gender : data [ 'Gender' ] = gender if last_name : data [ 'LastName' ] = last_name if mobile_num...
def _on_close ( self , socket ) : """Called when the connection was closed ."""
self . logger . debug ( 'Connection closed.' ) for subscription in self . subscriptions . values ( ) : if subscription . state == 'subscribed' : subscription . state = 'connection_pending'
def render ( self , context = None ) : """Renders the error message , optionally using the given context ( which , if specified , will override the internal context ) ."""
ctx = context . render ( ) if context else self . get_error_context ( ) . render ( ) return "%s: %s%s%s" % ( self . get_error_kind ( ) , self . get_error_message ( ) , ( " (%s)." % ctx ) if ctx else "" , self . get_additional_error_detail ( ) )
def p_concat_list ( p ) : """concat _ list : expr _ list SEMI expr _ list | concat _ list SEMI expr _ list"""
if p [ 1 ] . __class__ == node . expr_list : p [ 0 ] = node . concat_list ( [ p [ 1 ] , p [ 3 ] ] ) else : p [ 0 ] = p [ 1 ] p [ 0 ] . append ( p [ 3 ] )
def always_iterable ( obj , base_type = ( str , bytes ) ) : """If * obj * is iterable , return an iterator over its items : : > > > obj = ( 1 , 2 , 3) > > > list ( always _ iterable ( obj ) ) [1 , 2 , 3] If * obj * is not iterable , return a one - item iterable containing * obj * : : > > > obj = 1 > > >...
if obj is None : return iter ( ( ) ) if ( base_type is not None ) and isinstance ( obj , base_type ) : return iter ( ( obj , ) ) try : return iter ( obj ) except TypeError : return iter ( ( obj , ) )
def pipeline_execute_command ( self , * args , ** options ) : """Stage a command to be executed when execute ( ) is next called Returns the current Pipeline object back so commands can be chained together , such as : pipe = pipe . set ( ' foo ' , ' bar ' ) . incr ( ' baz ' ) . decr ( ' bang ' ) At some othe...
self . command_stack . append ( ( args , options ) ) return self
def disqualified ( self , num , natural = True , ** kwargs ) : """Search for disqualified officers by officer ID . Searches for natural disqualifications by default . Specify natural = False to search for corporate disqualifications . Args : num ( str ) : Company number to search on . natural ( Optional [...
search_type = 'natural' if natural else 'corporate' baseuri = ( self . _BASE_URI + 'disqualified-officers/{}/{}' . format ( search_type , num ) ) res = self . session . get ( baseuri , params = kwargs ) self . handle_http_error ( res ) return res
def add_lambda_permissions ( function = '' , statement_id = '' , action = 'lambda:InvokeFunction' , principal = '' , source_arn = '' , env = '' , region = 'us-east-1' ) : """Add permission to Lambda for the event trigger . Args : function ( str ) : Lambda function name statement _ id ( str ) : IAM policy stat...
session = boto3 . Session ( profile_name = env , region_name = region ) lambda_client = session . client ( 'lambda' ) response_action = None prefixed_sid = FOREMAST_PREFIX + statement_id add_permissions_kwargs = { 'FunctionName' : function , 'StatementId' : prefixed_sid , 'Action' : action , 'Principal' : principal , }...
def check_all ( cls , tools = True , encoding = True , c_ext = True ) : """Perform all checks . Return a tuple of booleans ` ` ( errors , warnings , c _ ext _ warnings ) ` ` . : param bool tools : if ` ` True ` ` , check aeneas tools : param bool encoding : if ` ` True ` ` , check shell encoding : param boo...
# errors are fatal if cls . check_ffprobe ( ) : return ( True , False , False ) if cls . check_ffmpeg ( ) : return ( True , False , False ) if cls . check_espeak ( ) : return ( True , False , False ) if ( tools ) and ( cls . check_tools ( ) ) : return ( True , False , False ) # warnings are non - fatal ...
def add_child_hash ( self , child_hash ) : """Adds specified child hash . The hash must be one of the binary types ."""
# Hash must generate binary keys if not ( isinstance ( child_hash , PCABinaryProjections ) or isinstance ( child_hash , RandomBinaryProjections ) or isinstance ( child_hash , RandomBinaryProjectionTree ) ) : raise ValueError ( 'Child hashes must generate binary keys' ) # Add both hash and config to array of child h...
def node_to_elem ( root ) : """Convert ( recursively ) a Node object into an ElementTree object ."""
def generate_elem ( append , node , level ) : var = "e" + str ( level ) arg = repr ( node . tag ) if node . attrib : arg += ", **%r" % node . attrib if level == 1 : append ( "e1 = Element(%s)" % arg ) else : append ( "%s = SubElement(e%d, %s)" % ( var , level - 1 , arg ) ) ...
def stop_all ( self ) : """Stop all module instances : return : None"""
logger . info ( 'Shutting down modules...' ) # Ask internal to quit if they can for instance in self . get_internal_instances ( ) : if hasattr ( instance , 'quit' ) and isinstance ( instance . quit , collections . Callable ) : instance . quit ( ) self . clear_instances ( [ instance for instance in self . in...
def center_of_mass ( self ) : """Calculates the center of mass of the slab"""
weights = [ s . species . weight for s in self ] center_of_mass = np . average ( self . frac_coords , weights = weights , axis = 0 ) return center_of_mass
def create_mysql_db ( db_url ) : """To simplify deployment , create the mysql DB if it ' s not there . Accepts a URL with or without a DB name stated , and returns a db url containing the db name for use in the main sqlalchemy engine . THe formats can take the following form : mysql + driver : / / username ...
# Remove trailing whitespace and forwardslashes db_url = db_url . strip ( ) . strip ( '/' ) # Check this is a mysql URL if db_url . find ( 'mysql' ) >= 0 : # Get the DB name from config and check if it ' s in the URL db_name = config . get ( 'mysqld' , 'db_name' , 'hydradb' ) if db_url . find ( db_name ) >= 0 :...
def make_xpath_ranges ( html , phrase ) : '''Given a HTML string and a ` phrase ` , build a regex to find offsets for the phrase , and then build a list of ` XPathRange ` objects for it . If this fails , return empty list .'''
if not html : return [ ] if not isinstance ( phrase , unicode ) : try : phrase = phrase . decode ( 'utf8' ) except : logger . info ( 'failed %r.decode("utf8")' , exc_info = True ) return [ ] phrase_re = re . compile ( phrase , flags = re . UNICODE | re . IGNORECASE | re . MULTILINE )...
def add_fields ( self , fields ) : """Adds all of the passed fields to the table ' s current field list : param fields : The fields to select from ` ` table ` ` . This can be a single field , a tuple of fields , or a list of fields . Each field can be a string or ` ` Field ` ` instance : type fields : str o...
if isinstance ( fields , string_types ) : fields = [ fields ] elif type ( fields ) is tuple : fields = list ( fields ) field_objects = [ self . add_field ( field ) for field in fields ] return field_objects
def enum ( option , * options ) : """Construct a new enum object . Parameters * options : iterable of str The names of the fields for the enum . Returns enum A new enum collection . Examples > > > e = enum ( ' a ' , ' b ' , ' c ' ) < enum : ( ' a ' , ' b ' , ' c ' ) > > > > e . a > > > e . b ...
options = ( option , ) + options rangeob = range ( len ( options ) ) try : inttype = _inttypes [ int ( np . log2 ( len ( options ) - 1 ) ) // 8 ] except IndexError : raise OverflowError ( 'Cannot store enums with more than sys.maxsize elements, got %d' % len ( options ) , ) class _enum ( Structure ) : _fiel...
def normalize ( self ) : """Rearrange the conjunction to a conventional form . This puts any coreference ( s ) first , followed by type terms , then followed by AVM ( s ) ( including lists ) . AVMs are normalized via : meth : ` AVM . normalize ` ."""
corefs = [ ] types = [ ] avms = [ ] for term in self . _terms : if isinstance ( term , TypeTerm ) : types . append ( term ) elif isinstance ( term , AVM ) : term . normalize ( ) avms . append ( term ) elif isinstance ( term , Coreference ) : corefs . append ( term ) else ...
def secure_required ( view_func ) : """Decorator to switch an url from http to https . If a view is accessed through http and this decorator is applied to that view , than it will return a permanent redirect to the secure ( https ) version of the same view . The decorator also must check that ` ` ACCOUNTS _...
def _wrapped_view ( request , * args , ** kwargs ) : if not request . is_secure ( ) : if defaults . ACCOUNTS_USE_HTTPS : request_url = request . build_absolute_uri ( request . get_full_path ( ) ) secure_url = request_url . replace ( 'http://' , 'https://' ) return HttpRes...
def mock_attr ( self , * args , ** kwargs ) : """Empty method to call to slurp up args and kwargs . ` args ` get pushed onto the url path . ` kwargs ` are converted to a query string and appended to the URL ."""
self . path . extend ( args ) self . qs . update ( kwargs ) return self
def check_chain ( chain ) : """Verify a merkle chain to see if the Merkle root can be reproduced ."""
link = chain [ 0 ] [ 0 ] for i in range ( 1 , len ( chain ) - 1 ) : if chain [ i ] [ 1 ] == 'R' : link = hash_function ( link + chain [ i ] [ 0 ] ) . digest ( ) elif chain [ i ] [ 1 ] == 'L' : link = hash_function ( chain [ i ] [ 0 ] + link ) . digest ( ) else : raise MerkleError ( '...
def when2 ( fn , * args , ** kwargs ) : """Stub a function call with the given arguments Exposes a more pythonic interface than : func : ` when ` . See : func : ` when ` for more documentation . Returns ` AnswerSelector ` interface which exposes ` thenReturn ` , ` thenRaise ` , and ` thenAnswer ` as usual ....
obj , name = get_obj_attr_tuple ( fn ) theMock = _get_mock ( obj , strict = True ) return invocation . StubbedInvocation ( theMock , name ) ( * args , ** kwargs )
def _distinct ( row1 , row2 ) : """Returns a list of distinct ( or none overlapping ) intervals if two intervals are overlapping . Returns None if the two intervals are none overlapping . The list can have 2 or 3 intervals . : param tuple [ int , int ] row1 : The first interval . : param tuple [ int , int ] r...
relation = Allen . relation ( row1 [ 0 ] , row1 [ 1 ] , row2 [ 0 ] , row2 [ 1 ] ) if relation is None : # One of the 2 intervals is invalid . return [ ] if relation == Allen . X_BEFORE_Y : # row1 : | - - - - | # row2 : | - - - - - | return None # [ ( row1[0 ] , row1[1 ] ) , ( row2[0 ] , row2[1 ] ) ] if relation...
def _find_valid_index ( self , how ) : """Retrieves the index of the first valid value . Parameters how : { ' first ' , ' last ' } Use this parameter to change between the first or last valid index . Returns idx _ first _ valid : type of index"""
assert how in [ 'first' , 'last' ] if len ( self ) == 0 : # early stop return None is_valid = ~ self . isna ( ) if self . ndim == 2 : is_valid = is_valid . any ( 1 ) # reduce axis 1 if how == 'first' : idxpos = is_valid . values [ : : ] . argmax ( ) if how == 'last' : idxpos = len ( self ) - 1 - is_vali...
def find_iteration ( url : Union [ methods , str ] , itermode : Optional [ str ] = None , iterkey : Optional [ str ] = None , ) -> Tuple [ str , str ] : """Find iteration mode and iteration key for a given : class : ` slack . methods ` Args : url : : class : ` slack . methods ` or string url itermode : Custom...
if isinstance ( url , methods ) : if not itermode : itermode = url . value [ 1 ] if not iterkey : iterkey = url . value [ 2 ] if not iterkey or not itermode : raise ValueError ( "Iteration not supported for: {}" . format ( url ) ) elif itermode not in ITERMODE : raise ValueError ( "Itera...
def substitute ( self , text , subvars = { } , trim_leading_lf = None , checkmissing = None ) : '''substitute variables in a string'''
if trim_leading_lf is None : trim_leading_lf = self . trim_leading_lf if checkmissing is None : checkmissing = self . checkmissing # handle repititions while True : subidx = text . find ( self . start_rep_token ) if subidx == - 1 : break endidx = self . find_rep_end ( text [ subidx : ] ) ...
def date_time ( name = None ) : """Creates the grammar for a date and time field , which is a combination of the Date ( D ) and Time or Duration field ( T ) . This field requires first a Date , and then a Time , without any space in between . : param name : name for the field : return : grammar for a Date...
if name is None : name = 'Date and Time Field' date = basic . date ( 'Date' ) time = basic . time ( 'Time' ) date = date . setResultsName ( 'date' ) time = time . setResultsName ( 'time' ) field = pp . Group ( date + time ) field . setParseAction ( lambda d : _combine_date_time ( d [ 0 ] ) ) field . setName ( name ...
def _check_local_option ( self , option ) : """Test the status of local negotiated Telnet options ."""
if not self . telnet_opt_dict . has_key ( option ) : self . telnet_opt_dict [ option ] = TelnetOption ( ) return self . telnet_opt_dict [ option ] . local_option