signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def zrem ( self , key , * members ) : """Removes the specified members from the sorted set stored at key . Non existing members are ignored . An error is returned when key exists and does not hold a sorted set . . . note : : * * Time complexity * * : ` ` O ( M * log ( N ) ) ` ` with ` ` N ` ` being the numb...
return self . _execute ( [ b'ZREM' , key ] + list ( members ) )
def _method_error_handler ( self , response : Dict [ str , Any ] ) : """处理400 ~ 499段状态码 , 为对应的任务设置异常 . Parameters : s ( response ) : - 响应的python字典形式数据 Return : ( bool ) : - 准确地说没有错误就会返回True"""
exp = response . get ( 'MESSAGE' ) code = response . get ( "CODE" ) ID = exp . get ( "ID" ) e = abort ( code , ID = ID , message = exp . get ( 'MESSAGE' ) ) self . tasks [ ID ] . set_exception ( e ) return True
def find ( self , selector : str = '*' , containing : _Containing = None , first : bool = False , _encoding : str = None ) -> _Find : """Given a simple element name , returns a list of : class : ` Element < Element > ` objects or a single one . : param selector : Element name to find . : param containing : If...
# Convert a single containing into a list . if isinstance ( containing , str ) : containing = [ containing ] encoding = _encoding or self . encoding elements = [ Element ( element = found , default_encoding = encoding ) for found in self . pq ( selector ) ] if containing : elements_copy = elements . copy ( ) ...
def cloneTable ( self , login , tableName , newTableName , flush , propertiesToSet , propertiesToExclude ) : """Parameters : - login - tableName - newTableName - flush - propertiesToSet - propertiesToExclude"""
self . send_cloneTable ( login , tableName , newTableName , flush , propertiesToSet , propertiesToExclude ) self . recv_cloneTable ( )
def rgb ( self , color_tuple ) : """Used as main setter ( rgb256 , hls , hls256 , hsv , hsv256)"""
# Check bounds self . color = tuple ( map ( self . _apply_float_bounds , color_tuple [ : 3 ] ) ) # Include alpha if necessary if len ( color_tuple ) > 3 : self . alpha = self . _apply_float_bounds ( color_tuple [ 3 ] )
def hash ( self , rtdc_ds ) : """Used for identifying an ancillary computation The data columns and the used configuration keys / values are hashed ."""
hasher = hashlib . md5 ( ) # data columns for col in self . req_features : hasher . update ( obj2str ( rtdc_ds [ col ] ) ) # config keys for sec , keys in self . req_config : for key in keys : val = rtdc_ds . config [ sec ] [ key ] data = "{}:{}={}" . format ( sec , key , val ) hasher . ...
def _get_adjustment ( mag , year , mmin , completeness_year , t_f , mag_inc = 0.1 ) : '''If the magnitude is greater than the minimum in the completeness table and the year is greater than the corresponding completeness year then return the Weichert factor : param float mag : Magnitude of an earthquake : ...
if len ( completeness_year ) == 1 : if ( mag >= mmin ) and ( year >= completeness_year [ 0 ] ) : # No adjustment needed - event weight = = 1 return 1.0 else : # Event should not be counted return False kval = int ( ( ( mag - mmin ) / mag_inc ) ) + 1 if ( kval >= 1 ) and ( year >= completeness_ye...
def merge ( self , branch , destination = "master" ) : """Merge the the given WIP branch to master ( or destination , if specified ) If the merge fails , the merge will be aborted and then a MergeException will be thrown . The message of the MergeException will be the " git status " output , so details abou...
current_branch = self . current_branch ( ) if current_branch != destination : _LOG . debug ( 'checking out ' + destination ) git ( self . gitdir , self . gitwd , "checkout" , destination ) try : git ( self . gitdir , self . gitwd , "merge" , branch ) except sh . ErrorReturnCode : _LOG . exception ( 'mer...
def get ( self , network_id , * args , ** kwargs ) : """Get a network by its ID . Args : network _ id ( str ) : The ID of the network . verbose ( bool ) : Retrieve the service details across the cluster in swarm mode . scope ( str ) : Filter the network by scope ( ` ` swarm ` ` , ` ` global ` ` or ` ` l...
return self . prepare_model ( self . client . api . inspect_network ( network_id , * args , ** kwargs ) )
def from_signed_raw ( cls : Type [ RevocationType ] , signed_raw : str ) -> RevocationType : """Return Revocation document instance from a signed raw string : param signed _ raw : raw document file in duniter format : return :"""
lines = signed_raw . splitlines ( True ) n = 0 version = int ( Revocation . parse_field ( "Version" , lines [ n ] ) ) n += 1 Revocation . parse_field ( "Type" , lines [ n ] ) n += 1 currency = Revocation . parse_field ( "Currency" , lines [ n ] ) n += 1 issuer = Revocation . parse_field ( "Issuer" , lines [ n ] ) n += ...
def from_mixed_draws ( cls , pst , how_dict , default = "gaussian" , num_reals = 100 , cov = None , sigma_range = 6 , enforce_bounds = True , partial = False ) : """instaniate a parameter ensemble from stochastic draws using a mixture of distributions . Available distributions include ( log ) " uniform " , ( log ...
# error checking accept = { "uniform" , "triangular" , "gaussian" } assert default in accept , "ParameterEnsemble.from_mixed_draw() error: 'default' must be in {0}" . format ( accept ) par_org = pst . parameter_data . copy ( ) pset = set ( pst . adj_par_names ) hset = set ( how_dict . keys ( ) ) missing = pset . differ...
def unsubscribe ( self , subscriber : 'Subscriber' ) -> None : """Unsubscribe the given subscriber : param subscriber : subscriber to unsubscribe : raises SubscriptionError : if subscriber is not subscribed ( anymore )"""
# here is a special implementation which is replacing the more # obvious one : self . _ subscriptions . remove ( subscriber ) - this will not # work because list . remove ( x ) is doing comparision for equality . # Applied to publishers this will return another publisher instead of # a boolean result for i , _s in enum...
def get_symmetrized_structure ( self ) : """Get a symmetrized structure . A symmetrized structure is one where the sites have been grouped into symmetrically equivalent groups . Returns : : class : ` pymatgen . symmetry . structure . SymmetrizedStructure ` object ."""
ds = self . get_symmetry_dataset ( ) sg = SpacegroupOperations ( self . get_space_group_symbol ( ) , self . get_space_group_number ( ) , self . get_symmetry_operations ( ) ) return SymmetrizedStructure ( self . _structure , sg , ds [ "equivalent_atoms" ] , ds [ "wyckoffs" ] )
def parse ( self , fo ) : """Convert BioProspector output to motifs Parameters fo : file - like File object containing BioProspector output . Returns motifs : list List of Motif instances ."""
motifs = [ ] p = re . compile ( r'^\d+\s+(\d+\.\d+)\s+(\d+\.\d+)\s+(\d+\.\d+)\s+(\d+\.\d+)' ) pwm = [ ] motif_id = "" for line in fo . readlines ( ) : if line . startswith ( "Motif #" ) : if pwm : m = Motif ( pwm ) m . id = "BioProspector_w%s_%s" % ( len ( m ) , motif_id ) ...
def datetime_to_iso_date ( the_datetime , use_micros = False ) : """> > > datetime _ to _ iso _ date ( datetime . datetime ( 2013 , 12 , 26 , 10 , 11 , 12 ) ) '2013-12-26T10:11:12Z ' > > > datetime _ to _ iso _ date ( datetime . datetime ( 2013 , 12 , 26 , 10 , 11 , 12 , 456789 ) ) '2013-12-26T10:11:12Z ' >...
if not use_micros : return the_datetime . strftime ( ISO_DT ) else : return the_datetime . isoformat ( ) + 'Z'
def add_resize_bilinear ( self , name , input_name , output_name , target_height = 1 , target_width = 1 , mode = 'ALIGN_ENDPOINTS_MODE' ) : """Add resize bilinear layer to the model . A layer that resizes the input to a given spatial size using bilinear interpolation . Parameters name : str The name of this l...
spec = self . spec nn_spec = self . nn_spec # Add a new inner - product layer spec_layer = nn_spec . layers . add ( ) spec_layer . name = name spec_layer . input . append ( input_name ) spec_layer . output . append ( output_name ) spec_layer_params = spec_layer . resizeBilinear spec_layer_params . targetSize . append (...
def construct_operation_validators ( api_path , path_definition , operation_definition , context ) : """- consumes ( did the request conform to the content types this api consumes ) - produces ( did the response conform to the content types this endpoint produces ) - parameters ( did the parameters of this requ...
validators = { } # sanity check assert 'context' not in operation_definition assert 'api_path' not in operation_definition assert 'path_definition' not in operation_definition for key in operation_definition . keys ( ) : if key not in validator_mapping : # TODO : is this the right thing to do ? continue ...
def _filter_stmts ( self , stmts , frame , offset ) : """Filter the given list of statements to remove ignorable statements . If self is not a frame itself and the name is found in the inner frame locals , statements will be filtered to remove ignorable statements according to self ' s location . : param st...
# if offset = = - 1 , my actual frame is not the inner frame but its parent # class A ( B ) : pass # we need this to resolve B correctly if offset == - 1 : myframe = self . frame ( ) . parent . frame ( ) else : myframe = self . frame ( ) # If the frame of this node is the same as the statement # of this...
def commit ( self ) : """Commit changes to disk if attached . This method helps normalize the interface for detached and attached tables and makes writing attached tables a bit more efficient . For detached tables nothing is done , as there is no notion of changes , but neither is an error raised ( unlike w...
if not self . is_attached ( ) : return changes = self . list_changes ( ) if changes : indices , records = zip ( * changes ) if min ( indices ) > self . _last_synced_index : self . write ( records , append = True ) else : self . write ( append = False )
def equities_sids_for_country_code ( self , country_code ) : """Return all of the sids for a given country . Parameters country _ code : str An ISO 3166 alpha - 2 country code . Returns tuple [ int ] The sids whose exchanges are in this country ."""
sids = self . _compute_asset_lifetimes ( [ country_code ] ) . sid return tuple ( sids . tolist ( ) )
def energy ( self , strand , dotparens , temp = 37.0 , pseudo = False , material = None , dangles = 'some' , sodium = 1.0 , magnesium = 0.0 ) : '''Calculate the free energy of a given sequence structure . Runs the \' energy \' command . : param strand : Strand on which to run energy . Strands must be either c...
# Set the material ( will be used to set command material flag ) material = self . _set_material ( strand , material ) # Set up command flags cmd_args = self . _prep_cmd_args ( temp , dangles , material , pseudo , sodium , magnesium , multi = False ) # Set up the input file and run the command . Note : no STDOUT lines ...
def generate_rsa_public_and_private ( bits = _DEFAULT_RSA_KEY_BITS ) : """< Purpose > Generate public and private RSA keys with modulus length ' bits ' . The public and private keys returned conform to ' securesystemslib . formats . PEMRSA _ SCHEMA ' and have the form : ' - - - - - BEGIN RSA PUBLIC KEY - - ...
# Does ' bits ' have the correct format ? # This check will ensure ' bits ' conforms to # ' securesystemslib . formats . RSAKEYBITS _ SCHEMA ' . ' bits ' must be an integer # object , with a minimum value of 2048 . Raise # ' securesystemslib . exceptions . FormatError ' if the check fails . securesystemslib . formats ....
def set_wts_get_npred_wt ( gta , maskname ) : """Set a weights file and get the weighted npred for all the sources Parameters gta : ` fermipy . GTAnalysis ` The analysis object maskname : str The path to the file with the mask Returns odict : dict Dictionary mapping from source name to weighted npre...
if is_null ( maskname ) : maskname = None gta . set_weights_map ( maskname ) for name in gta . like . sourceNames ( ) : gta . _init_source ( name ) gta . _update_roi ( ) return build_srcdict ( gta , 'npred_wt' )
def setup_default_layouts ( self , index , settings ) : """Setup default layouts when run for the first time ."""
self . setUpdatesEnabled ( False ) first_spyder_run = bool ( self . first_spyder_run ) # Store copy if first_spyder_run : self . set_window_settings ( * settings ) else : if self . last_plugin : if self . last_plugin . ismaximized : self . maximize_dockwidget ( restore = True ) if not ( ...
def info ( self , val ) : """Set info metric ."""
if self . _labelname_set . intersection ( val . keys ( ) ) : raise ValueError ( 'Overlapping labels for Info metric, metric: %s child: %s' % ( self . _labelnames , val ) ) with self . _lock : self . _value = dict ( val )
def to_df ( self , method : str = 'MEMORY' , ** kwargs ) -> 'pd.DataFrame' : """Export this SAS Data Set to a Pandas Data Frame : param method : defaults to MEMORY ; the original method . CSV is the other choice which uses an intermediary csv file ; faster for large data : param kwargs : : return : Pandas dat...
ll = self . _is_valid ( ) if ll : print ( ll [ 'LOG' ] ) return None else : return self . sas . sasdata2dataframe ( self . table , self . libref , self . dsopts , method , ** kwargs )
def delete_atom ( self , * atom_numbers ) : """Delete atoms by atom number . : param str atom _ numbers : : return : None . : rtype : : py : obj : ` None `"""
for atom_number in atom_numbers : deletion_atom = self . atom_by_number ( atom_number = atom_number ) # update atom numbers for atom in self . atoms : if int ( atom . atom_number ) > int ( atom_number ) : atom . atom_number = str ( int ( atom . atom_number ) - 1 ) # find index of a b...
def _get_brew_versions ( ) : """Retrieve versions of tools installed via brew ."""
from bcbio import install tooldir = install . get_defaults ( ) . get ( "tooldir" ) brew_cmd = os . path . join ( tooldir , "bin" , "brew" ) if tooldir else "brew" try : vout = subprocess . check_output ( [ brew_cmd , "list" , "--versions" ] ) except OSError : # brew not installed / used vout = "" out = { } for ...
def _detect ( self ) : """Detect the suicidal functions"""
results = [ ] for c in self . contracts : functions = self . detect_suicidal ( c ) for func in functions : txt = "{}.{} ({}) allows anyone to destruct the contract\n" info = txt . format ( func . contract . name , func . name , func . source_mapping_str ) json = self . generate_json_resu...
def get_user_switchable_roles ( self ) : """Returns user ' s role list except current role as a tuple ( role . key , role . name ) Returns : ( list ) : list of tuples , user ' s role list except current role"""
roles = [ ] for rs in self . current . user . role_set : # rs . role ! = self . current . role is not True after python version 2.7.12 if rs . role . key != self . current . role . key : roles . append ( ( rs . role . key , '%s %s' % ( rs . role . unit . name , rs . role . abstract_role . name ) ) ) return ...
def list_nodes_min ( ) : '''Return a list of registered VMs , with minimal information CLI Example : . . code - block : : bash salt ' * ' vboxmanage . list _ nodes _ min'''
ret = { } cmd = '{0} list vms' . format ( vboxcmd ( ) ) for line in salt . modules . cmdmod . run ( cmd ) . splitlines ( ) : if not line . strip ( ) : continue comps = line . split ( ) name = comps [ 0 ] . replace ( '"' , '' ) ret [ name ] = True return ret
def dom_processing ( self , value ) : """The dom _ processing property . Args : value ( string ) . the property value ."""
if value == self . _defaults [ 'domProcessing' ] and 'domProcessing' in self . _values : del self . _values [ 'domProcessing' ] else : self . _values [ 'domProcessing' ] = value
def _cache_get_entry ( self , entry_name , key = ENTIRE_ENTRY_KEY , default = False ) : """Returns cache entry parameter value by its name . : param str entry _ name : : param str key : : param type default : : return :"""
if key is self . ENTIRE_ENTRY_KEY : return self . _cache [ entry_name ] return self . _cache [ entry_name ] . get ( key , default )
def contains ( ell , p , shell_only = False ) : """Check to see whether point is inside conic . : param exact : Only solutions exactly on conic are considered ( default : False ) ."""
v = augment ( p ) _ = ell . solve ( v ) return N . allclose ( _ , 0 ) if shell_only else _ <= 0
def level ( self , new_level ) : """Sets the new output level ."""
if self . _level == new_level : return self . _lutron . send ( Lutron . OP_EXECUTE , Output . _CMD_TYPE , self . _integration_id , Output . _ACTION_ZONE_LEVEL , "%.2f" % new_level ) self . _level = new_level
def get_networks ( self ) : """Get the networks assoiated with the resource description . Returns list of tuple roles , network"""
networks = self . c_resources [ "networks" ] result = [ ] for net in networks : _c_network = net . get ( "_c_network" ) if _c_network is None : continue roles = utils . get_roles_as_list ( net ) result . append ( ( roles , _c_network ) ) return result
def libseq_parse ( self , line ) : """This method parses a line containing a lib _ seq string and adds it to the lib _ seq key in the self . params dictionary"""
count = line . count ( ',' ) if count > 1 : raise ValueError ( """ERROR: There are too many commas in your lib_seq line. There should only be one, between the two filepath globs.""" ) if count == 0 : raise ValueError ( """ERROR: There are no commas in your lib_seq line. There...
def get_range_start_line_number ( self , rng ) : """. . warning : : not implemented"""
sys . stderr . write ( "error unimplemented get_range_start_line\n" ) sys . exit ( ) for i in range ( 0 , len ( self . _lines ) ) : if rng . cmp ( self . _lines [ i ] [ 'rng' ] ) == 0 : return i + 1 return None
def _get_image_stream_info_for_build_request ( self , build_request ) : """Return ImageStream , and ImageStreamTag name for base _ image of build _ request If build _ request is not auto instantiated , objects are not fetched and None , None is returned ."""
image_stream = None image_stream_tag_name = None if build_request . has_ist_trigger ( ) : image_stream_tag_id = build_request . trigger_imagestreamtag image_stream_id , image_stream_tag_name = image_stream_tag_id . split ( ':' ) try : image_stream = self . get_image_stream ( image_stream_id ) . json...
def compile_rename_column ( self , blueprint , command , connection ) : """Compile a rename column command . : param blueprint : The blueprint : type blueprint : Blueprint : param command : The command : type command : Fluent : param connection : The connection : type connection : orator . connections ....
sql = [ ] # If foreign keys are on , we disable them foreign_keys = self . _connection . select ( "PRAGMA foreign_keys" ) if foreign_keys : foreign_keys = bool ( foreign_keys [ 0 ] ) if foreign_keys : sql . append ( "PRAGMA foreign_keys = OFF" ) sql += super ( SQLiteSchemaGrammar , self ) . compile_rena...
def log ( cls , level , message ) : """: param level : The log level as in the Python logging documentation , 5 different possible values with increasing severity : type level : String of value ' DEBUG ' , ' INFO ' , ' WARNING ' , ' ERROR ' or ' CRITICAL ' . : param message : The logging data which should be ...
if cls . logger is None : cls . setup_logging ( ) log_levels = { 'DEBUG' : logging . DEBUG , 'ERROR' : logging . ERROR , 'INFO' : logging . INFO , 'WARNING' : logging . WARNING , 'CRITICAL' : logging . CRITICAL } cls . logger . log ( level = log_levels [ level ] , msg = message )
def objset_data ( self ) : '''Return the terms representation for our objset interface . If there is no qualifier , return just the string content value . If there is a qualifier , return a dict of { q : qualifier , v : content }'''
if not self . qualifier : return unicode ( self . content ) else : return dict ( q = unicode ( self . qualifier ) , v = unicode ( self . content ) )
async def get_source_list ( self , scheme : str = "" ) -> List [ Source ] : """Return available sources for playback ."""
res = await self . services [ "avContent" ] [ "getSourceList" ] ( scheme = scheme ) return [ Source . make ( ** x ) for x in res ]
def fuzzy_get_value ( obj , approximate_key , default = None , ** kwargs ) : """Like fuzzy _ get , but assume the obj is dict - like and return the value without the key Notes : Argument order is in reverse order relative to ` fuzzywuzzy . process . extractOne ( ) ` but in the same order as get ( self , key )...
dict_obj = OrderedDict ( obj ) try : return dict_obj [ list ( dict_obj . keys ( ) ) [ int ( approximate_key ) ] ] except ( ValueError , IndexError ) : pass return fuzzy_get ( dict_obj , approximate_key , key_and_value = False , ** kwargs )
def textForSaving ( self ) : """Get text with correct EOL symbols . Use this method for saving a file to storage"""
lines = self . text . splitlines ( ) if self . text . endswith ( '\n' ) : # splitlines ignores last \ n lines . append ( '' ) return self . eol . join ( lines ) + self . eol
def get_extension_reports ( self , publisher_name , extension_name , days = None , count = None , after_date = None ) : """GetExtensionReports . [ Preview API ] Returns extension reports : param str publisher _ name : Name of the publisher who published the extension : param str extension _ name : Name of the...
route_values = { } if publisher_name is not None : route_values [ 'publisherName' ] = self . _serialize . url ( 'publisher_name' , publisher_name , 'str' ) if extension_name is not None : route_values [ 'extensionName' ] = self . _serialize . url ( 'extension_name' , extension_name , 'str' ) query_parameters = ...
def clear ( self ) : """Clears all the axes to start fresh ."""
for ax in self . flat_grid : for im_h in ax . findobj ( AxesImage ) : im_h . remove ( )
def normalize ( vector , cutoffp = ( 0 , 100 ) , model = False ) : r"""Returns a feature - wise normalized version of the supplied vector . Normalization is achieved to [ 0,1 ] over the complete vector using shifting and scaling . When cut - off percentile ( cutoffp ) values other than ( 0 , 100 ) are supplied ...
vector = numpy . array ( vector , dtype = numpy . float ) # add a singleton dimension if required if 1 == vector . ndim : vector = vector [ : , None ] # compute lower and upper range border of each row using the supplied percentiles minp , maxp = numpy . percentile ( vector , cutoffp , 0 ) # shift outliers to fit r...
def genome_for_reference_name ( reference_name , allow_older_downloaded_release = True ) : """Given a genome reference name , such as " GRCh38 " , returns the corresponding Ensembl Release object . If ` allow _ older _ downloaded _ release ` is True , and some older releases have been downloaded , then return...
reference_name = normalize_reference_name ( reference_name ) species = find_species_by_reference ( reference_name ) ( min_ensembl_release , max_ensembl_release ) = species . reference_assemblies [ reference_name ] if allow_older_downloaded_release : # go through candidate releases in descending order for release in...
def send_broks_to_modules ( self ) : """Put broks into module queues Only broks without sent _ to _ externals to True are sent Only modules that ask for broks will get some : return : None"""
t00 = time . time ( ) nb_sent = 0 broks = [ ] for broker_link in list ( self . my_daemon . brokers . values ( ) ) : for brok in broker_link . broks : if not getattr ( brok , 'sent_to_externals' , False ) : brok . to_send = True broks . append ( brok ) if not broks : return logger...
def _check_decorator ( fct ) : """Check if the plugin is enabled ."""
def wrapper ( self , * args , ** kw ) : if self . is_enable ( ) : ret = fct ( self , * args , ** kw ) else : ret = self . stats return ret return wrapper
def _get_initial_residual ( self , x0 ) : '''Return the projected initial residual . Returns : math : ` MPM _ l ( b - Ax _ 0 ) ` .'''
if x0 is None : Mlr = self . linear_system . Mlb else : r = self . linear_system . b - self . linear_system . A * x0 Mlr = self . linear_system . Ml * r PMlr , self . UMlr = self . projection . apply_complement ( Mlr , return_Ya = True ) MPMlr = self . linear_system . M * PMlr MPMlr_norm = utils . norm ( PM...
def install ( self , host ) : """Setup common to all Qt - based hosts"""
print ( "Installing.." ) if self . _state [ "installed" ] : return if self . is_headless ( ) : log . info ( "Headless host" ) return print ( "aboutToQuit.." ) self . app . aboutToQuit . connect ( self . _on_application_quit ) if host == "Maya" : print ( "Maya host.." ) window = { widget . objectName...
def is_directory_index ( resource ) : """Classify the input resource as a directory index or not ."""
remote_regexp = re . compile ( r"^https?://(.+)/?$" , re . I ) result = remote_regexp . match ( resource ) if result is not None : juicer . utils . Log . log_debug ( "%s matches directory index regexp" % resource ) return True else : juicer . utils . Log . log_debug ( "%s doesn't match directory index regex...
def assist ( self , project_path , source , position , filename ) : """Return completion match and list of completion proposals : param project _ path : absolute project path : param source : unicode or byte string code source : param position : character or byte cursor position : param filename : absolute ...
return self . _call ( 'assist' , project_path , source , position , filename )
def _install_p4v_linux ( self , url ) : """Install perforce applications and binaries for linux"""
lib . extract_targz ( url , self . directory . install_directory ( self . feature_name ) , remove_common_prefix = True ) bin_path = os . path . join ( self . directory . install_directory ( self . feature_name ) , 'bin' ) if os . path . exists ( bin_path ) : for f in os . listdir ( bin_path ) : self . direc...
def _evalDayStr ( self , datetimeString , sourceTime ) : """Evaluate text passed by L { _ partialParseDaystr ( ) }"""
s = datetimeString . strip ( ) sourceTime = self . _evalDT ( datetimeString , sourceTime ) # Given string is a natural language date string like today , tomorrow . . ( yr , mth , dy , hr , mn , sec , wd , yd , isdst ) = sourceTime try : offset = self . ptc . dayOffsets [ s ] except KeyError : offset = 0 if self...
def get_attr ( self , name , default = None , fail_silently = True ) : """try extra context"""
try : return getattr ( self , name ) except KeyError : extra_context = getattr ( self , "extra_context" ) if name in extra_context : value = extra_context [ name ] if callable ( value ) : return value ( request = None ) return default
def create_task ( self , * command_tokens , ** command_env ) : """: return : WLauncherScheduleTask"""
return self . __scheduled_task_cls ( self . basic_command ( ) , * command_tokens , ** command_env )
def __hide_or_show_root_items ( self , item ) : """show _ all _ files option is disabled : hide all root items except * item * show _ all _ files option is enabled : do nothing"""
for _it in self . get_top_level_items ( ) : _it . setHidden ( _it is not item and not self . show_all_files )
def visit_with ( self , node ) : # ' with ' without ' as ' is possible """return an astroid . With node as string"""
items = ", " . join ( ( "%s" % expr . accept ( self ) ) + ( vars and " as %s" % ( vars . accept ( self ) ) or "" ) for expr , vars in node . items ) return "with %s:\n%s" % ( items , self . _stmt_list ( node . body ) )
def _parse_client_keys ( stream ) : '''This parses a hidden - service " client _ keys " file , either stealth or basic ( they ' re the same , except " stealth " includes a " client - key " ) . Returns a list of HiddenServiceClientAuth ( ) instances . Note that the key does NOT include the " - - - - BEGIN - - ...
def parse_error ( data ) : raise RuntimeError ( "Parse error at: " + data ) class ParserState ( object ) : def __init__ ( self ) : self . keys = [ ] self . reset ( ) def reset ( self ) : self . name = None self . cookie = None self . key = [ ] def create_key ( sel...
def make_patch ( self ) : '''Currently only works if all the pieces are Arcgons . In this case returns a multiple - piece path . Otherwise throws an exception .'''
paths = [ p . make_patch ( ) . get_path ( ) for p in self . pieces ] vertices = np . concatenate ( [ p . vertices for p in paths ] ) codes = np . concatenate ( [ p . codes for p in paths ] ) return PathPatch ( Path ( vertices , codes ) )
def to_python ( self , value ) : """Validates that the input can be converted to a date . Returns a Python datetime . date object ."""
if value in validators . EMPTY_VALUES : return None if isinstance ( value , datetime . datetime ) : return value . date ( ) if isinstance ( value , datetime . date ) : return value if isinstance ( value , list ) : # Input comes from a 2 SplitDateWidgets , for example . So , it ' s two # components : start d...
def stat ( self ) : """Returns ( opened connections , free connections , waiters )"""
return ( self . _opened_conns , len ( self . _free_conn ) , len ( self . _waitings ) )
def pad_to_bounding_box ( image , offset_height , offset_width , target_height , target_width , dynamic_shape = False ) : """Pad ` image ` with zeros to the specified ` height ` and ` width ` . Adds ` offset _ height ` rows of zeros on top , ` offset _ width ` columns of zeros on the left , and then pads the im...
image = ops . convert_to_tensor ( image , name = 'image' ) _Check3DImage ( image , require_static = ( not dynamic_shape ) ) height , width , depth = _ImageDimensions ( image , dynamic_shape = dynamic_shape ) after_padding_width = target_width - offset_width - width after_padding_height = target_height - offset_height -...
def getAsKmlPngAnimation ( self , tableName , timeStampedRasters = [ ] , rasterIdFieldName = 'id' , rasterFieldName = 'raster' , documentName = 'default' , noDataValue = 0 , alpha = 1.0 , drawOrder = 0 , cellSize = None , resampleMethod = 'NearestNeighbour' , discreet = False ) : """Return a sequence of rasters wit...
if not self . isNumber ( noDataValue ) : raise ValueError ( 'RASTER CONVERSION ERROR: noDataValue must be a number.' ) if not self . isNumber ( drawOrder ) : raise ValueError ( 'RASTER CONVERSION ERROR: drawOrder must be a number.' ) if not ( alpha >= 0 and alpha <= 1.0 ) : raise ValueError ( "RASTER CONVER...
def query ( self , ** query ) : """Gets the results of query , with optional parameters sort , limit , skip , and fields . : param query : Optional parameters . Valid options are sort , limit , skip , and fields : type query : ` ` dict ` ` : return : Array of documents retrieved by query . : rtype : ` ` arr...
return json . loads ( self . _get ( '' , ** query ) . body . read ( ) . decode ( 'utf-8' ) )
def prj_add_dep ( self , * args , ** kwargs ) : """Add more departments to the project . : returns : None : rtype : None : raises : None"""
if not self . cur_prj : return dialog = DepAdderDialog ( project = self . cur_prj ) dialog . exec_ ( ) deps = dialog . deps for dep in deps : depdata = djitemdata . DepartmentItemData ( dep ) treemodel . TreeItem ( depdata , self . prj_dep_model . root )
def files_in_path ( path ) : """Return a list of all files in a path but exclude git folders ."""
aggregated_files = [ ] for dir_ , _ , files in os . walk ( path ) : for file in files : relative_dir = os . path . relpath ( dir_ , path ) if ".git" not in relative_dir : relative_file = os . path . join ( relative_dir , file ) aggregated_files . append ( relative_file ) retu...
def nvmlDeviceSetApplicationsClocks ( handle , maxMemClockMHz , maxGraphicsClockMHz ) : r"""* Set clocks that applications will lock to . * Sets the clocks that compute and graphics applications will be running at . * e . g . CUDA driver requests these clocks during context creation which means this property ...
fn = _nvmlGetFunctionPointer ( "nvmlDeviceSetApplicationsClocks" ) ret = fn ( handle , c_uint ( maxMemClockMHz ) , c_uint ( maxGraphicsClockMHz ) ) _nvmlCheckReturn ( ret ) return None
def _sending_task ( self , backend ) : """Used internally to safely increment ` backend ` s task count . Returns the overall count of tasks for ` backend ` ."""
with self . backend_mutex : self . backends [ backend ] += 1 self . task_counter [ backend ] += 1 this_task = self . task_counter [ backend ] return this_task
def generate_uuid ( basedata = None ) : """Provides a _ random _ UUID with no input , or a UUID4 - format MD5 checksum of any input data provided"""
if basedata is None : return str ( uuid . uuid4 ( ) ) elif isinstance ( basedata , str ) : checksum = hashlib . md5 ( basedata ) . hexdigest ( ) return '%8s-%4s-%4s-%4s-%12s' % ( checksum [ 0 : 8 ] , checksum [ 8 : 12 ] , checksum [ 12 : 16 ] , checksum [ 16 : 20 ] , checksum [ 20 : 32 ] )
def bounce ( sequence ) : '''Return a driver function that can advance a " bounced " sequence of values . . . code - block : : none seq = [ 0 , 1 , 2 , 3] # bounce ( seq ) = > [ 0 , 1 , 2 , 3 , 3 , 2 , 1 , 0 , 0 , 1 , 2 , . . . ] Args : sequence ( seq ) : a sequence of values for the driver to bounce'''
N = len ( sequence ) def f ( i ) : div , mod = divmod ( i , N ) if div % 2 == 0 : return sequence [ mod ] else : return sequence [ N - mod - 1 ] return partial ( force , sequence = _advance ( f ) )
def decr ( self , key , delta = 1 ) : """Decrements the specified key value by the specified value . : param str | unicode key : : param int delta : : rtype : bool"""
return uwsgi . cache_dec ( key , delta , self . timeout , self . name )
def update ( self , lambda_mults = [ 1.0 ] , localizer = None , run_subset = None , use_approx = True , calc_only = False ) : """update the iES one GLM cycle Parameters lambda _ mults : list a list of lambda multipliers to test . Each lambda mult value will require evaluating ( a subset of ) the parameter e...
# if not self . parensemble . istransformed : # self . parensemble . _ transform ( inplace = False ) if run_subset is not None : if run_subset >= self . obsensemble . shape [ 0 ] : self . logger . warn ( "run_subset ({0}) >= num of active reals ({1})...ignoring " . format ( run_subset , self . obsensemble ....
def get_issue_labels ( self , issue_key ) : """Get issue labels . : param issue _ key : : return :"""
url = 'rest/api/2/issue/{issue_key}?fields=labels' . format ( issue_key = issue_key ) return ( self . get ( url ) or { } ) . get ( 'fields' ) . get ( 'labels' )
def gp_size ( self , _gp_size ) : """Store the new start address attribute of the BFD file being processed ."""
if not self . _ptr : raise BfdException ( "BFD not initialized" ) return _bfd . set_gp_size ( self . _ptr , _gp_size )
def _can_connect ( self ) : """Tries to connect to the configured host : port and returns True if the connection was established"""
self . log ( 'Trying to reach configured connectivity check endpoint' , lvl = verbose ) try : socket . setdefaulttimeout ( self . config . timeout ) socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) . connect ( ( self . config . host , self . config . port ) ) return True except Exception as ex : ...
def deduplicate ( pairs , aa = False , ignore_primer_regions = False ) : '''Removes duplicate sequences from a list of Pair objects . If a Pair has heavy and light chains , both chains must identically match heavy and light chains from another Pair to be considered a duplicate . If a Pair has only a single chai...
nr_pairs = [ ] just_pairs = [ p for p in pairs if p . is_pair ] single_chains = [ p for p in pairs if not p . is_pair ] _pairs = just_pairs + single_chains for p in _pairs : duplicates = [ ] for nr in nr_pairs : identical = True vdj = 'vdj_aa' if aa else 'vdj_nt' offset = 4 if aa else 12...
def login ( self , email , password , android_id ) : """Authenticate to Google with the provided credentials . Args : email ( str ) : The account to use . password ( str ) : The account password . android _ id ( str ) : An identifier for this client . Raises : LoginException : If there was a problem log...
self . _email = email self . _android_id = android_id res = gpsoauth . perform_master_login ( self . _email , password , self . _android_id ) if 'Token' not in res : raise exception . LoginException ( res . get ( 'Error' ) , res . get ( 'ErrorDetail' ) ) self . _master_token = res [ 'Token' ] self . refresh ( ) ret...
def destroy_venv ( env_path , venvscache = None ) : """Destroy a venv ."""
# remove the venv itself in disk logger . debug ( "Destroying virtualenv at: %s" , env_path ) shutil . rmtree ( env_path , ignore_errors = True ) # remove venv from cache if venvscache is not None : venvscache . remove ( env_path )
def mac_address_table_aging_time_legacy_time_out ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) mac_address_table = ET . SubElement ( config , "mac-address-table" , xmlns = "urn:brocade.com:mgmt:brocade-mac-address-table" ) aging_time = ET . SubElement ( mac_address_table , "aging-time" ) legacy_time_out = ET . SubElement ( aging_time , "legacy-time-out" ) legacy_time_out . text...
def _name_to_tensor ( self , tensor_name ) : """The tensor with the given name . Args : tensor _ name : a string , name of a tensor in the graph . Returns : a tf . Tensor or mtf . Tensor"""
id1 , id2 = self . _tensor_name_to_ids [ tensor_name ] return self . _operations [ id1 ] . outputs [ id2 ]
def datasetHeaderChunk ( key , lines ) : """Process the dataset header"""
KEYWORDS = ( 'DATASET' , 'OBJTYPE' , 'VECTYPE' , 'BEGSCL' , 'BEGVEC' , 'OBJID' , 'ND' , 'NC' , 'NAME' ) TYPE_KEYS = ( 'BEGSCL' , 'BEGVEC' ) result = { 'type' : None , 'numberData' : None , 'numberCells' : None , 'name' : None , 'objectID' : None , 'objectType' : None , 'vectorType' : None } chunks = pt . chunk ( KEYWOR...
def open ( self , configuration , flags ) : """Opens a CAN connection using ` CanalOpen ( ) ` . : param str configuration : the configuration : " device _ id ; baudrate " : param int flags : the flags to be set : raises can . CanError : if any error occurred : returns : Valid handle for CANAL API functions ...
try : # we need to convert this into bytes , since the underlying DLL cannot # handle non - ASCII configuration strings config_ascii = configuration . encode ( 'ascii' , 'ignore' ) result = self . __m_dllBasic . CanalOpen ( config_ascii , flags ) except Exception as ex : # catch any errors thrown by this call a...
def db_for_write ( self , model , ** hints ) : """Prevent write actions on read - only tables . Raises : WriteNotSupportedError : If models . sf _ access is ` ` read _ only ` ` ."""
try : if model . sf_access == READ_ONLY : raise WriteNotSupportedError ( "%r is a read-only model." % model ) except AttributeError : pass return None
def ssh_config ( ssh_user , ssh_private_key_file ) : """Create temporary ssh config file ."""
try : ssh_file = NamedTemporaryFile ( delete = False , mode = 'w+' ) ssh_file . write ( 'Host *\n' ) ssh_file . write ( ' IdentityFile %s\n' % ssh_private_key_file ) ssh_file . write ( ' User %s' % ssh_user ) ssh_file . close ( ) yield ssh_file . name finally : with ignored ( OSError )...
def get_hline ( ) : """gets a horiztonal line"""
return Window ( width = LayoutDimension . exact ( 1 ) , height = LayoutDimension . exact ( 1 ) , content = FillControl ( '-' , token = Token . Line ) )
def userInformation ( MoreData_presence = 0 ) : """USER INFORMATION Section 9.3.31"""
a = TpPd ( pd = 0x3 ) b = MessageType ( mesType = 0x20 ) # 000100000 c = UserUser ( ) packet = a / b / c if MoreData_presence is 1 : d = MoreDataHdr ( ieiMD = 0xA0 , eightBitMD = 0x0 ) packet = packet / d return packet
def path ( * components ) : """Get a file path . Concatenate all components into a path ."""
_path = os . path . join ( * components ) _path = os . path . expanduser ( _path ) return _path
def process_edge_search ( self , current , neighbor , pred , q , component , algo , ** kargs ) : '''API : process _ edge _ search ( self , current , neighbor , pred , q , component , algo , * * kargs ) Description : Used by search ( ) method . Processes edges according to the underlying algortihm . User doe...
if algo == 'Dijkstra' : return self . process_edge_dijkstra ( current , neighbor , pred , q , component ) if algo == 'Prim' : return self . process_edge_prim ( current , neighbor , pred , q , component ) neighbor_node = self . get_node ( neighbor ) if current == None : neighbor_node . set_attr ( 'distance' ...
def qteTextChanged ( self ) : """Search for sub - string matches . This method is triggered by Qt whenever the text changes , ie . whenever the user has altered the input . Extract the new input , find all matches , and highlight them accordingly ."""
# Remove any previous highlighting . self . clearHighlighting ( ) SCI = self . qteWidget # Compile a list of spans that contain the specified string . self . compileMatchList ( ) # Return if the substring does not exist in the text . if len ( self . matchList ) == 0 : return # Make a copy of the style bits of the d...
def set_remote_addr ( self , dst_mac , dst_ip ) : """Configure remote ethernet and IP addresses ."""
self . dst_mac = dst_mac self . dst_ip = dst_ip if not ( dst_mac == "FF:FF:FF:FF:FF:FF" or dst_ip == "255.255.255.255" ) : self . _remote_addr_config = True LOG . info ( "[BFD][%s][REMOTE] Remote address configured: %s, %s." , hex ( self . _local_discr ) , self . dst_ip , self . dst_mac )
def add_authorization_policy ( access_token , ck_id , oid ) : '''Add Media Service Authorization Policy . Args : access _ token ( str ) : A valid Azure authentication token . ck _ id ( str ) : A Media Service Asset Content Key ID . options _ id ( str ) : A Media Service OID . Returns : HTTP response . J...
path = '/ContentKeys' body = '{"AuthorizationPolicyId":"' + oid + '"}' return helper_add ( access_token , ck_id , path , body )
def check_for_wdiff ( ) : """Checks if the ` wdiff ` command can be found . Raises : WdiffNotFoundError : if ` ` wdiff ` ` is not found ."""
cmd = [ 'which' , CMD_WDIFF ] DEVNULL = open ( os . devnull , 'wb' ) proc = sub . Popen ( cmd , stdout = DEVNULL ) proc . wait ( ) DEVNULL . close ( ) if proc . returncode != 0 : msg = "the `{}` command can't be found" . format ( CMD_WDIFF ) raise WdiffNotFoundError ( msg )
def atlas_peer_update_health ( peer_hostport , received_response , peer_table = None ) : """Mark the given peer as alive at this time . Update times at which we contacted it , and update its health score . Use the global health table by default , or use the given health info if set ."""
with AtlasPeerTableLocked ( peer_table ) as ptbl : if peer_hostport not in ptbl . keys ( ) : return False # record that we contacted this peer , and whether or not we useful info from it now = time_now ( ) # update timestamps ; remove old data new_times = [ ] for ( t , r ) in ptbl [ peer...
def get ( name , rc_file = '~/.odoorpcrc' ) : """Return the session configuration identified by ` name ` from the ` rc _ file ` file . > > > import odoorpc > > > from pprint import pprint as pp > > > pp ( odoorpc . session . get ( ' foo ' ) ) # doctest : + SKIP { ' database ' : ' db _ name ' , ' host ' ...
conf = ConfigParser ( ) conf . read ( [ os . path . expanduser ( rc_file ) ] ) if not conf . has_section ( name ) : raise ValueError ( "'%s' session does not exist in %s" % ( name , rc_file ) ) return { 'type' : conf . get ( name , 'type' ) , 'host' : conf . get ( name , 'host' ) , 'protocol' : conf . get ( name , ...
def cache_jobs ( opts , jid , ret ) : '''Write job information to cache'''
serial = salt . payload . Serial ( opts = opts ) fn_ = os . path . join ( opts [ 'cachedir' ] , 'minion_jobs' , jid , 'return.p' ) jdir = os . path . dirname ( fn_ ) if not os . path . isdir ( jdir ) : os . makedirs ( jdir ) with salt . utils . files . fopen ( fn_ , 'w+b' ) as fp_ : fp_ . write ( serial . dumps...
def gradient_compression_params ( args : argparse . Namespace ) -> Optional [ Dict [ str , Any ] ] : """: param args : Arguments as returned by argparse . : return : Gradient compression parameters or None ."""
if args . gradient_compression_type is None : return None else : return { 'type' : args . gradient_compression_type , 'threshold' : args . gradient_compression_threshold }