signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def unique_ordered ( list_ ) : """Returns unique items in ` ` list _ ` ` in the order they were seen . Args : list _ ( list ) : Returns : list : unique _ list - unique list which maintains order CommandLine : python - m utool . util _ list - - exec - unique _ ordered Example : > > > # ENABLE _ DOCTE...
list_ = list ( list_ ) flag_list = flag_unique_items ( list_ ) unique_list = compress ( list_ , flag_list ) return unique_list
def add ( self , ipaddr = None , proto = None , port = None , fields = None ) : """Add a service record : param ipaddr : IP Address : param proto : Protocol ( tcp , udp , info ) : param port : Port ( 0-65535) : param fields : Extra fields : return : ( True / False , t _ services . id or response message )...
return self . send . service_add ( ipaddr , proto , port , fields )
def add_node ( cls , cluster_id_label , parameters = None ) : """Add a node to an existing cluster"""
conn = Qubole . agent ( version = Cluster . api_version ) parameters = { } if not parameters else parameters return conn . post ( cls . element_path ( cluster_id_label ) + "/nodes" , data = { "parameters" : parameters } )
def _startup ( cls ) : """Create Endpoint instances and manage automatic flags ."""
for endpoint_name in sorted ( hookenv . relation_types ( ) ) : # populate context based on attached relations relf = relation_factory ( endpoint_name ) if not relf or not issubclass ( relf , cls ) : continue rids = sorted ( hookenv . relation_ids ( endpoint_name ) ) # ensure that relation IDs ha...
def _default_request_kwargs ( self ) : """The default request keyword arguments to be passed to the requests library ."""
defaults = copy . deepcopy ( super ( Acls , self ) . _default_request_kwargs ) defaults . setdefault ( 'headers' , { } ) . update ( { 'X-Auth-Token' : self . _client . auth . _token } ) return defaults
def split_namespace ( self , tag ) : r"""Split tag namespace . : param tag : tag name : return : a pair of ( namespace , tag ) : rtype : tuple"""
matchobj = self . __regex [ 'xml_ns' ] . search ( tag ) return matchobj . groups ( ) if matchobj else ( '' , tag )
def _is_statement_in_list ( new_stmt , old_stmt_list ) : """Return True of given statement is equivalent to on in a list Determines whether the statement is equivalent to any statement in the given list of statements , with equivalency determined by Statement ' s equals method . Parameters new _ stmt : in...
for old_stmt in old_stmt_list : if old_stmt . equals ( new_stmt ) : return True elif old_stmt . evidence_equals ( new_stmt ) and old_stmt . matches ( new_stmt ) : # If we ' re comparing a complex , make sure the agents are sorted . if isinstance ( new_stmt , Complex ) : agent_pairs =...
def policy_definition_absent ( name , connection_auth = None ) : '''. . versionadded : : 2019.2.0 Ensure a policy definition does not exist in the current subscription . : param name : Name of the policy definition . : param connection _ auth : A dict with subscription and authentication parameters to be ...
ret = { 'name' : name , 'result' : False , 'comment' : '' , 'changes' : { } } if not isinstance ( connection_auth , dict ) : ret [ 'comment' ] = 'Connection information must be specified via connection_auth dictionary!' return ret policy = __salt__ [ 'azurearm_resource.policy_definition_get' ] ( name , azurearm...
def get_throttled_by_provisioned_read_event_percent ( table_name , gsi_name , lookback_window_start = 15 , lookback_period = 5 ) : """Returns the number of throttled read events in percent : type table _ name : str : param table _ name : Name of the DynamoDB table : type gsi _ name : str : param gsi _ name ...
try : metrics = __get_aws_metric ( table_name , gsi_name , lookback_window_start , lookback_period , 'ReadThrottleEvents' ) except BotoServerError : raise if metrics : lookback_seconds = lookback_period * 60 throttled_read_events = ( float ( metrics [ 0 ] [ 'Sum' ] ) / float ( lookback_seconds ) ) else ...
def _unpack ( formatstring , packed ) : """Unpack a bytestring into a value . Uses the built - in : mod : ` struct ` Python module . Args : * formatstring ( str ) : String for the packing . See the : mod : ` struct ` module for details . * packed ( str ) : The bytestring to be unpacked . Returns : A val...
_checkString ( formatstring , description = 'formatstring' , minlength = 1 ) _checkString ( packed , description = 'packed string' , minlength = 1 ) if sys . version_info [ 0 ] > 2 : packed = bytes ( packed , encoding = 'latin1' ) # Convert types to make it Python3 compatible try : value = struct . unpack ( for...
def user_info ( self , username ) : """Get info of a specific user . : param username : the username of the user to get info about : return :"""
request_url = "{}/api/0/user/{}" . format ( self . instance , username ) return_value = self . _call_api ( request_url ) return return_value
def _outliers ( self , x ) : """Compute number of outliers"""
outliers = self . _tukey ( x , threshold = 1.5 ) return np . size ( outliers )
def read_cz_sem ( fh , byteorder , dtype , count , offsetsize ) : """Read Zeiss SEM tag and return as dict . See https : / / sourceforge . net / p / gwyddion / mailman / message / 29275000 / for unnamed values ."""
result = { '' : ( ) } key = None data = bytes2str ( stripnull ( fh . read ( count ) ) ) for line in data . splitlines ( ) : if line . isupper ( ) : key = line . lower ( ) elif key : try : name , value = line . split ( '=' ) except ValueError : try : ...
def state ( self ) : """Personsa state ( e . g . Online , Offline , Away , Busy , etc ) : rtype : : class : ` . EPersonaState `"""
state = self . get_ps ( 'persona_state' , False ) return EPersonaState ( state ) if state else EPersonaState . Offline
def _get_constrs_load_memory ( self , gadget ) : """Generate constraints for the LoadMemory gadgets : dst _ reg < - mem [ src _ reg + offset ]"""
dst = self . analyzer . get_register_expr ( gadget . destination [ 0 ] . name , mode = "post" ) size = gadget . destination [ 0 ] . size if isinstance ( gadget . sources [ 0 ] , ReilRegisterOperand ) : base_addr = self . analyzer . get_register_expr ( gadget . sources [ 0 ] . name , mode = "pre" ) offset = gadg...
def QA_util_get_real_datelist ( start , end ) : """取数据的真实区间 , 返回的时候用 start , end = QA _ util _ get _ real _ datelist @ yutiansut 2017/8/10 当start end中间没有交易日 返回None , None @ yutiansut / 2017-12-19"""
real_start = QA_util_get_real_date ( start , trade_date_sse , 1 ) real_end = QA_util_get_real_date ( end , trade_date_sse , - 1 ) if trade_date_sse . index ( real_start ) > trade_date_sse . index ( real_end ) : return None , None else : return ( real_start , real_end )
def nx_transitive_reduction ( G , mode = 1 ) : """References : https : / / en . wikipedia . org / wiki / Transitive _ reduction # Computing _ the _ reduction _ using _ the _ closure http : / / dept - info . labri . fr / ~ thibault / tmp / 0201008 . pdf http : / / stackoverflow . com / questions / 17078696 / t...
import utool as ut has_cycles = not nx . is_directed_acyclic_graph ( G ) if has_cycles : # FIXME : this does not work for cycle graphs . # Need to do algorithm on SCCs G_orig = G G = nx . condensation ( G_orig ) nodes = list ( G . nodes ( ) ) node2_idx = ut . make_index_lookup ( nodes ) # For each node u , perf...
def check_environment ( provider_conf ) : """Check all ressources needed by Enos ."""
session = get_session ( ) image_id = check_glance ( session , provider_conf . image ) flavor_to_id , id_to_flavor = check_flavors ( session ) ext_net , network , subnet = check_network ( session , provider_conf . configure_network , provider_conf . network , subnet = provider_conf . subnet , dns_nameservers = provider_...
def parse_requirements ( file_ ) : """Parse a requirements formatted file . Traverse a string until a delimiter is detected , then split at said delimiter , get module name by element index , create a dict consisting of module : version , and add dict to list of parsed modules . Args : file _ : File to pa...
modules = [ ] delim = [ "<" , ">" , "=" , "!" , "~" ] # https : / / www . python . org / dev / peps / pep - 0508 / # complete - grammar try : f = open_func ( file_ , "r" ) except OSError : logging . error ( "Failed on file: {}" . format ( file_ ) ) raise else : data = [ x . strip ( ) for x in f . readli...
def set_initial_state ( self , initial_state , initial_frames ) : """Sets the state that will be used on next reset ."""
self . env . set_initial_state ( initial_state , initial_frames ) self . _initial_frames = initial_frames
async def acquire_lease_async ( self , lease ) : """Acquire the lease on the desired partition for this EventProcessorHost . Note that it is legal to acquire a lease that is already owned by another host . Lease - stealing is how partitions are redistributed when additional hosts are started . : param lease :...
retval = True new_lease_id = str ( uuid . uuid4 ( ) ) partition_id = lease . partition_id try : if asyncio . iscoroutinefunction ( lease . state ) : state = await lease . state ( ) else : state = lease . state ( ) if state == "leased" : if not lease . token : # We reach here in a rac...
def is_escalable ( self , notification , escalations , timeperiods ) : """Check if a notification can be escalated . Basically call is _ eligible for each escalation : param notification : notification we would like to escalate : type notification : alignak . objects . notification . Notification : param es...
cls = self . __class__ # We search since when we are in notification for escalations # that are based on time in_notif_time = time . time ( ) - notification . creation_time # Check is an escalation match the current _ notification _ number for escalation_id in self . escalations : escalation = escalations [ escalat...
def is_purine ( nucleotide , allow_extended_nucleotides = False ) : """Is the nucleotide a purine"""
if not allow_extended_nucleotides and nucleotide not in STANDARD_NUCLEOTIDES : raise ValueError ( "{} is a non-standard nucleotide, neither purine or pyrimidine" . format ( nucleotide ) ) return nucleotide in PURINE_NUCLEOTIDES
def triplifyGML ( fname = "foo.gml" , fpath = "./fb/" , scriptpath = None , uid = None , sid = None , extra_info = None ) : """Produce a linked data publication tree from a standard GML file . INPUTS : = > the file name ( fname , with path ) where the gdf file of the friendship network is . = > the final pa...
# aname = fname . split ( " / " ) [ - 1 ] . split ( " . " ) [ 0] aname = fname . split ( "/" ) [ - 1 ] . split ( "." ) [ 0 ] if "RonaldCosta" in fname : aname = fname . split ( "/" ) [ - 1 ] . split ( "." ) [ 0 ] name , day , month , year = re . findall ( ".*/([a-zA-Z]*)(\d\d)(\d\d)(\d\d\d\d).gml" , fname ) [ 0...
def venv_resolve_deps ( deps , which , project , pre = False , clear = False , allow_global = False , pypi_mirror = None , dev = False , pipfile = None , lockfile = None , keep_outdated = False ) : """Resolve dependencies for a pipenv project , acts as a portal to the target environment . Regardless of whether a ...
from . vendor . vistir . misc import fs_str from . vendor . vistir . compat import Path , JSONDecodeError , NamedTemporaryFile from . vendor . vistir . path import create_tracked_tempdir from . import resolver from . _compat import decode_for_output import json results = [ ] pipfile_section = "dev-packages" if dev else...
def _generate_field_with_default ( ** kwargs ) : """Only called if field . default ! = NOT _ PROVIDED"""
field = kwargs [ 'field' ] if callable ( field . default ) : return field . default ( ) return field . default
def _populate_profile_flags_from_dn_regex ( self , profile ) : """Populate the given profile object flags from AUTH _ LDAP _ PROFILE _ FLAGS _ BY _ DN _ REGEX . Returns True if the profile was modified"""
save_profile = True for field , regex in self . settings . PROFILE_FLAGS_BY_DN_REGEX . items ( ) : field_value = False if re . search ( regex , self . _get_user_dn ( ) , re . IGNORECASE ) : field_value = True setattr ( profile , field , field_value ) save_profile = True return save_profile
def replace_body_vars ( self , body ) : """Given a multiline string that is the body of the job script , replace the placeholders for environment variables with backend - specific realizations , and return the modified body . See the ` job _ vars ` attribute for the mappings that are performed ."""
for key , val in self . job_vars . items ( ) : body = body . replace ( key , val ) return body
def compare_ecp_pots ( potential1 , potential2 , compare_meta = False , rel_tol = 0.0 ) : '''Compare two ecp potentials for approximate equality ( exponents / coefficients are within a tolerance ) If compare _ meta is True , the metadata is also compared for exact equality .'''
if potential1 [ 'angular_momentum' ] != potential2 [ 'angular_momentum' ] : return False rexponents1 = potential1 [ 'r_exponents' ] rexponents2 = potential2 [ 'r_exponents' ] gexponents1 = potential1 [ 'gaussian_exponents' ] gexponents2 = potential2 [ 'gaussian_exponents' ] coefficients1 = potential1 [ 'coefficient...
def main ( ) : """NAME di _ eq . py DESCRIPTION converts dec , inc pairs to x , y pairs using equal area projection NB : do only upper or lower hemisphere at a time : does not distinguish between up and down . SYNTAX di _ eq . py [ command line options ] [ < filename ] OPTIONS - h prints help messag...
out = "" UP = 0 if '-h' in sys . argv : print ( main . __doc__ ) sys . exit ( ) if '-f' in sys . argv : ind = sys . argv . index ( '-f' ) file = sys . argv [ ind + 1 ] DI = numpy . loadtxt ( file , dtype = numpy . float ) else : DI = numpy . loadtxt ( sys . stdin , dtype = numpy . float ) # ...
def _import ( self ) : """Makes imports : return :"""
import os . path import gspread self . path = os . path self . gspread = gspread self . _login ( )
def reduce ( self , values , inplace = True ) : """Reduces the factor to the context of the given variable values . Parameters values : list , array - like A list of tuples of the form ( variable _ name , variable _ value ) . inplace : boolean If inplace = True it will modify the factor itself , else woul...
phi = self if inplace else self . copy ( ) phi . distribution = phi . distribution . reduce ( values , inplace = False ) if not inplace : return phi
def hidden_from ( self , a , b ) : """Return True if ` ` a ` ` is hidden in a different box than ` ` b ` ` ."""
return a in self . hidden_indices and not self . in_same_box ( a , b )
def get_sensor_data ( ** kwargs ) : '''Get sensor readings Iterates sensor reading objects : param kwargs : - api _ host = 127.0.0.1 - api _ user = admin - api _ pass = example - api _ port = 623 - api _ kg = None CLI Example : . . code - block : : bash salt - call ipmi . get _ sensor _ data api...
import ast with _IpmiCommand ( ** kwargs ) as s : data = { } for reading in s . get_sensor_data ( ) : if reading : r = ast . literal_eval ( repr ( reading ) ) data [ r . pop ( 'name' ) ] = r return data
def calculate_bucket_level ( k , b ) : """Calculate the level in which a 0 - based bucket lives inside of a k - ary heap ."""
assert k >= 2 if k == 2 : return log2floor ( b + 1 ) v = ( k - 1 ) * ( b + 1 ) + 1 h = 0 while k ** ( h + 1 ) < v : h += 1 return h
def reciprocal_remove ( self ) : """Removes results rows for which the n - gram is not present in at least one text in each labelled set of texts ."""
self . _logger . info ( 'Removing n-grams that are not attested in all labels' ) self . _matches = self . _reciprocal_remove ( self . _matches )
def virtual ( opts , virtualname , filename ) : '''Returns the _ _ virtual _ _ .'''
if ( ( HAS_NAPALM and NAPALM_MAJOR >= 2 ) or HAS_NAPALM_BASE ) and ( is_proxy ( opts ) or is_minion ( opts ) ) : return virtualname else : return ( False , ( '"{vname}"" {filename} cannot be loaded: ' 'NAPALM is not installed: ``pip install napalm``' ) . format ( vname = virtualname , filename = '({filename})' ...
def get_storage_pools ( self , id_or_uri ) : """Gets a list of Storage pools . Returns a list of storage pools belonging to the storage system referred by the Path property { ID } parameter or URI . Args : id _ or _ uri : Can be either the storage system ID ( serial number ) or the storage system URI . Retu...
uri = self . _client . build_uri ( id_or_uri ) + "/storage-pools" return self . _client . get ( uri )
def check_covariance_Kgrad_x ( covar , relchange = 1E-5 , threshold = 1E-2 , check_diag = True ) : """check _ covariance _ Kgrad _ x ( ACovarianceFunction covar , limix : : mfloat _ t relchange = 1E - 5 , limix : : mfloat _ t threshold = 1E - 2 , bool check _ diag = True ) - > bool Parameters covar : limix : : ...
return _core . ACovarianceFunction_check_covariance_Kgrad_x ( covar , relchange , threshold , check_diag )
def _py2round ( x ) : """This function returns a rounded up value of the argument , similar to Python 2."""
if hasattr ( x , '__iter__' ) : rx = np . empty_like ( x ) m = x >= 0.0 rx [ m ] = np . floor ( x [ m ] + 0.5 ) m = np . logical_not ( m ) rx [ m ] = np . ceil ( x [ m ] - 0.5 ) return rx else : if x >= 0.0 : return np . floor ( x + 0.5 ) else : return np . ceil ( x - 0.5...
def _check_spades_log_file ( logfile ) : '''SPAdes can fail with a strange error . Stop everything if this happens'''
f = pyfastaq . utils . open_file_read ( logfile ) for line in f : if line . startswith ( '== Error == system call for:' ) and line . rstrip ( ) . endswith ( 'finished abnormally, err code: -7' ) : pyfastaq . utils . close ( f ) print ( 'Error running SPAdes. Cannot continue. This is the error from ...
def fill_subparser ( subparser ) : """Sets up a subparser to convert the ILSVRC2012 dataset files . Parameters subparser : : class : ` argparse . ArgumentParser ` Subparser handling the ` ilsvrc2012 ` command ."""
subparser . add_argument ( "--shuffle-seed" , help = "Seed to use for randomizing order of the " "training set on disk." , default = config . default_seed , type = int , required = False ) return convert_ilsvrc2012
def set_value ( self , value : str ) : """Sets the displayed digits based on the value string . : param value : a string containing an integer or float value : return : None"""
[ digit . clear ( ) for digit in self . _digits ] grouped = self . _group ( value ) # return the parts , reversed digits = self . _digits [ : : - 1 ] # reverse the digits # fill from right to left has_period = False for i , digit_value in enumerate ( grouped ) : try : if has_period : digits [ i ...
def resolve ( self , uri = None , ** parts ) : """Attempt to resolve a new URI given an updated URI , partial or complete ."""
if uri : result = self . __class__ ( urljoin ( str ( self ) , str ( uri ) ) ) else : result = self . __class__ ( self ) for part , value in parts . items ( ) : if part not in self . __all_parts__ : raise TypeError ( "Unknown URI component: " + part ) setattr ( result , part , value ) return resu...
def disable ( cls , user_id , github_id , name ) : """Disable webhooks for a repository . Disables the webhook from a repository if it exists in the DB . : param user _ id : User identifier . : param repo _ id : GitHub id of the repository . : param name : Fully qualified name of the repository ."""
repo = cls . get ( user_id , github_id = github_id , name = name ) repo . hook = None repo . user_id = None return repo
def select_default ( self ) : """Resets the combo box to the original " selected " value from the constructor ( or the first value if no selected value was specified ) ."""
if self . _default is None : if not self . _set_option_by_index ( 0 ) : utils . error_format ( self . description + "\n" + "Unable to select default option as the Combo is empty" ) else : if not self . _set_option ( self . _default ) : utils . error_format ( self . description + "\n" + "Unable t...
def _GetUncompressedStreamSize ( self ) : """Retrieves the uncompressed stream size . Returns : int : uncompressed stream size ."""
self . _file_object . seek ( 0 , os . SEEK_SET ) self . _decompressor = self . _GetDecompressor ( ) self . _uncompressed_data = b'' compressed_data_offset = 0 compressed_data_size = self . _file_object . get_size ( ) uncompressed_stream_size = 0 while compressed_data_offset < compressed_data_size : read_count = sel...
def mod_liu ( q , w ) : r"""Joint significance of statistics derived from chi2 - squared distributions . Parameters q : float Test statistics . w : array _ like Weights of the linear combination . Returns float Estimated p - value ."""
q = asarray ( q , float ) if not all ( isfinite ( atleast_1d ( q ) ) ) : raise ValueError ( "There are non-finite values in `q`." ) w = asarray ( w , float ) if not all ( isfinite ( atleast_1d ( w ) ) ) : raise ValueError ( "There are non-finite values in `w`." ) d = sum ( w ) w /= d c1 = sum ( w ) c2 = sum ( w...
def mk_definition ( defn ) : """Instantiates a struct or SBP message specification from a parsed " AST " of a struct or message . Parameters defn : dict Returns A Definition or a specialization of a definition , like a Struct"""
assert len ( defn ) == 1 identifier , contents = next ( iter ( defn . items ( ) ) ) fs = [ mk_field ( f ) for f in contents . get ( 'fields' , [ ] ) ] return sbp . resolve_type ( sbp . Definition ( identifier = identifier , sbp_id = contents . get ( 'id' , None ) , short_desc = contents . get ( 'short_desc' , None ) , ...
def validate_depth ( self , depth : DepthDefinitionType ) -> Optional [ int ] : """Converts the depth to int and validates that the value can be used . : raise ValueError : If the provided depth is not valid"""
if depth is not None : try : depth = int ( depth ) except ValueError : raise ValueError ( f"Depth '{depth}' can't be converted to int." ) if depth < 1 : raise ValueError ( f"Depth '{depth}' isn't a positive number" ) return depth return None
def get_data_by_time ( path , columns , dates , start_time = '00:00' , end_time = '23:59' ) : """Extract columns of data from a ProCoDA datalog based on date ( s ) and time ( s ) Note : Column 0 is time . The first data column is column 1. : param path : The path to the folder containing the ProCoDA data file (...
data = data_from_dates ( path , dates ) first_time_column = pd . to_numeric ( data [ 0 ] . iloc [ : , 0 ] ) start = max ( day_fraction ( start_time ) , first_time_column [ 0 ] ) start_idx = time_column_index ( start , first_time_column ) end_idx = time_column_index ( day_fraction ( end_time ) , pd . to_numeric ( data [...
def get_link ( self , peer ) : """Retrieves the link to the given peer"""
for access in peer . accesses : if access . type == 'mqtt' : break else : # No MQTT access found return None # Get server access tuple server = ( access . server . host , access . server . port ) with self . __lock : try : # Get existing link return self . _links [ server ] except KeyErr...
def QueryService ( svc_name ) : """Query service and get its config ."""
hscm = win32service . OpenSCManager ( None , None , win32service . SC_MANAGER_ALL_ACCESS ) result = None try : hs = win32serviceutil . SmartOpenService ( hscm , svc_name , win32service . SERVICE_ALL_ACCESS ) result = win32service . QueryServiceConfig ( hs ) win32service . CloseServiceHandle ( hs ) finally :...
def default_callback ( self , text ) : """Default clean the \\ n in text ."""
text = text . replace ( "\r\n" , "\n" ) text = "%s\n" % text flush_print ( text , sep = "" , end = "" ) return text
def splitpath ( path ) : """Recursively split a filepath into all directories and files ."""
head , tail = os . path . split ( path ) if tail == '' : return head , elif head == '' : return tail , else : return splitpath ( head ) + ( tail , )
def sample_indexes_by_distribution ( indexes , distributions , nsample ) : """Samples trajectory / time indexes according to the given probability distributions Parameters indexes : list of ndarray ( ( N _ i , 2 ) ) For each state , all trajectory and time indexes where this state occurs . Each matrix has a...
# how many states in total ? n = len ( indexes ) for dist in distributions : if len ( dist ) != n : raise ValueError ( 'Size error: Distributions must all be of length n (number of states).' ) # list of states res = np . ndarray ( ( len ( distributions ) ) , dtype = object ) for i in range ( len ( distribut...
def _rm_is_alignment_line ( parts , s1_name , s2_name ) : """return true if the tokenized line is a repeatmasker alignment line . : param parts : the line , already split into tokens around whitespace : param s1 _ name : the name of the first sequence , as extracted from the header of the element this line is...
if len ( parts ) < 2 : return False if _rm_name_match ( parts [ 0 ] , s1_name ) : return True if ( _rm_name_match ( parts [ 0 ] , s2_name ) or ( parts [ 0 ] == "C" and _rm_name_match ( parts [ 1 ] , s2_name ) ) ) : return True return False
def rank ( self ) : """Returns the item ' s rank ( if it has one ) as a dict that includes required score , name , and level ."""
if self . _rank != { } : # Don ' t bother doing attribute lookups again return self . _rank try : # The eater determining the rank levelkey , typename , count = self . kill_eaters [ 0 ] except IndexError : # Apparently no eater available self . _rank = None return None rankset = self . _ranks . get ( le...
def parse_angular_length_quantity ( string_rep ) : """Given a string that is a number and a unit , return a Quantity of that string . Raise an Error If there is no unit . e . g . : 50 " - > 50 * u . arcsec 50 - > CRTFRegionParserError : Units must be specified for 50"""
unit_mapping = { 'deg' : u . deg , 'rad' : u . rad , 'arcmin' : u . arcmin , 'arcsec' : u . arcsec , 'pix' : u . dimensionless_unscaled , '"' : u . arcsec , "'" : u . arcmin , } regex_str = re . compile ( r'([0-9+,-.]*)(.*)' ) str = regex_str . search ( string_rep ) unit = str . group ( 2 ) if unit : if unit in uni...
def doesnt_have ( self , relation , boolean = 'and' , extra = None ) : """Add a relationship count to the query . : param relation : The relation to count : type relation : str : param boolean : The boolean value : type boolean : str : param extra : The extra query : type extra : Builder or callable :...
return self . has ( relation , '<' , 1 , boolean , extra )
def cmd_certclone ( hostname , port , keyfile , certfile , copy_extensions , expired , verbose ) : """Connect to an SSL / TLS server , get the certificate and generate a certificate with the same options and field values . Note : The generated certificate is invalid , but can be used for social engineering atta...
context = ssl . create_default_context ( ) with socket . create_connection ( ( hostname , port ) , timeout = 3 ) as sock : with context . wrap_socket ( sock , server_hostname = hostname ) as ssock : original = ssock . getpeercert ( binary_form = True ) key , cert = certclone ( original , copy_extensions = c...
def escape_filename_sh_ansic ( name ) : """Return an ansi - c shell - escaped version of a filename ."""
out = [ ] # gather the escaped characters into a list for ch in name : if ord ( ch ) < 32 : out . append ( "\\x%02x" % ord ( ch ) ) elif ch == '\\' : out . append ( '\\\\' ) else : out . append ( ch ) # slap them back together in an ansi - c quote $ ' . . . ' return "$'" + "" . join ...
def hex_to_rgb ( color ) : """Converts from hex to rgb Parameters : color : string Color representation on hex or rgb Example : hex _ to _ rgb ( ' # E1E5ED ' ) hex _ to _ rgb ( ' # f03 ' )"""
color = normalize ( color ) color = color [ 1 : ] # return ' rgb ' + str ( tuple ( ord ( c ) for c in color . decode ( ' hex ' ) ) ) return 'rgb' + str ( ( int ( color [ 0 : 2 ] , base = 16 ) , int ( color [ 2 : 4 ] , base = 16 ) , int ( color [ 4 : 6 ] , base = 16 ) ) )
def sg_sum ( tensor , opt ) : r"""Computes the sum of elements across axis of a tensor . See ` tf . reduce _ sum ( ) ` in tensorflow . Args : tensor : A ` Tensor ` with zero - padding ( automatically given by chain ) . opt : axis : A tuple / list of integers or an integer . The axis to reduce . keep _ d...
return tf . reduce_sum ( tensor , axis = opt . axis , keep_dims = opt . keep_dims , name = opt . name )
def create_plot_option_dicts ( info , marker_types = None , colors = None , line_dash = None , size = None ) : """Create two dictionaries with plot - options . The first iterates colors ( based on group - number ) , the second iterates through marker types . Returns : group _ styles ( dict ) , sub _ group _ s...
logging . debug ( " - creating plot-options-dict (for bokeh)" ) # Current only works for bokeh if marker_types is None : marker_types = [ "circle" , "square" , "triangle" , "invertedtriangle" , "diamond" , "cross" , "asterix" ] if line_dash is None : line_dash = [ 0 , 0 ] if size is None : size = 10 grou...
def identifiers ( dataset_uri ) : """List the item identifiers in the dataset ."""
dataset = dtoolcore . DataSet . from_uri ( dataset_uri ) for i in dataset . identifiers : click . secho ( i )
def get_module ( path ) : """A modified duplicate from Django ' s built in backend retriever . slugify = get _ module ( ' django . template . defaultfilters . slugify ' )"""
try : from importlib import import_module except ImportError as e : from django . utils . importlib import import_module try : mod_name , func_name = path . rsplit ( '.' , 1 ) mod = import_module ( mod_name ) except ImportError as e : raise ImportError ( 'Error importing alert function {0}: "{1}"' ....
def show_pricing ( kwargs = None , call = None ) : '''Show pricing for a particular profile . This is only an estimate , based on unofficial pricing sources . . . versionadded : : 2015.8.0 CLI Example : . . code - block : : bash salt - cloud - f show _ pricing my - linode - config profile = my - linode - ...
if call != 'function' : raise SaltCloudException ( 'The show_instance action must be called with -f or --function.' ) profile = __opts__ [ 'profiles' ] . get ( kwargs [ 'profile' ] , { } ) if not profile : raise SaltCloudNotFound ( 'The requested profile was not found.' ) # Make sure the profile belongs to Lino...
def serial_udb_extra_f13_encode ( self , sue_week_no , sue_lat_origin , sue_lon_origin , sue_alt_origin ) : '''Backwards compatible version of SERIAL _ UDB _ EXTRA F13 : format sue _ week _ no : Serial UDB Extra GPS Week Number ( int16 _ t ) sue _ lat _ origin : Serial UDB Extra MP Origin Latitude ( int32 _ t )...
return MAVLink_serial_udb_extra_f13_message ( sue_week_no , sue_lat_origin , sue_lon_origin , sue_alt_origin )
def default_pixmap ( self , value ) : """Setter for * * self . _ _ default _ pixmap * * attribute . : param value : Attribute value . : type value : QPixmap"""
if value is not None : assert type ( value ) is QPixmap , "'{0}' attribute: '{1}' type is not 'QPixmap'!" . format ( "default_pixmap" , value ) self . __default_pixmap = value
def register_account ( self , account , portfolio_cookie = None ) : '''注册一个account到portfolio组合中 account 也可以是一个策略类 , 实现其 on _ bar 方法 : param account : 被注册的account : return :'''
# 查找 portfolio if len ( self . portfolio_list . keys ( ) ) < 1 : po = self . new_portfolio ( ) elif portfolio_cookie is not None : po = self . portfolio_list [ portfolio_cookie ] else : po = list ( self . portfolio_list . values ( ) ) [ 0 ] # 把account 添加到 portfolio中去 po . add_account ( account ) return ( po...
def get_event ( self , client , check ) : """Returns an event for a given client & check name ."""
data = self . _request ( 'GET' , '/events/{}/{}' . format ( client , check ) ) return data . json ( )
def complex_check ( * args , func = None ) : """Check if arguments are complex numbers ."""
func = func or inspect . stack ( ) [ 2 ] [ 3 ] for var in args : if not isinstance ( var , numbers . Complex ) : name = type ( var ) . __name__ raise ComplexError ( f'Function {func} expected complex number, {name} got instead.' )
def unpack_float16 ( src ) : """Read and unpack a 16b float . The structure is : - 1 bit for the sign . 5 bits for the exponent , with an exponent bias of 16 - 10 bits for the mantissa"""
bc = BitConsumer ( src ) sign = bc . u_get ( 1 ) exponent = bc . u_get ( 5 ) mantissa = bc . u_get ( 10 ) exponent -= 16 mantissa /= 2 ** 10 num = ( - 1 ** sign ) * mantissa * ( 10 ** exponent ) return num
def data_iterator_csv_dataset ( uri , batch_size , shuffle = False , rng = None , normalize = True , with_memory_cache = True , with_file_cache = True , cache_dir = None , epoch_begin_callbacks = [ ] , epoch_end_callbacks = [ ] ) : '''data _ iterator _ csv _ dataset Get data directly from a dataset provided as a ...
ds = CsvDataSource ( uri , shuffle = shuffle , rng = rng , normalize = normalize ) return data_iterator ( ds , batch_size = batch_size , with_memory_cache = with_memory_cache , with_file_cache = with_file_cache , cache_dir = cache_dir , epoch_begin_callbacks = epoch_begin_callbacks , epoch_end_callbacks = epoch_end_cal...
def execute ( self , conn , daoinput , transaction = False ) : """required keys : migration _ status , migration _ request _ id"""
if not conn : dbsExceptionHandler ( "dbsException-failed-connect2host" , "Oracle/MigrationRequests/UpdateRequestStatus. Expects db connection from upper layer." , self . logger . exception ) if daoinput [ 'migration_status' ] == 1 : sql = self . sql2 elif daoinput [ 'migration_status' ] == 2 : sql = self . ...
def render_to_string ( template_name , context = None , request = None , using = None ) : """Loads a template and renders it with a context . Returns a string . template _ name may be a string or a list of strings ."""
if isinstance ( template_name , ( list , tuple ) ) : template = select_template ( template_name , using = using ) else : template = get_template ( template_name , using = using ) return template . render ( context , request )
def update_namelist_file ( self , rapid_namelist_file , new_namelist_file = None ) : """Update existing namelist file with new parameters Parameters rapid _ namelist _ file : str Path of namelist file to use in the simulation . It will be updated with any parameters added to the RAPID manager . new _ name...
if os . path . exists ( rapid_namelist_file ) and rapid_namelist_file : log ( "Adding missing inputs from RAPID input file ..." , "INFO" ) with open ( rapid_namelist_file , 'r' ) as old_file : for line in old_file : line = line . strip ( ) if not line [ : 1 ] . isalpha ( ) or not...
def get_pmt ( self , dom_id , channel_id ) : """Return PMT with DOM ID and DAQ channel ID"""
du , floor , _ = self . doms [ dom_id ] pmt = self . pmts [ self . _pmt_index_by_omkey [ ( du , floor , channel_id ) ] ] return pmt
def copy_from ( self , other ) : """Copy other onto self ."""
self . verbose , self . quiet , self . path , self . name , self . tracing = other . verbose , other . quiet , other . path , other . name , other . tracing
def form_fields ( self ) : """Return fields of default form . Fill some fields with reasonable values ."""
fields = dict ( self . form . fields ) # pylint : disable = no - member fields_to_remove = set ( ) for key , val in list ( fields . items ( ) ) : if isinstance ( val , CheckboxValues ) : if not len ( val ) : # pylint : disable = len - as - condition del fields [ key ] elif len ( val ) ==...
def put ( self , request , bot_id , id , format = None ) : """Update existing handler serializer : HandlerUpdateSerializer responseMessages : - code : 401 message : Not authenticated - code : 400 message : Not valid request"""
return super ( HandlerDetail , self ) . put ( request , bot_id , id , format )
def disable_reporting ( self ) : """Call this method to explicitly disable reporting . The current report will be discarded , along with the previously recorded ones that haven ' t been uploaded . The configuration is updated so that future runs do not record or upload reports ."""
if self . status == Stats . DISABLED : return if not self . disableable : logger . critical ( "Can't disable reporting" ) return self . status = Stats . DISABLED self . write_config ( self . status ) if os . path . exists ( self . location ) : old_reports = [ f for f in os . listdir ( self . location ) ...
async def encrypt ( self , message : bytes , authn : bool = False , recip : str = None ) -> bytes : """Encrypt plaintext for owner of DID or verification key , anonymously or via authenticated encryption scheme . If given DID , first check wallet and then pool for corresponding verification key . Raise Wallet...
LOGGER . debug ( 'BaseAnchor.encrypt >>> message: %s, authn: %s, recip: %s' , message , authn , recip ) if not self . wallet . handle : LOGGER . debug ( 'BaseAnchor.encrypt <!< Wallet %s is closed' , self . name ) raise WalletState ( 'Wallet {} is closed' . format ( self . name ) ) rv = await self . wallet . en...
def _send_post ( self , blogname , params ) : """Formats parameters and sends the API request off . Validates common and per - post - type parameters and formats your tags for you . : param blogname : a string , the blogname of the blog you are posting to : param params : a dict , the key - value of the param...
url = "/v2/blog/{}/post" . format ( blogname ) valid_options = self . _post_valid_options ( params . get ( 'type' , None ) ) if len ( params . get ( "tags" , [ ] ) ) > 0 : # Take a list of tags and make them acceptable for upload params [ 'tags' ] = "," . join ( params [ 'tags' ] ) return self . send_api_request ( ...
def findNestedDirectories ( self , lst ) : '''Recursive helper function for finding nested directories . If this node is a directory node , it is appended to ` ` lst ` ` . Each node also calls each of its child ` ` findNestedDirectories ` ` with the same list . : Parameters : ` ` lst ` ` ( list ) The list...
if self . kind == "dir" : lst . append ( self ) for c in self . children : c . findNestedDirectories ( lst )
def get_all ( self , page = None , per_page = None , include_totals = False ) : """Retrieves all resource servers Args : page ( int , optional ) : The result ' s page number ( zero based ) . per _ page ( int , optional ) : The amount of entries per page . include _ totals ( bool , optional ) : True if the q...
params = { 'page' : page , 'per_page' : per_page , 'include_totals' : str ( include_totals ) . lower ( ) } return self . client . get ( self . _url ( ) , params = params )
def ssml_phoneme ( self , words , alphabet = None , ph = None , ** kwargs ) : """Create a < Phoneme > element : param words : Words to speak : param alphabet : Specify the phonetic alphabet : param ph : Specifiy the phonetic symbols for pronunciation : param kwargs : additional attributes : returns : < Ph...
return self . nest ( SsmlPhoneme ( words , alphabet = alphabet , ph = ph , ** kwargs ) )
def train_model ( self , dataset_id , model_name , token = None , url = API_TRAIN_MODEL ) : """Train a model given a specifi dataset previously created : param dataset _ id : string , the id of a previously created dataset : param model _ name : string , what you will call this model attention : This may take...
auth = 'Bearer ' + self . check_for_token ( token ) m = MultipartEncoder ( fields = { 'name' : model_name , 'datasetId' : dataset_id } ) h = { 'Authorization' : auth , 'Cache-Control' : 'no-cache' , 'Content-Type' : m . content_type } the_url = url r = requests . post ( the_url , headers = h , data = m ) return r
def namespace ( self ) : """Return a dictionary representing the namespace which should be available to the user ."""
self . _ns = { 'db' : self . store , 'store' : store , 'autocommit' : False , } return self . _ns
def load ( self , path = None , ignore_errors = True , block_user_signals = False ) : """Loads all the parameters from a databox text file . If path = None , loads from self . _ autosettings _ path ( provided this is not None ) . Parameters path = None Path to load the settings from . If None , will load fr...
if path == None : # Bail if there is no path if self . _autosettings_path == None : return self # Get the gui settings directory gui_settings_dir = _os . path . join ( _cwd , 'egg_settings' ) # Get the final path path = _os . path . join ( gui_settings_dir , self . _autosettings_path ) # mak...
def copy_content ( origin , dstPath , blockSize , mode ) : '''copy the content of ` origin ` to ` dstPath ` in a safe manner . this function will first copy the content to a temporary file and then move it atomically to the requested destination . if some error occurred during content copy or file movement ...
tmpFD , tmpPath = tempfile . mkstemp ( prefix = os . path . basename ( dstPath ) + "_" , suffix = '.tmp' , dir = os . path . dirname ( dstPath ) ) try : try : # change mode of the temp file oldmask = os . umask ( 0 ) try : os . chmod ( tmpPath , mode ) finally : os . ...
def terminate_manager ( self ) : """* * Purpose * * : Method to terminate the tmgr process . This method is blocking as it waits for the tmgr process to terminate ( aka join ) ."""
try : if self . _tmgr_process : if not self . _tmgr_terminate . is_set ( ) : self . _tmgr_terminate . set ( ) if self . check_manager ( ) : self . _tmgr_process . join ( ) self . _tmgr_process = None self . _logger . info ( 'Task manager process closed' ) ...
def run ( self , scale_out , sectors = 'all' ) : """Evolve the Wilson coefficients to the scale ` scale _ out ` . Parameters : - scale _ out : output scale - sectors : optional . If provided , must be a tuple of strings corresponding to WCxf sector names . Only Wilson coefficients belonging to these secto...
C_out = self . _run_dict ( scale_out , sectors = sectors ) all_wcs = set ( wcxf . Basis [ self . eft , 'JMS' ] . all_wcs ) # to speed up lookup C_out = { k : v for k , v in C_out . items ( ) if v != 0 and k in all_wcs } return wcxf . WC ( eft = self . eft , basis = 'JMS' , scale = scale_out , values = wcxf . WC . dict2...
def prefix_lines ( lines , prefix ) : """Add the prefix to each of the lines . > > > prefix _ lines ( [ ' foo ' , ' bar ' ] , ' ' ) [ ' foo ' , ' bar ' ] > > > prefix _ lines ( ' foo \\ nbar ' , ' ' ) [ ' foo ' , ' bar ' ] : param list or str lines : A string or a list of strings . If a string is passed...
if isinstance ( lines , bytes ) : lines = lines . decode ( 'utf-8' ) if isinstance ( lines , str ) : lines = lines . splitlines ( ) return [ prefix + line for line in lines ]
def maintenance ( self , on = True ) : """Toggles maintenance mode ."""
r = self . _h . _http_resource ( method = 'POST' , resource = ( 'apps' , self . name , 'server' , 'maintenance' ) , data = { 'maintenance_mode' : int ( on ) } ) return r . ok
def round_sig ( x , n , scien_notation = False ) : if x < 0 : x = x * - 1 symbol = '-' else : symbol = '' '''round floating point x to n significant figures'''
if type ( n ) is not types . IntType : raise TypeError , "n must be an integer" try : x = float ( x ) except : raise TypeError , "x must be a floating point object" form = "%0." + str ( n - 1 ) + "e" st = form % x num , expo = epat . findall ( st ) [ 0 ] expo = int ( expo ) fs = string . split ( num , '.' )...
def create_qualification_type ( Name = None , Keywords = None , Description = None , QualificationTypeStatus = None , RetryDelayInSeconds = None , Test = None , AnswerKey = None , TestDurationInSeconds = None , AutoGranted = None , AutoGrantedValue = None ) : """The CreateQualificationType operation creates a new Q...
pass
def spawn_server_api ( api_name , app , api_spec , error_callback , decorator ) : """Take a a Flask app and a swagger file in YAML format describing a REST API , and populate the app with routes handling all the paths and methods declared in the swagger file . Also handle marshaling and unmarshaling between j...
def mycallback ( endpoint ) : handler_func = get_function ( endpoint . handler_server ) # Generate api endpoint around that handler handler_wrapper = _generate_handler_wrapper ( api_name , api_spec , endpoint , handler_func , error_callback , decorator ) # Bind handler to the API path log . info ( "...
def drop_database ( self , name , force = False ) : """Drop an MapD database Parameters name : string Database name force : boolean , default False If False and there are any tables in this database , raises an IntegrityError"""
tables = [ ] if not force or self . database ( name ) : tables = self . list_tables ( database = name ) if not force and len ( tables ) : raise com . IntegrityError ( 'Database {0} must be empty before being dropped, or set ' 'force=True' . format ( name ) ) statement = ddl . DropDatabase ( name ) self . _execu...