signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def motif_tree_plot ( outfile , tree , data , circle = True , vmin = None , vmax = None , dpi = 300 ) : """Plot a " phylogenetic " tree"""
try : from ete3 import Tree , faces , AttrFace , TreeStyle , NodeStyle except ImportError : print ( "Please install ete3 to use this functionality" ) sys . exit ( 1 ) # Define the tree t , ts = _get_motif_tree ( tree , data , circle , vmin , vmax ) # Save image t . render ( outfile , tree_style = ts , w = 1...
def resize_for_flows ( self ) : """Extend ` unamey ` and ` fnamey ` for bus injections and line flows"""
if self . system . config . dime_enable : self . system . tds . config . compute_flows = True if self . system . tds . config . compute_flows : nflows = 2 * self . system . Bus . n + 8 * self . system . Line . n + 2 * self . system . Area . n_combination self . unamey . extend ( [ '' ] * nflows ) self ....
def assert_valid_schema ( schema : GraphQLSchema ) -> None : """Utility function which asserts a schema is valid . Throws a TypeError if the schema is invalid ."""
errors = validate_schema ( schema ) if errors : raise TypeError ( "\n\n" . join ( error . message for error in errors ) )
def minute_to_session_label ( self , dt , direction = "next" ) : """Given a minute , get the label of its containing session . Parameters dt : pd . Timestamp or nanosecond offset The dt for which to get the containing session . direction : str " next " ( default ) means that if the given dt is not part of...
if direction == "next" : try : return self . _minute_to_session_label_cache [ dt ] except KeyError : pass idx = searchsorted ( self . market_closes_nanos , dt ) current_or_next_session = self . schedule . index [ idx ] self . _minute_to_session_label_cache [ dt ] = current_or_next_session if dir...
def remove ( self , type_name , entity ) : """Removes an entity using the API . Shortcut for using call ( ) with the ' Remove ' method . : param type _ name : The type of entity . : type type _ name : str : param entity : The entity to remove . : type entity : dict : raise MyGeotabException : Raises when ...
return self . call ( 'Remove' , type_name = type_name , entity = entity )
def install_package ( package , wheels_path , venv = None , requirement_files = None , upgrade = False , install_args = None ) : """Install a Python package . Can specify a specific version . Can specify a prerelease . Can specify a venv to install in . Can specify a list of paths or urls to requirement txt...
requirement_files = requirement_files or [ ] logger . info ( 'Installing %s...' , package ) if venv and not os . path . isdir ( venv ) : raise WagonError ( 'virtualenv {0} does not exist' . format ( venv ) ) pip_command = _construct_pip_command ( package , wheels_path , venv , requirement_files , upgrade , install_...
def _update_rs_no_primary_from_member ( sds , replica_set_name , server_description ) : """RS without known primary . Update from a non - primary ' s response . Pass in a dict of ServerDescriptions , current replica set name , and the ServerDescription we are processing . Returns ( new topology type , new rep...
topology_type = TOPOLOGY_TYPE . ReplicaSetNoPrimary if replica_set_name is None : replica_set_name = server_description . replica_set_name elif replica_set_name != server_description . replica_set_name : sds . pop ( server_description . address ) return topology_type , replica_set_name # This isn ' t the pr...
def _normalize ( self , addr ) : """Take any format of address and turn it into a hex string ."""
normalize = None if isinstance ( addr , Address ) : normalize = addr . addr self . _is_x10 = addr . is_x10 elif isinstance ( addr , bytearray ) : normalize = binascii . unhexlify ( binascii . hexlify ( addr ) . decode ( ) ) elif isinstance ( addr , bytes ) : normalize = addr elif isinstance ( addr , str...
def _call_vecfield_1 ( self , vf , out ) : """Implement ` ` self ( vf , out ) ` ` for exponent 1."""
vf [ 0 ] . ufuncs . absolute ( out = out ) if self . is_weighted : out *= self . weights [ 0 ] if len ( self . domain ) == 1 : return tmp = self . range . element ( ) for fi , wi in zip ( vf [ 1 : ] , self . weights [ 1 : ] ) : fi . ufuncs . absolute ( out = tmp ) if self . is_weighted : tmp *= ...
def _run ( self , url_path , headers = None , ** kwargs ) : """Requests API"""
url = self . _construct_url ( url_path ) payload = kwargs payload . update ( { 'api_token' : self . api_token } ) return self . _make_request ( url , payload , headers )
def client_config ( path , env_var = 'SALT_CLIENT_CONFIG' , defaults = None ) : '''Load Master configuration data Usage : . . code - block : : python import salt . config master _ opts = salt . config . client _ config ( ' / etc / salt / master ' ) Returns a dictionary of the Salt Master configuration fil...
if defaults is None : defaults = DEFAULT_MASTER_OPTS . copy ( ) xdg_dir = salt . utils . xdg . xdg_config_dir ( ) if os . path . isdir ( xdg_dir ) : client_config_dir = xdg_dir saltrc_config_file = 'saltrc' else : client_config_dir = os . path . expanduser ( '~' ) saltrc_config_file = '.saltrc' # Ge...
def float_range ( value ) : """Ensure that the provided value is a float integer in the range [ 0 . , 1 . ] . Parameters value : float The number to evaluate Returns value : float Returns a float in the range ( 0 . , 1 . )"""
try : value = float ( value ) except Exception : raise argparse . ArgumentTypeError ( 'Invalid float value: \'{}\'' . format ( value ) ) if value < 0.0 or value > 1.0 : raise argparse . ArgumentTypeError ( 'Invalid float value: \'{}\'' . format ( value ) ) return value
def parseAnchorName ( anchorName , markPrefix = MARK_PREFIX , ligaSeparator = LIGA_SEPARATOR , ligaNumRE = LIGA_NUM_RE , ignoreRE = None , ) : """Parse anchor name and return a tuple that specifies : 1 ) whether the anchor is a " mark " anchor ( bool ) ; 2 ) the " key " name of the anchor , i . e . the name aft...
number = None if ignoreRE is not None : anchorName = re . sub ( ignoreRE , "" , anchorName ) m = ligaNumRE . match ( anchorName ) if not m : key = anchorName else : number = m . group ( 1 ) key = anchorName . rstrip ( number ) separator = ligaSeparator if key . endswith ( separator ) : a...
def _set_adj_type ( self , v , load = False ) : """Setter method for adj _ type , mapped from YANG variable / adj _ neighbor _ entries _ state / adj _ neighbor / adj _ type ( isis - adj - type ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ adj _ type is considered as...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'is-adj-ptpt' : { 'value' : 8 } , u'is-adj-l1' : { 'value' : 2 } , u'is-adj-l2' : { 'value' : 4 } , u'is-adj-es' : { 'value' : 1...
def get_condition_value ( self , operator , value ) : """Gets the condition value based on the operator and value : param operator : the condition operator name : type operator : str : param value : the value to be formatted based on the condition operator : type value : object : return : the comparison o...
if operator in ( 'contains' , 'icontains' ) : value = '%{0}%' . format ( value ) elif operator == 'startswith' : value = '{0}%' . format ( value ) return value
def fromtif ( path , ext = 'tif' , start = None , stop = None , recursive = False , nplanes = None , npartitions = None , labels = None , engine = None , credentials = None , discard_extra = False ) : """Loads images from single or multi - page TIF files . Parameters path : str Path to data files or directory...
from tifffile import TiffFile if nplanes is not None and nplanes <= 0 : raise ValueError ( 'nplanes must be positive if passed, got %d' % nplanes ) def getarray ( idx_buffer_filename ) : idx , buf , fname = idx_buffer_filename fbuf = BytesIO ( buf ) tfh = TiffFile ( fbuf ) ary = tfh . asarray ( ) ...
def flowspec_prefix_add ( self , flowspec_family , rules , route_dist = None , actions = None ) : """This method adds a new Flow Specification prefix to be advertised . ` ` flowspec _ family ` ` specifies one of the flowspec family name . This parameter must be one of the following . - FLOWSPEC _ FAMILY _ IPV...
func_name = 'flowspec.add' # Set required arguments kwargs = { FLOWSPEC_FAMILY : flowspec_family , FLOWSPEC_RULES : rules , FLOWSPEC_ACTIONS : actions or { } , } if flowspec_family in [ FLOWSPEC_FAMILY_VPNV4 , FLOWSPEC_FAMILY_VPNV6 , FLOWSPEC_FAMILY_L2VPN ] : func_name = 'flowspec.add_local' kwargs . update ( {...
def srfxpt ( method , target , et , abcorr , obsrvr , dref , dvec ) : """Deprecated : This routine has been superseded by the CSPICE routine : func : ` sincpt ` . This routine is supported for purposes of backward compatibility only . Given an observer and a direction vector defining a ray , compute the sur...
method = stypes . stringToCharP ( method ) target = stypes . stringToCharP ( target ) abcorr = stypes . stringToCharP ( abcorr ) obsrvr = stypes . stringToCharP ( obsrvr ) dref = stypes . stringToCharP ( dref ) dvec = stypes . toDoubleVector ( dvec ) spoint = stypes . emptyDoubleVector ( 3 ) trgepc = ctypes . c_double ...
def zipsafe ( dist ) : """Returns whether or not we determine a distribution is zip - safe ."""
# zip - safety is only an attribute of eggs . wheels are considered never # zip safe per implications of PEP 427. if hasattr ( dist , 'egg_info' ) and dist . egg_info . endswith ( 'EGG-INFO' ) : egg_metadata = dist . metadata_listdir ( '' ) return 'zip-safe' in egg_metadata and 'native_libs.txt' not in egg_meta...
def uninstall ( ** kwargs ) : """Uninstall the current pre - commit hook ."""
force = kwargs . get ( 'force' ) restore_legacy = kwargs . get ( 'restore_legacy' ) colorama . init ( strip = kwargs . get ( 'no_color' ) ) git_dir = current_git_dir ( ) if git_dir is None : output ( NOT_GIT_REPO_MSG ) exit ( 1 ) hook_path = os . path . join ( git_dir , 'hooks' , 'pre-commit' ) if not os . path...
def set_host ( self , host ) : """Set the host for a lightning server . Host can be local ( e . g . http : / / localhost : 3000 ) , a heroku instance ( e . g . http : / / lightning - test . herokuapp . com ) , or a independently hosted lightning server ."""
if host [ - 1 ] == '/' : host = host [ : - 1 ] self . host = host return self
def Extract ( self , components ) : """Extracts interesting paths from a given path . Args : components : Source string represented as a list of components . Returns : A list of extracted paths ( as strings ) ."""
for index , component in enumerate ( components ) : if component . lower ( ) . endswith ( self . EXECUTABLE_EXTENSIONS ) : extracted_path = " " . join ( components [ 0 : index + 1 ] ) return [ extracted_path ] return [ ]
def directory_values_generator ( self , key ) : '''Retrieve directory values for given key .'''
directory = self . directory ( key ) for key in directory : yield self . get ( Key ( key ) )
async def create_role ( self , * , reason = None , ** fields ) : """| coro | Creates a : class : ` Role ` for the guild . All fields are optional . You must have the : attr : ` ~ Permissions . manage _ roles ` permission to do this . Parameters name : : class : ` str ` The role name . Defaults to ' ne...
try : perms = fields . pop ( 'permissions' ) except KeyError : fields [ 'permissions' ] = 0 else : fields [ 'permissions' ] = perms . value try : colour = fields . pop ( 'colour' ) except KeyError : colour = fields . get ( 'color' , Colour . default ( ) ) finally : fields [ 'color' ] = colour . ...
def process_default ( self , raw_event , to_append = None ) : """Commons handling for the followings events : IN _ ACCESS , IN _ MODIFY , IN _ ATTRIB , IN _ CLOSE _ WRITE , IN _ CLOSE _ NOWRITE , IN _ OPEN , IN _ DELETE , IN _ DELETE _ SELF , IN _ UNMOUNT ."""
watch_ = self . _watch_manager . get_watch ( raw_event . wd ) if raw_event . mask & ( IN_DELETE_SELF | IN_MOVE_SELF ) : # Unfornulately this information is not provided by the kernel dir_ = watch_ . dir else : dir_ = bool ( raw_event . mask & IN_ISDIR ) dict_ = { 'wd' : raw_event . wd , 'mask' : raw_event . mas...
def unsub ( feednames , delete , dontask ) : """Unsubscribe from the specified feed ( s ) ."""
ecode = 0 try : for feed in feednames : rc , msg = anchore_feeds . unsubscribe_anchore_feed ( feed ) if not rc : ecode = 1 anchore_print_err ( msg ) else : anchore_print ( msg ) if delete : dodelete = False if do...
def publish_queue_length ( self , redis_client , port , db ) : """: param redis _ client : Redis client : param db : Redis Database index : param port : Redis port : return : Redis queue length"""
for queue in redis_client . smembers ( 'queues' ) : queue_length = redis_client . llen ( 'queue:%s' % queue ) self . __publish ( port , db , queue , queue_length )
def current ( cls ) : """Helper method for getting the current peer of whichever host we ' re running on ."""
name = socket . getfqdn ( ) ip = socket . gethostbyname ( name ) return cls ( name , ip )
def plot_events_in_signal ( signal , events_onsets , color = "red" , marker = None ) : """Plot events in signal . Parameters signal : array or DataFrame Signal array ( can be a dataframe with many signals ) . events _ onsets : list or ndarray Events location . color : int or list Marker color . mark...
df = pd . DataFrame ( signal ) ax = df . plot ( ) def plotOnSignal ( x , color , marker = None ) : if ( marker is None ) : plt . axvline ( x = event , color = color ) else : plt . plot ( x , signal [ x ] , marker , color = color ) events_onsets = np . array ( events_onsets ) try : len ( even...
def free_symbols ( self ) : """Set of all symbols occcuring in S , L , or H"""
return set . union ( self . S . free_symbols , self . L . free_symbols , self . H . free_symbols )
def get_nnsoap ( obj , first_shell , alphas , betas , rcut = 6 , nmax = 10 , lmax = 9 , all_atomtypes = [ ] ) : """Takes cluster structure and nearest neighbour information of a datapoint , Returns concatenated soap vectors for each nearest neighbour ( up to 3 ) . Top , bridge , hollow fill the initial zero s...
soap_vector = [ ] nnn = len ( first_shell ) for tbh in range ( 0 , 3 ) : try : atom_idx = first_shell [ tbh ] except : soap_vector . append ( soap_zero ) else : Hpos = [ ] print ( atom_idx ) pos = obj . get_positions ( ) [ atom_idx ] Hpos . append ( pos ) ...
def to_python ( self ) : """Returns a plain python list and converts to plain python objects all this object ' s descendants ."""
result = list ( self ) for index , value in enumerate ( result ) : if isinstance ( value , DottedCollection ) : result [ index ] = value . to_python ( ) return result
def var_unset ( session , name ) : """Unsets the given variable"""
name = name . strip ( ) try : session . unset ( name ) except KeyError : session . write_line ( "Unknown variable: {0}" , name ) return False else : session . write_line ( "Variable {0} unset." , name ) return None
def _get_best_min_account ( self , cluster , adj_list , counts ) : '''return the min UMI ( s ) need to account for cluster'''
if len ( cluster ) == 1 : return list ( cluster ) sorted_nodes = sorted ( cluster , key = lambda x : counts [ x ] , reverse = True ) for i in range ( len ( sorted_nodes ) - 1 ) : if len ( remove_umis ( adj_list , cluster , sorted_nodes [ : i + 1 ] ) ) == 0 : return sorted_nodes [ : i + 1 ]
def get_objects ( self ) : """Returns the list of objects passed as this parameter"""
return rope . base . oi . soi . get_passed_objects ( self . pyfunction , self . index )
def validate_capacity ( capacity ) : """Validate ScalingConfiguration capacity for serverless DBCluster"""
if capacity not in VALID_SCALING_CONFIGURATION_CAPACITIES : raise ValueError ( "ScalingConfiguration capacity must be one of: {}" . format ( ", " . join ( map ( str , VALID_SCALING_CONFIGURATION_CAPACITIES ) ) ) ) return capacity
def create_datastore ( self , schema = None , primary_key = None , delete_first = 0 , path = None ) : # type : ( Optional [ List [ Dict ] ] , Optional [ str ] , int , Optional [ str ] ) - > None """For tabular data , create a resource in the HDX datastore which enables data preview in HDX . If no schema is provided...
if delete_first == 0 : pass elif delete_first == 1 : self . delete_datastore ( ) elif delete_first == 2 : if primary_key is None : self . delete_datastore ( ) else : raise HDXError ( 'delete_first must be 0, 1 or 2! (0 = No, 1 = Yes, 2 = Delete if no primary key)' ) if path is None : # Download ...
def wait ( self , timeout = None ) : """Wait for the job to complete , or a timeout to happen . This is more efficient than the version in the base Job class , in that we can use a call that blocks for the poll duration rather than a sleep . That means we shouldn ' t block unnecessarily long and can also poll...
poll = 30 while not self . _is_complete : try : query_result = self . _api . jobs_query_results ( self . _job_id , project_id = self . _context . project_id , page_size = 0 , timeout = poll * 1000 ) except Exception as e : raise e if query_result [ 'jobComplete' ] : if 'totalBytesPro...
def gridfs_namespace ( self , plain_src_ns ) : """Given a plain source namespace , return the corresponding plain target namespace if this namespace is a gridfs collection ."""
namespace = self . lookup ( plain_src_ns ) if namespace and namespace . gridfs : return namespace . dest_name return None
def setting ( key , default = None , expected_type = None , qsettings = None ) : """Helper function to get a value from settings under InaSAFE scope . : param key : Unique key for setting . : type key : basestring : param default : The default value in case of the key is not found or there is an error . :...
if default is None : default = inasafe_default_settings . get ( key , None ) full_key = '%s/%s' % ( APPLICATION_NAME , key ) return general_setting ( full_key , default , expected_type , qsettings )
def create_experiment ( self , workflow_type , microscope_type , plate_format , plate_acquisition_mode ) : '''Creates the experiment . Parameters workflow _ type : str workflow type microscope _ type : str microscope type plate _ format : int well - plate format , i . e . total number of wells per pla...
logger . info ( 'create experiment "%s"' , self . experiment_name ) content = { 'name' : self . experiment_name , 'workflow_type' : workflow_type , 'microscope_type' : microscope_type , 'plate_format' : plate_format , 'plate_acquisition_mode' : plate_acquisition_mode } url = self . _build_api_url ( '/experiments' ) res...
def files_sharedPublicURL ( self , * , id : str , ** kwargs ) -> SlackResponse : """Enables a file for public / external sharing . Args : id ( str ) : The file id . e . g . ' F1234467890'"""
self . _validate_xoxp_token ( ) kwargs . update ( { "id" : id } ) return self . api_call ( "files.sharedPublicURL" , json = kwargs )
def _make_matchers ( self , crontab ) : '''This constructs the full matcher struct .'''
crontab = _aliases . get ( crontab , crontab ) ct = crontab . split ( ) if len ( ct ) == 5 : ct . insert ( 0 , '0' ) ct . append ( '*' ) elif len ( ct ) == 6 : ct . insert ( 0 , '0' ) _assert ( len ( ct ) == 7 , "improper number of cron entries specified; got %i need 5 to 7" % ( len ( ct , ) ) ) matchers = ...
def write_to_ndef_service ( self , data , * blocks ) : """Write block data to an NDEF compatible tag . This is a convinience method to write block data to a tag that has system code 0x12FC ( NDEF ) . For other tags this method simply does nothing . The * data * to write must be a string or bytearray with le...
if self . sys == 0x12FC : sc_list = [ ServiceCode ( 0 , 0b001001 ) ] bc_list = [ BlockCode ( n ) for n in blocks ] self . write_without_encryption ( sc_list , bc_list , data )
def local_imports ( remote_base , local_base , ontologies , local_versions = tuple ( ) , readonly = False , dobig = False , revert = False ) : """Read the import closure and use the local versions of the files ."""
done = [ ] triples = set ( ) imported_iri_vs_ontology_iri = { } p = owl . imports oi = b'owl:imports' oo = b'owl:Ontology' def inner ( local_filepath , remote = False ) : if noneMembers ( local_filepath , * bigleaves ) or dobig : ext = os . path . splitext ( local_filepath ) [ - 1 ] if ext == '.ttl'...
def add_override ( self , symbol , ind , val , dt_log = None , user = None , comment = None ) : """Appends a single indexed - value pair , to a symbol object , to be used during the final steps of the aggregation of the datatable . With default settings Overrides , get applied with highest priority . Paramete...
self . _add_orfs ( 'override' , symbol , ind , val , dt_log , user , comment )
def validate_session ( self , session , latest_only = False ) : """Check that a session is present in the metadata dictionary . raises : exc : ` ~ billy . scrape . NoDataForPeriod ` if session is invalid : param session : string representing session to check"""
if latest_only : if session != self . metadata [ 'terms' ] [ - 1 ] [ 'sessions' ] [ - 1 ] : raise NoDataForPeriod ( session ) for t in self . metadata [ 'terms' ] : if session in t [ 'sessions' ] : return True raise NoDataForPeriod ( session )
def dispatch_request ( self ) : """Handle redirect back from provider"""
if current_user . is_authenticated : return redirect ( self . next ) # clear previous ! if 'social_data' in session : del session [ 'social_data' ] res = self . app . authorized_response ( ) if res is None : if self . flash : flash ( self . auth_failed_msg , 'danger' ) return redirect ( self . n...
def api_config ( path ) : '''Read in the Salt Master config file and add additional configs that need to be stubbed out for salt - api'''
# Let ' s grab a copy of salt - api ' s required defaults opts = DEFAULT_API_OPTS . copy ( ) # Let ' s override them with salt ' s master opts opts . update ( client_config ( path , defaults = DEFAULT_MASTER_OPTS . copy ( ) ) ) # Let ' s set the pidfile and log _ file values in opts to api settings opts . update ( { 'p...
def _Connect ( self , banner = None , ** kwargs ) : """Connect to the device . Args : banner : See protocol _ handler . Connect . * * kwargs : See protocol _ handler . Connect and adb _ commands . ConnectDevice for kwargs . Includes handle , rsa _ keys , and auth _ timeout _ ms . Returns : An instance o...
if not banner : banner = socket . gethostname ( ) . encode ( ) conn_str = self . protocol_handler . Connect ( self . _handle , banner = banner , ** kwargs ) # Remove banner and colons after device state ( state : : banner ) parts = conn_str . split ( b'::' ) self . _device_state = parts [ 0 ] # Break out the build ...
def get_trigger_data ( value , mode = 0 ) : '''Returns 31bit trigger counter ( mode = 0 ) , 31bit timestamp ( mode = 1 ) , 15bit timestamp and 16bit trigger counter ( mode = 2)'''
if mode == 2 : return np . right_shift ( np . bitwise_and ( value , 0x7FFF0000 ) , 16 ) , np . bitwise_and ( value , 0x0000FFFF ) else : return np . bitwise_and ( value , 0x7FFFFFFF )
def parse_solr_geo_range_as_pair ( geo_box_str ) : """: param geo _ box _ str : [ - 90 , - 180 TO 90,180] : return : ( " - 90 , - 180 " , " 90,180 " )"""
pattern = "\\[(.*) TO (.*)\\]" matcher = re . search ( pattern , geo_box_str ) if matcher : return matcher . group ( 1 ) , matcher . group ( 2 ) else : raise Exception ( "Regex {0} could not parse {1}" . format ( pattern , geo_box_str ) )
def rank ( values , axis = 0 , method = 'average' , na_option = 'keep' , ascending = True , pct = False ) : """Rank the values along a given axis . Parameters values : array - like Array whose values will be ranked . The number of dimensions in this array must not exceed 2. axis : int , default 0 Axis o...
if values . ndim == 1 : f , values = _get_data_algo ( values , _rank1d_functions ) ranks = f ( values , ties_method = method , ascending = ascending , na_option = na_option , pct = pct ) elif values . ndim == 2 : f , values = _get_data_algo ( values , _rank2d_functions ) ranks = f ( values , axis = axis...
def shapes_match ( a , b ) : """Recursively check if shapes of object ` a ` and ` b ` match . Will walk lists , tuples and dicts . Args : a : object of type ( numpy . ndarray , tf . Tensor , list , tuple , dict ) to check for matching shapes against ` b ` . b : object to check for matching shape against `...
if isinstance ( a , ( tuple , list ) ) and isinstance ( b , ( tuple , list ) ) : if len ( a ) != len ( b ) : return False return all ( [ shapes_match ( ia , ib ) for ia , ib in zip ( a , b ) ] ) elif isinstance ( a , dict ) and isinstance ( b , dict ) : if len ( a ) != len ( b ) : return Fal...
def get_region ( self , ip ) : '''Get region'''
rec = self . get_all ( ip ) return rec and rec . region
def Package ( env , target = None , source = None , ** kw ) : """Entry point for the package tool ."""
# check if we need to find the source files ourself if not source : source = env . FindInstalledFiles ( ) if len ( source ) == 0 : raise UserError ( "No source for Package() given" ) # decide which types of packages shall be built . Can be defined through # four mechanisms : command line argument , keyword argu...
def register ( event = None ) : """Decorator method to * register * event handlers . This is the client - less ` add _ event _ handler < telethon . client . updates . UpdateMethods . add _ event _ handler > ` variant . Note that this method only registers callbacks as handlers , and does not attach them to ...
if isinstance ( event , type ) : event = event ( ) elif not event : event = Raw ( ) def decorator ( callback ) : handlers = getattr ( callback , _HANDLERS_ATTRIBUTE , [ ] ) handlers . append ( event ) setattr ( callback , _HANDLERS_ATTRIBUTE , handlers ) return callback return decorator
def move_in ( self , space , offset , length , width , extended = False ) : """Moves a block of data to local memory from the specified address space and offset . : param space : Specifies the address space . ( Constants . * SPACE * ) : param offset : Offset ( in bytes ) of the address or register from which to...
return self . visalib . move_in ( self . session , space , offset , length , width , extended )
def print_maps_by_type ( map_type , number = None ) : """Print all available maps of a given type . Parameters map _ type : { ' Sequential ' , ' Diverging ' , ' Qualitative ' } Select map type to print . number : int , optional Filter output by number of defined colors . By default there is no numeric f...
map_type = map_type . lower ( ) . capitalize ( ) if map_type not in MAP_TYPES : s = 'Invalid map type, must be one of {0}' . format ( MAP_TYPES ) raise ValueError ( s ) print ( map_type ) map_keys = sorted ( COLOR_MAPS [ map_type ] . keys ( ) ) format_str = '{0:8} : {1}' for mk in map_keys : num_keys = so...
def restricted_brands ( self ) : """| Comment : ids of all brands that this ticket form is restricted to"""
if self . api and self . restricted_brand_ids : return self . api . _get_restricted_brands ( self . restricted_brand_ids )
def print_all_param_defaults ( ) : """Print the default values for all imported Parameters ."""
print ( "_______________________________________________________________________________" ) print ( "" ) print ( " Parameter Default Values" ) print ( "" ) classes = descendents ( Parameterized ) classes . sort ( key = lambda x : x . __name__ ) for c in classes : c . print_param_defaults (...
def DeserializeMessage ( self , response_type , data ) : """Deserialize the given data as method _ config . response _ type ."""
try : message = encoding . JsonToMessage ( response_type , data ) except ( exceptions . InvalidDataFromServerError , messages . ValidationError , ValueError ) as e : raise exceptions . InvalidDataFromServerError ( 'Error decoding response "%s" as type %s: %s' % ( data , response_type . __name__ , e ) ) return m...
def get_analysis_data_for ( self , ar ) : """Return the Analysis data for this AR"""
# Exclude analyses from children ( partitions ) analyses = ar . objectValues ( "Analysis" ) out = [ ] for an in analyses : info = self . get_base_info ( an ) info . update ( { "service_uid" : an . getServiceUID ( ) , } ) out . append ( info ) return out
def plot_pnlmoney ( self ) : """画出pnl盈亏额散点图"""
plt . scatter ( x = self . pnl . sell_date . apply ( str ) , y = self . pnl . pnl_money ) plt . gcf ( ) . autofmt_xdate ( ) return plt
def xlsx_part ( self ) : """Return the related | EmbeddedXlsxPart | object having its rId at ` c : chartSpace / c : externalData / @ rId ` or | None | if there is no ` < c : externalData > ` element ."""
xlsx_part_rId = self . _chartSpace . xlsx_part_rId if xlsx_part_rId is None : return None return self . _chart_part . related_parts [ xlsx_part_rId ]
def proxy_manager_for ( self , proxy , ** proxy_kwargs ) : """Return urllib3 ProxyManager for the given proxy . This method should not be called from user code , and is only exposed for use when subclassing the : class : ` HTTPAdapter < requests . adapters . HTTPAdapter > ` . : param proxy : The proxy to re...
if not proxy in self . proxy_manager : proxy_headers = self . proxy_headers ( proxy ) self . proxy_manager [ proxy ] = proxy_from_url ( proxy , proxy_headers = proxy_headers , num_pools = self . _pool_connections , maxsize = self . _pool_maxsize , block = self . _pool_block , ** proxy_kwargs ) return self . pro...
def amplification_type ( self , channels = None ) : """Get the amplification type used for the specified channel ( s ) . Each channel uses one of two amplification types : linear or logarithmic . This function returns , for each channel , a tuple of two numbers , in which the first number indicates the number...
# Check default if channels is None : channels = self . _channels # Get numerical indices of channels channels = self . _name_to_index ( channels ) # Get detector type of the specified channels if hasattr ( channels , '__iter__' ) and not isinstance ( channels , six . string_types ) : return [ self . _amplifica...
def stage_tc ( self , owner , staging_data , variable ) : """Stage data using ThreatConnect API . . . code - block : : javascript " data " : { " id " : 116, " value " : " adversary001 - build - testing " , " type " : " Adversary " , " ownerName " : " qa - build " , " dateAdded " : " 2017-08-16T18:35:0...
# parse resource _ data resource_type = staging_data . pop ( 'type' ) if resource_type in self . tcex . indicator_types or resource_type in self . tcex . group_types : try : attributes = staging_data . pop ( 'attribute' ) except KeyError : attributes = [ ] try : security_labels = sta...
def encrypt ( message , keyPath ) : """Encrypts a message given a path to a local file containing a key . : param message : The message to be encrypted . : param keyPath : A path to a file containing a 256 - bit key ( and nothing else ) . : type message : bytes : type keyPath : str : rtype : bytes A con...
with open ( keyPath , 'rb' ) as f : key = f . read ( ) if len ( key ) != SecretBox . KEY_SIZE : raise ValueError ( "Key is %d bytes, but must be exactly %d bytes" % ( len ( key ) , SecretBox . KEY_SIZE ) ) sb = SecretBox ( key ) # We generate the nonce using secure random bits . For long enough # nonce size , t...
def next_frame_basic_stochastic_discrete ( ) : """Basic 2 - frame conv model with stochastic discrete latent ."""
hparams = basic_deterministic_params . next_frame_sampling ( ) hparams . batch_size = 4 hparams . video_num_target_frames = 6 hparams . scheduled_sampling_mode = "prob_inverse_lin" hparams . scheduled_sampling_decay_steps = 40000 hparams . scheduled_sampling_max_prob = 1.0 hparams . dropout = 0.15 hparams . filter_doub...
def start ( self , tag , attrib ) : """On start of element tag"""
if tag == E_CLINICAL_DATA : self . ref_state = AUDIT_REF_STATE self . context = Context ( attrib [ A_STUDY_OID ] , attrib [ A_AUDIT_SUBCATEGORY_NAME ] , int ( attrib [ A_METADATA_VERSION_OID ] ) ) elif tag == E_SUBJECT_DATA : self . context . subject = Subject ( attrib . get ( A_SUBJECT_KEY ) , attrib . get...
def _basic_auth_str ( username , password ) : """Returns a Basic Auth string ."""
# " I want us to put a big - ol ' comment on top of it that # says that this behaviour is dumb but we need to preserve # it because people are relying on it . " # - Lukasa # These are here solely to maintain backwards compatibility # for things like ints . This will be removed in 3.0.0. if not isinstance ( username , b...
def recipe ( package , repository = None , depends_on = None , release = False , output_path = None , auto = False , overwrite = False , name = None ) : """Create a new upgrade recipe , for developers ."""
upgrader = InvenioUpgrader ( ) logger = upgrader . get_logger ( ) try : path , found_repository = _upgrade_recipe_find_path ( package ) if output_path : path = output_path if not repository : repository = found_repository if not os . path . exists ( path ) : raise RuntimeError ( ...
def _get_distance_segment_coefficients ( self , rval ) : """Returns the coefficients describing the distance attenuation shape for three different distance bins , equations 12a - 12c"""
# Get distance segment ends nsites = len ( rval ) # Equation 12a f_0 = np . log10 ( self . CONSTS [ "r0" ] / rval ) f_0 [ rval > self . CONSTS [ "r0" ] ] = 0.0 # Equation 12b f_1 = np . log10 ( rval ) f_1 [ rval > self . CONSTS [ "r1" ] ] = np . log10 ( self . CONSTS [ "r1" ] ) # Equation 12c f_2 = np . log10 ( rval / ...
def has_comic ( name ) : """Check if comic name already exists ."""
names = [ ( "Creators/%s" % name ) . lower ( ) , ( "GoComics/%s" % name ) . lower ( ) , ] for scraperclass in get_scraperclasses ( ) : lname = scraperclass . getName ( ) . lower ( ) if lname in names : return True return False
def disable ( self ) : """Disable the Cloud . : returns : A list of mist . clients ' updated clouds ."""
payload = { "new_state" : "0" } data = json . dumps ( payload ) req = self . request ( self . mist_client . uri + '/clouds/' + self . id , data = data ) req . post ( ) self . enabled = False self . mist_client . update_clouds ( )
def log_flush_for_obj_for_interval ( self , log_type , obj_id , interval ) : """Flush logs for an interval of time for a specific object . Please note , log _ type is a variable according to the API docs , but acceptable values are not listed . Only " policies " is demonstrated as an acceptable value . Args...
if not log_type : log_type = "policies" # The XML for the / logflush basic endpoint allows spaces # instead of " + " , so do a replace here just in case . interval = interval . replace ( " " , "+" ) flush_url = "{}/{}/id/{}/interval/{}" . format ( self . url , log_type , obj_id , interval ) self . jss . delete ( fl...
def callHook ( self , hookname , * args , ** kwargs ) : 'Call all functions registered with ` addHook ` for the given hookname .'
r = [ ] for f in self . hooks [ hookname ] : try : r . append ( f ( * args , ** kwargs ) ) except Exception as e : exceptionCaught ( e ) return r
def get_custom_values ( self , key ) : """Return a set of values for the given customParameter name ."""
self . _handled . add ( key ) return self . _lookup [ key ]
def get_scm_status ( config , read_modules = False , repo_url = None , mvn_repo_local = None , additional_params = None ) : """Gets the artifact status ( MavenArtifact instance ) from SCM defined by config . Only the top - level artifact is read by default , although it can be requested to read the whole availabl...
global scm_status_cache if config . artifact in scm_status_cache . keys ( ) : result = scm_status_cache [ config . artifact ] elif not read_modules and ( ( "%s|False" % config . artifact ) in scm_status_cache . keys ( ) ) : result = scm_status_cache [ "%s|False" % config . artifact ] else : result = _get_sc...
def schedule ( self , task ) : """Schedules a new Task in the PoolManager ."""
self . task_manager . register ( task ) self . worker_manager . dispatch ( task )
def getOutputDevice ( self , textureType ) : """* Returns platform - and texture - type specific adapter identification so that applications and the compositor are creating textures and swap chains on the same GPU . If an error occurs the device will be set to 0. pInstance is an optional parameter that is req...
fn = self . function_table . getOutputDevice pnDevice = c_uint64 ( ) pInstance = VkInstance_T ( ) fn ( byref ( pnDevice ) , textureType , byref ( pInstance ) ) return pnDevice . value , pInstance
def productinfo ( self ) : """Return the productversion and channel of this MAR if present ."""
if not self . mardata . additional : return None for s in self . mardata . additional . sections : if s . id == 1 : return str ( s . productversion ) , str ( s . channel ) return None
def startstop ( inst_id , cmdtodo ) : """Start or Stop the Specified Instance . Args : inst _ id ( str ) : instance - id to perform command against cmdtodo ( str ) : command to perform ( start or stop ) Returns : response ( dict ) : reponse returned from AWS after performing specified action ."""
tar_inst = EC2R . Instance ( inst_id ) thecmd = getattr ( tar_inst , cmdtodo ) response = thecmd ( ) return response
def __get_document ( self , content ) : """Returns a ` QTextDocument < http : / / doc . qt . nokia . com / qtextdocument . html > ` _ class instance with given content . : return : Document . : rtype : QTextDocument"""
document = QTextDocument ( QString ( content ) ) document . clearUndoRedoStacks ( ) document . setModified ( False ) return document
def local_expiring_lru ( obj ) : """Property that maps to a key in a local dict - like attribute . self . _ cache must be an OrderedDict self . _ cache _ size must be defined as LRU size self . _ cache _ ttl is the expiration time in seconds class Foo ( object ) : def _ _ init _ _ ( self , cache _ size = ...
@ wraps ( obj ) def memoizer ( * args , ** kwargs ) : instance = args [ 0 ] lru_size = instance . _cache_size cache_ttl = instance . _cache_ttl if lru_size and cache_ttl : cache = instance . _cache kargs = list ( args ) kargs [ 0 ] = id ( instance ) key = str ( ( kargs , ...
def _erase_in_line ( self , type_of = 0 ) : """Erases the row in a specific way , depending on the type _ of ."""
row = self . display [ self . y ] attrs = self . attributes [ self . y ] if type_of == 0 : # Erase from the cursor to the end of line , including the cursor row = row [ : self . x ] + u" " * ( self . size [ 1 ] - self . x ) attrs = attrs [ : self . x ] + [ self . default_attributes ] * ( self . size [ 1 ] - sel...
async def connect ( self , * args , ** kwargs ) : """Connect to a Juju controller . This supports two calling conventions : The controller and ( optionally ) authentication information can be taken from the data files created by the Juju CLI . This convention will be used if a ` ` controller _ name ` ` is s...
await self . disconnect ( ) if 'endpoint' not in kwargs and len ( args ) < 2 : if args and 'model_name' in kwargs : raise TypeError ( 'connect() got multiple values for ' 'controller_name' ) elif args : controller_name = args [ 0 ] else : controller_name = kwargs . pop ( 'controller_...
def MultiDelete ( self , urns , token = None ) : """Drop all the information about given objects . DANGEROUS ! This recursively deletes all objects contained within the specified URN . Args : urns : Urns of objects to remove . token : The Security Token to use for opening this item . Raises : ValueErr...
urns = [ rdfvalue . RDFURN ( urn ) for urn in urns ] if token is None : token = data_store . default_token for urn in urns : if urn . Path ( ) == "/" : raise ValueError ( "Can't delete root URN. Please enter a valid URN" ) deletion_pool = DeletionPool ( token = token ) deletion_pool . MultiMarkForDeleti...
def dtdQElementDesc ( self , name , prefix ) : """Search the DTD for the description of this element"""
ret = libxml2mod . xmlGetDtdQElementDesc ( self . _o , name , prefix ) if ret is None : raise treeError ( 'xmlGetDtdQElementDesc() failed' ) __tmp = xmlElement ( _obj = ret ) return __tmp
def _get_time_stamp ( entry ) : """Return datetime object from a timex constraint start / end entry . Example string format to convert : 2018-01-01T00:00"""
if not entry or entry == 'Undef' : return None try : dt = datetime . datetime . strptime ( entry , '%Y-%m-%dT%H:%M' ) except Exception as e : logger . debug ( 'Could not parse %s format' % entry ) return None return dt
def declare_api_routes ( config ) : """Declare routes , with a custom pregenerator ."""
# The pregenerator makes sure we can generate a path using # request . route _ path even if we don ' t have all the variables . # For example , instead of having to do this : # request . route _ path ( ' resource ' , hash = hash , ignore = ' ' ) # it ' s possible to do this : # request . route _ path ( ' resource ' , h...
def generate_broadcast_to ( node_name , x , y , out_name , axis , base_name , func_counter ) : """Generate a BroadcastTo operator to brodcast specified buffer"""
bt = nnabla_pb2 . Function ( ) bt . type = "BroadcastTo" set_function_name ( bt , node_name , base_name , func_counter ) bt . input . extend ( [ x , y ] ) bt . output . extend ( [ out_name ] ) btp = bt . broadcast_to_param btp . axis = axis return bt
def continue_with ( self , continuation_func , * args ) : """Create a continuation that executes when the Future is completed . : param continuation _ func : A function which takes the future as the only parameter . Return value of the function will be set as the result of the continuation future . : return :...
future = Future ( ) def callback ( f ) : try : future . set_result ( continuation_func ( f , * args ) ) except : future . set_exception ( sys . exc_info ( ) [ 1 ] , sys . exc_info ( ) [ 2 ] ) self . add_done_callback ( callback ) return future
def as_dash_instance ( self , cache_id = None ) : 'Return a dash application instance for this model instance'
dash_app = self . stateless_app . as_dash_app ( ) # pylint : disable = no - member base = self . current_state ( ) return dash_app . do_form_dash_instance ( replacements = base , specific_identifier = self . slug , cache_id = cache_id )
def tn_mean ( tasmin , freq = 'YS' ) : r"""Mean minimum temperature . Mean of daily minimum temperature . Parameters tasmin : xarray . DataArray Minimum daily temperature [ ° C ] or [ K ] freq : str , optional Resampling frequency Returns xarray . DataArray Mean of daily minimum temperature . No...
arr = tasmin . resample ( time = freq ) if freq else tasmin return arr . mean ( dim = 'time' , keep_attrs = True )
def compare_words_lexicographic ( word_a , word_b ) : """compare words in Tamil lexicographic order"""
# sanity check for words to be all Tamil if ( not all_tamil ( word_a ) ) or ( not all_tamil ( word_b ) ) : # print ( " # # " ) # print ( word _ a ) # print ( word _ b ) # print ( " Both operands need to be Tamil words " ) pass La = len ( word_a ) Lb = len ( word_b ) all_TA_letters = u"" . join ( tamil_letters ) for...
def generate_data_key ( self , name , key_type , context = "" , nonce = "" , bits = 256 , mount_point = DEFAULT_MOUNT_POINT ) : """Generates a new high - entropy key and the value encrypted with the named key . Optionally return the plaintext of the key as well . Whether plaintext is returned depends on the path ...
if key_type not in transit_constants . ALLOWED_DATA_KEY_TYPES : error_msg = 'invalid key_type argument provided "{arg}", supported types: "{allowed_types}"' raise exceptions . ParamValidationError ( error_msg . format ( arg = key_type , allowed_types = ', ' . join ( transit_constants . ALLOWED_DATA_KEY_TYPES ) ...
def get_maxcov_downsample_cl ( data , in_pipe = None ) : """Retrieve command line for max coverage downsampling , fitting into bamsormadup output ."""
max_cov = _get_maxcov_downsample ( data ) if dd . get_aligner ( data ) not in [ "snap" ] else None if max_cov : if in_pipe == "bamsormadup" : prefix = "level=0" elif in_pipe == "samtools" : prefix = "-l 0" else : prefix = "" # Swap over to multiple cores until after testing #...
def categorical_df_concat ( df_list , inplace = False ) : """Prepare list of pandas DataFrames to be used as input to pd . concat . Ensure any columns of type ' category ' have the same categories across each dataframe . Parameters df _ list : list List of dataframes with same columns . inplace : bool ...
if not inplace : df_list = deepcopy ( df_list ) # Assert each dataframe has the same columns / dtypes df = df_list [ 0 ] if not all ( [ ( df . dtypes . equals ( df_i . dtypes ) ) for df_i in df_list [ 1 : ] ] ) : raise ValueError ( "Input DataFrames must have the same columns/dtypes." ) categorical_columns = df...