signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def template ( args ) : "Add or remove templates from site ."
site = Site ( args . PATH ) if args . ACTION == "add" : return site . add_template ( args . TEMPLATE ) return site . remove_template ( args . TEMPLATE )
def unregister ( self , items ) : """Remove items from registry . : param items :"""
items = _listify ( items ) # get all members of Registry except private , special or class meta_names = ( m for m in vars ( self ) . iterkeys ( ) if ( not m . startswith ( '_' ) and m not in dir ( Registry ) ) ) # check that meta names matches # FIXME : this is so lame . replace this with something more robust for m in...
def set_aesthetic ( palette = "yellowbrick" , font = "sans-serif" , font_scale = 1 , color_codes = True , rc = None ) : """Set aesthetic parameters in one step . Each set of parameters can be set directly or temporarily , see the referenced functions below for more information . Parameters palette : string ...
_set_context ( font_scale ) set_style ( rc = { "font.family" : font } ) set_palette ( palette , color_codes = color_codes ) if rc is not None : mpl . rcParams . update ( rc )
def _update_best_params_link ( self ) : """Updates the params . best link to the latest best parameter file ."""
best_params_path = self . best_params_fname actual_best_params_fname = C . PARAMS_NAME % self . state . best_checkpoint if os . path . lexists ( best_params_path ) : os . remove ( best_params_path ) os . symlink ( actual_best_params_fname , best_params_path )
def process_meta ( cls , line , kwargs ) : """Process a line of metadata found in the markdown . Lines are usually in the format of " key : value " . Modify the kwargs dict in order to change or add new kwargs that should be passed to the class ' s constructor ."""
if line . startswith ( 'slug:' ) : kwargs [ 'slug' ] = line [ 5 : ] . strip ( ) elif line . startswith ( 'public:' ) : try : kwargs [ 'public' ] = _str_to_bool ( line [ 7 : ] ) except ValueError : LOG . warning ( 'invalid boolean value for public' , exc_info = True ) elif line . startswith (...
def eq ( self , other ) : """Boolean equal operator ."""
other_node = self . box ( other ) . node return _expr ( exprnode . eq ( self . node , other_node ) )
def _CreatePlacemark ( self , parent , name , style_id = None , visible = True , description = None ) : """Create a KML Placemark element . Args : parent : The parent ElementTree . Element instance . name : The placemark name as a string . style _ id : If not None , the id of a style to use for the placemar...
placemark = ET . SubElement ( parent , 'Placemark' ) placemark_name = ET . SubElement ( placemark , 'name' ) placemark_name . text = name if description is not None : desc_tag = ET . SubElement ( placemark , 'description' ) desc_tag . text = description if style_id is not None : styleurl = ET . SubElement (...
def next_state_fluent_ordering ( self ) -> List [ str ] : '''The list of next state - fluent names in canonical order . Returns : List [ str ] : A list of fluent names .'''
key = lambda x : x . name return [ cpf . name for cpf in sorted ( self . state_cpfs , key = key ) ]
def execute ( self , database , query , properties = None ) : """Executes a query or management command . : param str database : Database against query will be executed . : param str query : Query to be executed . : param azure . kusto . data . request . ClientRequestProperties properties : Optional additiona...
if query . startswith ( "." ) : return self . execute_mgmt ( database , query , properties ) return self . execute_query ( database , query , properties )
def stats ( self ) : """Return dictionay with all stats at this level ."""
assert self . backend . LOAD_count >= 0 , "LOAD_count < 0" assert self . backend . LOAD_byte >= 0 , "LOAD_byte < 0" assert self . backend . STORE_count >= 0 , "STORE_count < 0" assert self . backend . STORE_byte >= 0 , "STORE_byte < 0" assert self . backend . HIT_count >= 0 , "HIT_count < 0" assert self . backend . HIT...
def _make_fits ( self ) : """Generates the data fits for any variables set for fitting in the shell ."""
a = self . tests [ self . active ] args = self . curargs # We need to generate a fit for the data if there are any fits specified . if len ( args [ "fits" ] ) > 0 : for fit in list ( args [ "fits" ] . keys ( ) ) : a . fit ( args [ "independent" ] , fit , args [ "fits" ] [ fit ] , args [ "threshold" ] , args...
def calc_correction ( volt1 , volt2 , volt3 ) : """Remove the temperature effect from field data using inversion results of that data : print ( volt [ 0 ] ) d _ obs ^ TC = d _ obs + ( d _ est ^ TC - d _ est ) Parameters d _ obs : measured field data to correct ( volt1) d _ est : synthetic data of in...
volt = np . array ( [ a - b + c for a , b , c in zip ( volt1 , volt2 , volt3 ) ] ) volt [ np . where ( volt < 0 ) ] = 0.000001 return volt
def threshold_monitor_hidden_threshold_monitor_security_pause ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) threshold_monitor_hidden = ET . SubElement ( config , "threshold-monitor-hidden" , xmlns = "urn:brocade.com:mgmt:brocade-threshold-monitor" ) threshold_monitor = ET . SubElement ( threshold_monitor_hidden , "threshold-monitor" ) security = ET . SubElement ( threshold_monitor , "securi...
def range ( self , x_data = None ) : """Generate the upper and lower bounds of a distribution . Args : x _ data ( numpy . ndarray ) : The bounds might vary over the sample space . By providing x _ data you can specify where in the space the bound should be taken . If omitted , a ( pseudo - ) random sample...
if x_data is None : try : x_data = evaluation . evaluate_inverse ( self , numpy . array ( [ [ 0.5 ] ] * len ( self ) ) ) except StochasticallyDependentError : x_data = approximation . find_interior_point ( self ) shape = ( len ( self ) , ) if hasattr ( self , "_range" ) : return ...
def image ( self , image ) : """Set buffer to value of Python Imaging Library image . The image should be in 1 bit mode and a size equal to the display size ."""
if image . mode != '1' : raise ValueError ( 'Image must be in mode 1.' ) imwidth , imheight = image . size if imwidth != self . width or imheight != self . height : raise ValueError ( 'Image must be same dimensions as display ({0}x{1}).' . format ( self . width , self . height ) ) print ( "bitmap display: image...
def bet_cancel ( self , bet_to_cancel , account = None , ** kwargs ) : """Cancel a bet : param str bet _ to _ cancel : The identifier that identifies the bet to cancel : param str account : ( optional ) the account that owns the bet ( defaults to ` ` default _ account ` ` )"""
if not account : if "default_account" in self . config : account = self . config [ "default_account" ] if not account : raise ValueError ( "You need to provide an account" ) account = Account ( account ) bet = Bet ( bet_to_cancel ) op = operations . Bet_cancel ( ** { "fee" : { "amount" : 0 , "asset_id" ...
def on_button_release ( self , event ) : """Select or deselect rubber banded groups of items The selection of elements is prior and never items are selected or deselected at the same time ."""
self . queue_draw ( self . view ) x0 , y0 , x1 , y1 = self . x0 , self . y0 , self . x1 , self . y1 rectangle = ( min ( x0 , x1 ) , min ( y0 , y1 ) , abs ( x1 - x0 ) , abs ( y1 - y0 ) ) selected_items = self . view . get_items_in_rectangle ( rectangle , intersect = False ) self . view . handle_new_selection ( selected_...
def strip_prompt ( self , a_string ) : """Strip the trailing router prompt from the output . : param a _ string : Returned string from device : type a _ string : str"""
response_list = a_string . split ( self . RESPONSE_RETURN ) last_line = response_list [ - 1 ] if self . base_prompt in last_line : return self . RESPONSE_RETURN . join ( response_list [ : - 1 ] ) else : return a_string
def main ( argv = None ) : """script main . parses command line options in sys . argv , unless * argv * is given ."""
if argv is None : argv = sys . argv # setup command line parser parser = U . OptionParser ( version = "%prog version: $Id$" , usage = usage , description = globals ( ) [ "__doc__" ] ) group = U . OptionGroup ( parser , "count-specific options" ) parser . add_option ( "--wide-format-cell-counts" , dest = "wide_forma...
def _mktemp ( self ) : """Create a temporary file on the same filesystem as self . association _ dir . The temporary directory should not be cleaned if there are any processes using the store . If there is no active process using the store , it is safe to remove all of the files in the temporary directory...
fd , name = mkstemp ( dir = self . temp_dir ) try : file_obj = os . fdopen ( fd , 'wb' ) return file_obj , name except : _removeIfPresent ( name ) raise
def query_pending_jobs ( auth , repo_name = None , return_raw = False ) : """Return pending jobs"""
url = '%s/pending?format=json' % HOST_ROOT LOG . debug ( 'About to fetch %s' % url ) req = requests . get ( url , auth = auth , timeout = TCP_TIMEOUT ) # If the revision doesn ' t exist on buildapi , that means there are # no builapi jobs for this revision if req . status_code not in [ 200 ] : return [ ] raw = req ...
def get_end_offset ( self , value , parent = None , index = None ) : """Return the end offset of the Field ' s data . Useful for chainloading . value Input Python object to process . parent Parent block object where this Field is defined . Used for e . g . evaluating Refs . index Index of the Python o...
return self . get_start_offset ( value , parent , index ) + self . get_size ( value , parent , index )
def fix_workflow_transitions ( portal ) : """Replace target states from some workflow statuses"""
logger . info ( "Fixing workflow transitions..." ) tochange = [ { 'wfid' : 'bika_duplicateanalysis_workflow' , 'trid' : 'submit' , 'changes' : { 'new_state_id' : 'to_be_verified' , 'guard_expr' : '' } , 'update' : { 'catalog' : CATALOG_ANALYSIS_LISTING , 'portal_type' : 'DuplicateAnalysis' , 'status_from' : 'attachment...
def _handle_tasks_insert ( self , batch_size = None ) : """Convert all Async ' s into tasks , then insert them into queues ."""
if self . _tasks_inserted : raise errors . ContextAlreadyStartedError ( "This Context has already had its tasks inserted." ) task_map = self . _get_tasks_by_queue ( ) # QUESTION : Should the persist happen before or after the task # insertion ? I feel like this is something that will alter the # behavior of the tas...
def generate_matches ( self , nodes ) : """Generator yielding all matches for this pattern . Default implementation for non - wildcard patterns ."""
r = { } if nodes and self . match ( nodes [ 0 ] , r ) : yield 1 , r
def process_result_value ( self , value , dialect ) : """SQLAlchemy uses this to convert a string into a SourceLocation object . We separate the fields by a |"""
if value is None : return None p = value . split ( "|" ) if len ( p ) == 0 : return None return SourceLocation ( * map ( int , p ) )
def _create_tmp_input ( input_bams , names , tmp_path , config ) : """Create input file for pindel . tab file : bam file , insert size , name : param input _ bams : ( list ) bam files : param names : ( list ) names of samples : param tmp _ path : ( str ) temporal dir : param config : ( dict ) information fr...
tmp_input = os . path . join ( tmp_path , "pindel.txt" ) with open ( tmp_input , 'w' ) as out_handle : for bam_file , name in zip ( input_bams , names ) : print ( "%s\t%s\t%s\n" % ( bam_file , 250 , name ) , file = out_handle ) return tmp_input
def argrelextrema ( data , comparator , axis = 0 , order = 1 , mode = 'clip' ) : """Calculate the relative extrema of ` data ` . . . versionadded : : 0.11.0 Parameters data : ndarray Array in which to find the relative extrema . comparator : callable Function to use to compare two data points . Should...
results = _boolrelextrema ( data , comparator , axis , order , mode ) if ~ results . any ( ) : return ( np . array ( [ ] ) , ) * 2 else : return np . where ( results )
def setConfiguration ( self , configuration ) : r"""Set the active configuration of a device . Arguments : configuration : a configuration value or a Configuration object ."""
if isinstance ( configuration , Configuration ) : configuration = configuration . value self . dev . set_configuration ( configuration )
def CheckLineLength ( filename , linenumber , clean_lines , errors ) : """Check for lines longer than the recommended length"""
line = clean_lines . raw_lines [ linenumber ] if len ( line ) > _lint_state . linelength : return errors ( filename , linenumber , 'linelength' , 'Lines should be <= %d characters long' % ( _lint_state . linelength ) )
def setSizeMetadata ( self , size ) : """Set size image metadata to what has been reliably identified ."""
assert ( ( self . needMetadataUpdate ( CoverImageMetadata . SIZE ) ) or ( self . size == size ) ) self . size = size self . check_metadata &= ~ CoverImageMetadata . SIZE
def find_missing_modules ( ) : """look for dependency that setuptools cannot check or that are too painful to install with setuptools"""
missing_modules = [ ] for module in MODULES : try : __import__ ( module [ 1 ] ) except ImportError : missing_modules . append ( module ) return missing_modules
def absolute_charindex ( self , string , start , end ) : """Finds the absolute character index of the specified regex match start and end indices in the * buffer * refstring ."""
search = string [ start : end ] abs_start = self . refstring . index ( search ) return abs_start , ( end - start ) + abs_start
def _wrapped_cardinality ( x , y , bits ) : """Return the cardinality for a set of number ( | x , y | ) on the wrapped - interval domain . : param x : The first operand ( an integer ) : param y : The second operand ( an integer ) : return : The cardinality"""
if x == ( ( y + 1 ) % ( 2 ** bits ) ) : return 2 ** bits else : return ( ( y - x ) + 1 ) & ( 2 ** bits - 1 )
def rollback ( using = None ) : """This function does the rollback itself and resets the dirty flag ."""
if using is None : for using in tldap . backend . connections : connection = tldap . backend . connections [ using ] connection . rollback ( ) return connection = tldap . backend . connections [ using ] connection . rollback ( )
def aquireMs1CalibrationData ( msrunContainer , specfile , siiArrays = None , lockMass = None , ** kwargs ) : """Aquire mass error data , observed vs expected m / z , for calibration of MS1 ion m / z values . Expected m / z values can be of ambient ions with known exact masses and from identified precursor mass...
scanRange = kwargs . get ( 'scanRange' , [ - 1 , 0 , 1 ] ) massTolerance = kwargs . get ( 'massTolerance' , 10 * 1e-6 ) toleranceMode = kwargs . get ( 'toleranceMode' , 'relative' ) topIntMatches = kwargs . get ( 'topIntMatches' , False ) useTopIntIons = kwargs . get ( 'useTopIntIons' , False ) ms1Arrays = msrunContain...
def icon_cache_key ( method , self , brain_or_object ) : """Generates a cache key for the icon lookup Includes the virtual URL to handle multiple HTTP / HTTPS domains Example : http : / / senaite . local / clients ? modified = 1512033263370"""
url = api . get_url ( brain_or_object ) modified = api . get_modification_date ( brain_or_object ) . millis ( ) key = "{}?modified={}" . format ( url , modified ) logger . debug ( "Generated Cache Key: {}" . format ( key ) ) return key
def add_noise_to_dict_values ( dictionary : Dict [ A , float ] , noise_param : float ) -> Dict [ A , float ] : """Returns a new dictionary with noise added to every key in ` ` dictionary ` ` . The noise is uniformly distributed within ` ` noise _ param ` ` percent of the value for every value in the dictionary ...
new_dict = { } for key , value in dictionary . items ( ) : noise_value = value * noise_param noise = random . uniform ( - noise_value , noise_value ) new_dict [ key ] = value + noise return new_dict
def main ( ) : """Run playbook"""
for flag in ( '--check' , ) : if flag not in sys . argv : sys . argv . append ( flag ) obj = PlaybookCLI ( sys . argv ) obj . parse ( ) obj . run ( )
def clearView ( self , fillColor = 0 ) : """\~english Clear up canvas with view size @ param fillColor : a color value @ note The fillColor value range depends on the setting of _ buffer _ color _ mode . * If it is SS _ COLOR _ MODE _ MONO ( " 1 " ) monochrome mode , it can only select 0 : black and 1 : w...
self . Canvas . rectangle ( self . View . rectToArray ( ) , outline = 0 , fill = fillColor )
def reduce_cuda ( g , x , axes , dtype ) : """Reductions in CUDA use the thrust library for speed and have limited functionality ."""
if axes != 0 : raise NotImplementedError ( "'axes' keyword is not implemented for CUDA" ) return g ( x , dtype = dtype )
def get_conventional_to_primitive_transformation_matrix ( self , international_monoclinic = True ) : """Gives the transformation matrix to transform a conventional unit cell to a primitive cell according to certain standards the standards are defined in Setyawan , W . , & Curtarolo , S . ( 2010 ) . High - thr...
conv = self . get_conventional_standard_structure ( international_monoclinic = international_monoclinic ) lattice = self . get_lattice_type ( ) if "P" in self . get_space_group_symbol ( ) or lattice == "hexagonal" : return np . eye ( 3 ) if lattice == "rhombohedral" : # check if the conventional representation is h...
def chi_square ( h1 , h2 ) : # 23 us @ array , 49 us @ list \ w 100 r"""Chi - square distance . Measure how unlikely it is that one distribution ( histogram ) was drawn from the other . The Chi - square distance between two histograms : math : ` H ` and : math : ` H ' ` of size : math : ` m ` is defined as : ...
h1 , h2 = __prepare_histogram ( h1 , h2 ) old_err_state = scipy . seterr ( invalid = 'ignore' ) # divide through zero only occurs when the bin is zero in both histograms , in which case the division is 0/0 and leads to ( and should lead to ) 0 result = scipy . square ( h1 - h2 ) / ( h1 + h2 ) scipy . seterr ( ** old_er...
def get_athlete ( self , athlete_id = None ) : """Gets the specified athlete ; if athlete _ id is None then retrieves a detail - level representation of currently authenticated athlete ; otherwise summary - level representation returned of athlete . http : / / strava . github . io / api / v3 / athlete / # get...
if athlete_id is None : raw = self . protocol . get ( '/athlete' ) else : raise NotImplementedError ( "The /athletes/{id} endpoint was removed by Strava. " "See https://developers.strava.com/docs/january-2018-update/" ) # raw = self . protocol . get ( ' / athletes / { athlete _ id } ' , athlete _ id = athl...
def add_arguments ( self , parser ) : """Command arguments ."""
super ( Command , self ) . add_arguments ( parser ) parser . add_argument ( '--badges' , action = 'store' , dest = 'badges' , type = str ) parser . add_argument ( '--db-read' , action = 'store' , dest = 'db_read' , type = str ) parser . add_argument ( '--disable-signals' , action = 'store_true' , dest = 'disable_signal...
def external2internal ( xe , bounds ) : """Convert a series of external variables to internal variables"""
xi = np . empty_like ( xe ) for i , ( v , bound ) in enumerate ( zip ( xe , bounds ) ) : a = bound [ 0 ] # minimum b = bound [ 1 ] # maximum if a == None and b == None : # No constraints xi [ i ] = v elif b == None : # only min xi [ i ] = np . sqrt ( ( v - a + 1. ) ** 2. - 1 ) ...
def _exprparser ( expr , scope , lang = None , conf = None , configurable = None , safe = DEFAULT_SAFE , besteffort = DEFAULT_BESTEFFORT , tostr = False ) : """In charge of parsing an expression and return a python object ."""
if scope is None : scope = { } scope . update ( { 'configurable' : configurable , 'conf' : conf } ) expr = REGEX_EXPR_R . sub ( _refrepl ( configurable = configurable , conf = conf , safe = safe , scope = scope , besteffort = besteffort ) , expr ) result = resolve ( expr = expr , name = lang , safe = safe , scope =...
def normalizer ( text , exclusion = OPERATIONS_EXCLUSION , lower = True , separate_char = '-' , ** kwargs ) : """Clean text string of simbols only alphanumeric chars ."""
clean_str = re . sub ( r'[^\w{}]' . format ( "" . join ( exclusion ) ) , separate_char , text . strip ( ) ) or '' clean_lowerbar = clean_str_without_accents = strip_accents ( clean_str ) if '_' not in exclusion : clean_lowerbar = re . sub ( r'\_' , separate_char , clean_str_without_accents . strip ( ) ) limit_guion...
def get_info ( self , code ) : """Return a dict of information about the currency"""
for i , currency in enumerate ( self . get_currency ( code ) ) : if i == 0 : try : exp = int ( currency . find ( 'CcyMnrUnts' ) . text ) except ValueError : exp = 0 info = { 'CountryNames' : [ ] , 'ISO4217Number' : int ( currency . find ( 'CcyNbr' ) . text ) , 'ISO421...
def _surfdens ( self , R , z , phi = 0. , t = 0. ) : """NAME : _ surfdens PURPOSE : evaluate the surface density INPUT : R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT : Sigma ( R , z ) HISTORY : 2018-08-19 - Written - Bovy ( UofT )"""
return self . _a * ( R ** 2 + self . _a ** 2 ) ** - 1.5 / 2. / nu . pi
def read_handle ( self , handle : int ) -> bytes : """Read a handle from the device . You must be connected to do this ."""
if self . _peripheral is None : raise BluetoothBackendException ( 'not connected to backend' ) return self . _peripheral . readCharacteristic ( handle )
def all ( self , stage = 'login_success' , enabled = True , fields = None , include_fields = True , page = None , per_page = None , include_totals = False ) : """Retrieves a list of all rules . Args : stage ( str , optional ) : Retrieves rules that match the execution stage ( defaults to login _ success ) . ...
params = { 'stage' : stage , 'fields' : fields and ',' . join ( fields ) or None , 'include_fields' : str ( include_fields ) . lower ( ) , 'page' : page , 'per_page' : per_page , 'include_totals' : str ( include_totals ) . lower ( ) } # since the default is True , this is here to disable the filter if enabled is not No...
def prepare_csv_read ( data , field_names , * args , ** kwargs ) : """Prepare various input types for CSV parsing . Args : data ( iter ) : Data to read field _ names ( tuple of str ) : Ordered names to assign to fields Returns : csv . DictReader : CSV reader suitable for parsing Raises : TypeError : I...
if hasattr ( data , 'readlines' ) or isinstance ( data , list ) : pass elif isinstance ( data , basestring ) : data = open ( data ) else : raise TypeError ( 'Unable to handle data of type %r' % type ( data ) ) return csv . DictReader ( data , field_names , * args , ** kwargs )
def query ( self , query ) : '''Returns an iterable of objects matching criteria expressed in ` query ` Naively applies the query operations on the objects within the namespaced collection corresponding to ` ` query . key . path ` ` . Args : query : Query object describing the objects to return . Raturns ...
# entire dataset already in memory , so ok to apply query naively if str ( query . key ) in self . _items : return query ( self . _items [ str ( query . key ) ] . values ( ) ) else : return query ( [ ] )
def RegisterHasher ( cls , hasher_class ) : """Registers a hasher class . The hasher classes are identified based on their lower case name . Args : hasher _ class ( type ) : class object of the hasher . Raises : KeyError : if hasher class is already set for the corresponding name ."""
hasher_name = hasher_class . NAME . lower ( ) if hasher_name in cls . _hasher_classes : raise KeyError ( ( 'hasher class already set for name: {0:s}.' ) . format ( hasher_class . NAME ) ) cls . _hasher_classes [ hasher_name ] = hasher_class
def AsPrimitiveProto ( self ) : """Return an old style protocol buffer object ."""
if self . protobuf : result = self . protobuf ( ) result . ParseFromString ( self . SerializeToString ( ) ) return result
def watched ( self , option ) : """Set whether to filter by a user ' s watchlist . Options available are user . ONLY , user . NOT , and None ; default is None ."""
params = join_params ( self . parameters , { "watched" : option } ) return self . __class__ ( ** params )
def AddClientLabels ( self , client_id , owner , labels ) : """Attaches a user label to a client ."""
if client_id not in self . metadatas : raise db . UnknownClientError ( client_id ) labelset = self . labels . setdefault ( client_id , { } ) . setdefault ( owner , set ( ) ) for l in labels : labelset . add ( utils . SmartUnicode ( l ) )
def sample_posterior ( x , post , nsamples = 1 ) : """Returns nsamples from a tabulated posterior ( not necessarily normalized )"""
cdf = post . cumsum ( ) cdf /= cdf . max ( ) u = rand . random ( size = nsamples ) inds = np . digitize ( u , cdf ) return x [ inds ]
def split_header ( fp ) : """Read file pointer and return pair of lines lists : first - header , second - the rest ."""
body_start , header_ended = 0 , False lines = [ ] for line in fp : if line . startswith ( '#' ) and not header_ended : # Header text body_start += 1 else : header_ended = True lines . append ( line ) return lines [ : body_start ] , lines [ body_start : ]
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : """See : meth : ` superclass method < . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > ` for spec of input and result values ."""
# extracting dictionary of coefficients specific to required # intensity measure type . C = self . COEFFS [ imt ] # Implements mean model ( equation 12) mean = ( self . _compute_magnitude ( rup , C ) + self . _compute_distance ( dists , C ) + self . _get_site_amplification ( sites , rup , C ) + self . _get_mechanism ( ...
def handle_delete_key ( self ) : """Read incoming delete key event from server"""
track_id = self . reader . int ( ) row = self . reader . int ( ) logger . info ( " -> track=%s, row=%s" , track_id , row ) # Delete the actual track value track = self . tracks . get_by_id ( track_id ) track . delete ( row )
def column ( * args , ** kwargs ) : """Create a column of Bokeh Layout objects . Forces all objects to have the same sizing _ mode , which is required for complex layouts to work . Args : children ( list of : class : ` ~ bokeh . models . layouts . LayoutDOM ` ) : A list of instances for the column . Can be ...
sizing_mode = kwargs . pop ( 'sizing_mode' , None ) children = kwargs . pop ( 'children' , None ) children = _handle_children ( * args , children = children ) col_children = [ ] for item in children : if isinstance ( item , LayoutDOM ) : if sizing_mode is not None and _has_auto_sizing ( item ) : ...
def mean_return_by_quantile ( factor_data , by_date = False , by_group = False , demeaned = True , group_adjust = False ) : """Computes mean returns for factor quantiles across provided forward returns columns . Parameters factor _ data : pd . DataFrame - MultiIndex A MultiIndex DataFrame indexed by date ( ...
if group_adjust : grouper = [ factor_data . index . get_level_values ( 'date' ) ] + [ 'group' ] factor_data = utils . demean_forward_returns ( factor_data , grouper ) elif demeaned : factor_data = utils . demean_forward_returns ( factor_data ) else : factor_data = factor_data . copy ( ) grouper = [ 'fac...
def _extract_apis_from_events ( function_logical_id , serverless_function_events , collector ) : """Given an AWS : : Serverless : : Function Event Dictionary , extract out all ' Api ' events and store within the collector Parameters function _ logical _ id : str LogicalId of the AWS : : Serverless : : Funct...
count = 0 for _ , event in serverless_function_events . items ( ) : if SamApiProvider . _FUNCTION_EVENT_TYPE_API == event . get ( SamApiProvider . _TYPE ) : api_resource_id , api = SamApiProvider . _convert_event_api ( function_logical_id , event . get ( "Properties" ) ) collector . add_apis ( api_r...
def tag_array ( events ) : """Return a numpy array mapping events to tags - Rows corresponds to events - Columns correspond to tags"""
all_tags = sorted ( set ( tag for event in events for tag in event . tags ) ) array = np . zeros ( ( len ( events ) , len ( all_tags ) ) ) for row , event in enumerate ( events ) : for tag in event . tags : array [ row , all_tags . index ( tag ) ] = 1 return array
async def get_ssh_key ( self , raw_ssh = False ) : """Return known SSH keys for this model . : param bool raw _ ssh : if True , returns the raw ssh key , else it ' s fingerprint"""
key_facade = client . KeyManagerFacade . from_connection ( self . connection ( ) ) entity = { 'tag' : tag . model ( self . info . uuid ) } entities = client . Entities ( [ entity ] ) return await key_facade . ListKeys ( entities , raw_ssh )
def get_random_mass_point_particles ( numPoints , massRangeParams ) : """This function will generate a large set of points within the chosen mass and spin space . It will also return the corresponding PN spin coefficients for ease of use later ( though these may be removed at some future point ) . Parameters ...
# WARNING : We expect mass1 > mass2 ALWAYS # First we choose the total masses from a unifrom distribution in mass # to the - 5/3 . power . mass = numpy . random . random ( numPoints ) * ( massRangeParams . minTotMass ** ( - 5. / 3. ) - massRangeParams . maxTotMass ** ( - 5. / 3. ) ) + massRangeParams . maxTotMass ** ( ...
def get_kinto_records ( kinto_client , bucket , collection , permissions , config = None ) : """Return all the kinto records for this bucket / collection ."""
# Create bucket if needed try : kinto_client . create_bucket ( id = bucket , if_not_exists = True ) except KintoException as e : if hasattr ( e , 'response' ) and e . response . status_code == 403 : # The user cannot create buckets on this server , ignore the creation . pass try : kinto_client . cre...
def do_ephemeral_endpoint ( self , params ) : """\x1b [1mNAME \x1b [0m ephemeral _ endpoint - Gets the ephemeral znode owner ' s session and ip : port \x1b [1mSYNOPSIS \x1b [0m ephemeral _ endpoint < path > < hosts > [ recursive ] [ reverse _ lookup ] \x1b [1mDESCRIPTION \x1b [0m hosts is a list of hosts ...
if invalid_hosts ( params . hosts ) : self . show_output ( "List of hosts has the wrong syntax." ) return stat = self . _zk . exists ( params . path ) if stat is None : self . show_output ( "%s is gone." , params . path ) return if not params . recursive and stat . ephemeralOwner == 0 : self . show_...
def read_settings ( filename = None , defs = None ) : """: param filename : Force load a file : param defs : arguments you want to accept : param default _ filename : A config file from an environment variable ( a fallback config file , if no other provided ) : return :"""
# READ SETTINGS defs = listwrap ( defs ) defs . append ( { "name" : [ "--config" , "--settings" , "--settings-file" , "--settings_file" ] , "help" : "path to JSON file with settings" , "type" : str , "dest" : "filename" , "default" : None , "required" : False } ) args = argparse ( defs ) args . filename = coalesce ( fi...
def initialize_plugins ( self ) : """Attempt to Load and initialize all the plugins . Any issues loading plugins will be output to stderr ."""
for plugin_name in self . options . plugin : parts = plugin_name . split ( '.' ) if len ( parts ) > 1 : module_name = '.' . join ( parts [ : - 1 ] ) class_name = parts [ - 1 ] else : # Use the titlecase format of the module name as the class name module_name = parts [ 0 ] cla...
def _check_rel ( attrs , rel_whitelist , rel_blacklist ) : """Check a link ' s relations against the whitelist or blacklist . First , this will reject based on blacklist . Next , if there is a whitelist , there must be at least one rel that matches . To explicitly allow links without a rel you can add None to...
rels = attrs . get ( 'rel' , [ None ] ) if rel_blacklist : # Never return True for a link whose rel appears in the blacklist for rel in rels : if rel in rel_blacklist : return False if rel_whitelist : # If there is a whitelist for rels , only return true for a rel that # appears in it for re...
def cancel ( self ) : """Instruct the cluster to cancel the running job . Has no effect if job is not running"""
if self . status > COMPLETED : return cmd = self . backend . cmd_cancel ( self ) self . _run_cmd ( cmd , self . remote , ignore_exit_code = True , ssh = self . ssh ) self . _status = CANCELLED self . dump ( )
def add_map ( self , counters_map ) : """Add all counters from the map . For each counter in the passed map , adds its value to the counter in this map . Args : counters _ map : CounterMap instance to add ."""
for counter_name in counters_map . counters : self . increment ( counter_name , counters_map . counters [ counter_name ] )
def getNextPID ( self , numPIDs = None , namespace = None ) : """Wrapper function for ` Fedora REST API getNextPid < http : / / fedora - commons . org / confluence / display / FCR30 / REST + API # RESTAPI - getNextPID > ` _ : param numPIDs : ( optional ) get the specified number of pids ; by default , returns 1...
http_args = { 'format' : 'xml' } if numPIDs : http_args [ 'numPIDs' ] = numPIDs if namespace : http_args [ 'namespace' ] = namespace rel_url = 'objects/nextPID' return self . post ( rel_url , params = http_args )
def bulk_delete ( self , * filters_or_records ) : """Shortcut to bulk delete records . . versionadded : : 2.17.0 Args : * filters _ or _ records ( tuple ) or ( Record ) : Either a list of Records , or a list of filters . Notes : Requires Swimlane 2.17 + Examples : # Bulk delete records by filter app...
_type = validate_filters_or_records ( filters_or_records ) data_dict = { } # build record _ id list if _type is Record : record_ids = [ ] for record in filters_or_records : record_ids . append ( record . id ) data_dict [ 'recordIds' ] = record_ids # build filters else : filters = [ ] record_...
def cal_k_vinet ( p , k ) : """calculate bulk modulus in GPa : param p : pressure in GPa : param k : [ v0 , k0 , k0p ] : return : bulk modulus at high pressure in GPa"""
v = cal_v_vinet ( p , k ) return cal_k_vinet_from_v ( v , k [ 0 ] , k [ 1 ] , k [ 2 ] )
def minter ( record_uuid , data , pid_type , key ) : """Mint PIDs for a record ."""
pid = PersistentIdentifier . create ( pid_type , data [ key ] , object_type = 'rec' , object_uuid = record_uuid , status = PIDStatus . REGISTERED ) for scheme , identifier in data [ 'identifiers' ] . items ( ) : if identifier : PersistentIdentifier . create ( scheme , identifier , object_type = 'rec' , obje...
def all_equal ( left , right , cache = None ) : """Check whether two objects ` left ` and ` right ` are equal . Parameters left : Union [ object , Expr , Node ] right : Union [ object , Expr , Node ] cache : Optional [ Dict [ Tuple [ Node , Node ] , bool ] ] A dictionary indicating whether two Nodes are e...
if cache is None : cache = { } if util . is_iterable ( left ) : # check that left and right are equal length iterables and that all # of their elements are equal return ( util . is_iterable ( right ) and len ( left ) == len ( right ) and all ( itertools . starmap ( functools . partial ( all_equal , cache = cach...
def _get_fields ( ast ) : """Return a list of vertex fields , and a list of property fields , for the given AST node . Also verifies that all property fields for the AST node appear before all vertex fields , raising GraphQLCompilationError if that is not the case . Args : ast : GraphQL AST node , obtained ...
if not ast . selection_set : # There are no child fields . return [ ] , [ ] property_fields = [ ] vertex_fields = [ ] seen_field_names = set ( ) switched_to_vertices = False # Ensures that all property fields are before all vertex fields . for field_ast in ast . selection_set . selections : if not isinstance ( ...
def base_parser ( ) : """Create arguments parser with basic options and no help message . * - c , - - config : load configuration file . * - v , - - verbose : increase logging verbosity . ` - v ` , ` - vv ` , and ` - vvv ` . * - q , - - quiet : quiet logging except critical level . * - o , - - output : outp...
parser = argparse . ArgumentParser ( add_help = False ) parser . add_argument ( "-c" , "--config" , dest = "config" , type = argparse . FileType ( 'r' ) , metavar = "FILE" , help = "configuration file" ) parser . add_argument ( "-o" , "--output" , dest = "output" , type = argparse . FileType ( 'w' ) , metavar = "FILE" ...
def once ( func ) : """Decorate func so it ' s only ever called the first time . This decorator can ensure that an expensive or non - idempotent function will not be expensive on subsequent calls and is idempotent . > > > add _ three = once ( lambda a : a + 3) > > > add _ three ( 3) > > > add _ three ( 9)...
@ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : if not hasattr ( wrapper , 'saved_result' ) : wrapper . saved_result = func ( * args , ** kwargs ) return wrapper . saved_result wrapper . reset = lambda : vars ( wrapper ) . __delitem__ ( 'saved_result' ) return wrapper
def clean ( ctx ) : """Clean previously built package artifacts ."""
clean_command = "python setup.py clean" report . info ( ctx , "package.clean" , "cleaning up built package artifacts" ) ctx . run ( clean_command ) egg_name = f"{ctx.metadata['package_name']}.egg-info" report . info ( ctx , "pacakge.clean" , "removing build directories" ) for artifact in ( "dist" , "build" , egg_name ,...
def _refresh ( self , session , stopping = False ) : '''Get this task ' s current state . This must be called under the registry ' s lock . It updates the : attr : ` finished ` and : attr : ` failed ` flags and the : attr : ` data ` dictionary based on the current state in the registry . In the normal cas...
data = session . get ( WORK_UNITS_ + self . work_spec_name + _FINISHED , self . key ) if data is not None : self . finished = True self . data = data if not stopping : raise LostLease ( 'work unit is already finished' ) return self . finished = False data = session . get ( WORK_UNITS_ + self . w...
def _rapRperiAxiFindStart ( R , E , L , pot , rap = False , startsign = 1. ) : """NAME : _ rapRperiAxiFindStart PURPOSE : Find adequate start or end points to solve for rap and rperi INPUT : R - Galactocentric radius E - energy L - angular momentum pot - potential rap - if True , find the rap end ...
if rap : rtry = 2. * R else : rtry = R / 2. while startsign * _rapRperiAxiEq ( rtry , E , L , pot ) > 0. and rtry > 0.000000001 : if rap : if rtry > 100. : # pragma : no cover raise UnboundError ( "Orbit seems to be unbound" ) rtry *= 2. else : rtry /= 2. if rtry < 0....
def replace_uri ( rdf , fromuri , touri ) : """Replace all occurrences of fromuri with touri in the given model . If touri is a list or tuple of URIRef , all values will be inserted . If touri = None , will delete all occurrences of fromuri instead ."""
replace_subject ( rdf , fromuri , touri ) replace_predicate ( rdf , fromuri , touri ) replace_object ( rdf , fromuri , touri )
def get_annotations ( self ) -> Dict : """Get the current annotations ."""
return { EVIDENCE : self . evidence , CITATION : self . citation . copy ( ) , ANNOTATIONS : self . annotations . copy ( ) }
def create_entity ( self ) : """Create entity if ` flow _ collection ` is defined in process . Following rules applies for adding ` Data ` object to ` Entity ` : * Only add ` Data object ` to ` Entity ` if process has defined ` flow _ collection ` field * Add object to existing ` Entity ` , if all parents t...
entity_type = self . process . entity_type # pylint : disable = no - member entity_descriptor_schema = self . process . entity_descriptor_schema # pylint : disable = no - member entity_input = self . process . entity_input # pylint : disable = no - member if entity_type : data_filter = { } if entity_input : ...
async def finalize_request ( self , result : ResponseReturnValue , request_context : Optional [ RequestContext ] = None , from_error_handler : bool = False , ) -> Response : """Turns the view response return value into a response . Arguments : result : The result of the request to finalize into a response . r...
response = await self . make_response ( result ) try : response = await self . process_response ( response , request_context ) await request_finished . send ( self , response = response ) except Exception : if not from_error_handler : raise self . logger . exception ( 'Request finalizing errored...
def reset_input_generators ( self , seed ) : """Helper method which explicitly resets all input generators to the derived generator . This should only ever be called for testing or debugging ."""
seed_generator = SeedGenerator ( ) . reset ( seed = seed ) for gen in self . input_generators : gen . reset ( next ( seed_generator ) ) try : # In case ` gen ` is itself a derived generator , # recursively reset its own input generators . gen . reset_input_generators ( next ( seed_generator ) ) ...
def _get_disksize_MiB ( iLOIP , cred ) : """Reads the dictionary of parsed MIBs and gets the disk size . : param iLOIP : IP address of the server on which SNMP discovery has to be executed . : param snmp _ credentials in a dictionary having following mandatory keys . auth _ user : SNMP user auth _ proto...
# '1.3.6.1.4.1.232.5.5.1.1 ' , # cpqscsi SAS HBA Table # '1.3.6.1.4.1.232.3.2.3.1 ' , # cpqida Drive Array Logical Drive Table result = _parse_mibs ( iLOIP , cred ) disksize = { } for uuid in sorted ( result ) : for key in result [ uuid ] : # We only track the Physical Disk Size if key . find ( 'PhyDrvSize'...
def cascaded_union ( cls , vectors , dst_crs , prevalidate = False ) : # type : ( list , CRS , bool ) - > GeoVector """Generate a GeoVector from the cascade union of the impute vectors ."""
try : shapes = [ geometry . get_shape ( dst_crs ) for geometry in vectors ] if prevalidate : if not all ( [ sh . is_valid for sh in shapes ] ) : warnings . warn ( "Some invalid shapes found, discarding them." ) except IndexError : crs = DEFAULT_CRS shapes = [ ] return cls ( cascaded_...
def descent ( self ) : """Returns descent of workout in meters"""
total_descent = 0.0 altitude_data = self . altitude_points ( ) for i in range ( len ( altitude_data ) - 1 ) : diff = altitude_data [ i + 1 ] - altitude_data [ i ] if diff < 0.0 : total_descent += abs ( diff ) return total_descent
def save_block_to_crt ( filename , group , norrec = 'all' , store_errors = False ) : """Save a dataset to a CRTomo - compatible . crt file Parameters filename : string Output filename group : pandas . group Data group norrec : string Which data to export Possible values : all | nor | rec store _ err...
if norrec != 'all' : group = group . query ( 'norrec == "{0}"' . format ( norrec ) ) # todo : we need to fix the global naming scheme for columns ! with open ( filename , 'wb' ) as fid : fid . write ( bytes ( '{0}\n' . format ( len ( group ) ) , 'UTF-8' ) ) AB = group [ 'a' ] * 1e4 + group [ 'b' ] MN = ...
def sens_from_spec ( spec , labels , scores , * args , ** kwargs ) : r"""Find the sensitivity that corresponds to the indicated specificity ( ROC function ) sensitivity = Num _ True _ Positive / ( Num _ True _ Postive + Num _ False _ Negative ) specificity = Num _ True _ Negative / ( Num _ True _ Negative + Num...
thresh = thresh_from_spec ( spec , labels , scores ) df = pd . DataFrame ( list ( zip ( labels , scores [ scores > thresh ] . astype ( int ) ) ) ) c = Confusion ( df , * args , ** kwargs ) return c . _binary_sensitivity
def _highest_perm_dict_from_perm_dict ( self , perm_dict ) : """Return a perm _ dict where only the highest permission for each subject is included ."""
highest_perm_dict = copy . copy ( perm_dict ) for ordered_str in reversed ( ORDERED_PERM_LIST ) : for lower_perm in self . _lower_perm_list ( ordered_str ) : highest_perm_dict . setdefault ( lower_perm , set ( ) ) highest_perm_dict [ lower_perm ] -= perm_dict . get ( ordered_str , set ( ) ) return h...
def apply_widget_invalid_options ( self , field_name ) : """Applies additional widget options for an invalid field . This method is called when there is some error on a field to apply additional options on its widget . It does the following : * Sets the aria - invalid property of the widget for accessibility ...
field = self . fields [ field_name ] class_name = self . get_widget_invalid_css_class ( field_name , field ) if class_name : field . widget . attrs [ 'class' ] = join_css_class ( field . widget . attrs . get ( 'class' , None ) , class_name ) field . widget . attrs [ 'aria-invalid' ] = 'true'
def notify_exception_handler ( * args ) : """Provides a notifier exception handler . : param \ * args : Arguments . : type \ * args : \ * : return : Definition success . : rtype : bool"""
callback = RuntimeGlobals . components_manager [ "factory.script_editor" ] . restore_development_layout foundations . exceptions . base_exception_handler ( * args ) cls , instance = foundations . exceptions . extract_exception ( * args ) [ : 2 ] RuntimeGlobals . notifications_manager . exceptify ( message = "{0}" . for...
def calc_riseset ( t , target_name , location , prev_next , rise_set , horizon ) : """Time at next rise / set of ` ` target ` ` . Parameters t : ` ~ astropy . time . Time ` or other ( see below ) Time of observation . This will be passed in as the first argument to the ` ~ astropy . time . Time ` initialize...
target = coord . get_body ( target_name , t ) t0 = _rise_set_trig ( t , target , location , prev_next , rise_set ) grid = t0 + np . linspace ( - 4 * u . hour , 4 * u . hour , 10 ) altaz_frame = coord . AltAz ( obstime = grid , location = location ) target = coord . get_body ( target_name , grid ) altaz = target . trans...