signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def calc_fc_size ( img_height , img_width ) : '''Calculates shape of data after encoding . Parameters img _ height : int Height of input image . img _ width : int Width of input image . Returns encoded _ shape : tuple ( int ) Gives back 3 - tuple with new dims .'''
height , width = img_height , img_width for _ in range ( 5 ) : height , width = _get_conv_outsize ( ( height , width ) , 4 , 2 , 1 ) conv_out_layers = 512 return conv_out_layers , height , width
def copy_database ( self , source , destination ) : """Copy a database ' s content and structure . SMALL Database speed improvements ( DB size < 5mb ) Using optimized is about 178 % faster Using one _ query is about 200 % faster LARGE Database speed improvements ( DB size > 5mb ) Using optimized is about ...
print ( '\tCopying database {0} structure and data to database {1}' . format ( source , destination ) ) with Timer ( '\nSuccess! Copied database {0} to {1} in ' . format ( source , destination ) ) : # Create destination database if it does not exist if destination in self . databases : self . truncate_datab...
def get_limits ( self ) : """Return all known limits for this service , as a dict of their names to : py : class : ` ~ . AwsLimit ` objects . : returns : dict of limit names to : py : class : ` ~ . AwsLimit ` objects : rtype : dict"""
if self . limits != { } : return self . limits limits = { } # autoscaleconnection . get _ all _ groups ( ) limits [ 'Auto Scaling groups' ] = AwsLimit ( 'Auto Scaling groups' , self , 200 , self . warning_threshold , self . critical_threshold , limit_type = 'AWS::AutoScaling::AutoScalingGroup' , ) # autoscaleconnec...
def _print ( self , * data , ** kw ) : """_ print ( self , * data , sep = ' ' , end = ' \n ' , file = None ) Alternative ' print ' function that prints back into the SSH channel ."""
# Pop keyword - only arguments . ( We cannot use the syntax from the # signature . Otherwise , Python2 will give a syntax error message when # installing . ) sep = kw . pop ( 'sep' , ' ' ) end = kw . pop ( 'end' , '\n' ) _ = kw . pop ( 'file' , None ) assert not kw , 'Too many keyword-only arguments' data = sep . join ...
def nth_prime_fibonacci ( n : int ) -> int : """Returns the nth number which is both a Fibonacci number and a prime . The function takes an integer n as input and retrieves the nth number that is both a Fibonacci number and a prime number . Examples : > > > nth _ prime _ fibonacci ( 1) > > > nth _ prime _...
fib_sequence = [ 0 , 1 ] primes_sequence = [ ] def is_prime ( num ) : if num < 2 : return False for n in range ( 2 , int ( num ** 0.5 ) + 1 ) : if num % n == 0 : return False return True i = 2 while len ( primes_sequence ) < n : next_fib = fib_sequence [ i - 1 ] + fib_sequenc...
def simplified_solis ( apparent_elevation , aod700 = 0.1 , precipitable_water = 1. , pressure = 101325. , dni_extra = 1364. ) : """Calculate the clear sky GHI , DNI , and DHI according to the simplified Solis model [ 1 ] _ . Reference [ 1 ] _ describes the accuracy of the model as being 15 , 20, and 18 W / m ...
p = pressure w = precipitable_water # algorithm fails for pw < 0.2 w = np . maximum ( w , 0.2 ) # this algorithm is reasonably fast already , but it could be made # faster by precalculating the powers of aod700 , the log ( p / p0 ) , and # the log ( w ) instead of repeating the calculations as needed in each # function...
def fsdecode ( path , os_name = os . name , fs_encoding = FS_ENCODING , errors = None ) : '''Decode given path . : param path : path will be decoded if using bytes : type path : bytes or str : param os _ name : operative system name , defaults to os . name : type os _ name : str : param fs _ encoding : cu...
if not isinstance ( path , bytes ) : return path if not errors : use_strict = PY_LEGACY or os_name == 'nt' errors = 'strict' if use_strict else 'surrogateescape' return path . decode ( fs_encoding , errors = errors )
def clean_doi ( doi_string ) : """Use regex to extract all DOI ids from string ( i . e . 10.1029/2005pa001215) : param str doi _ string : Raw DOI string value from input file . Often not properly formatted . : return list : DOI ids . May contain 0 , 1 , or multiple ids ."""
regex = re . compile ( r'\b(10[.][0-9]{3,}(?:[.][0-9]+)*/(?:(?!["&\'<>,])\S)+)\b' ) try : # Returns a list of matching strings m = re . findall ( regex , doi_string ) except TypeError as e : # If doi _ string is None type , return empty list print ( "TypeError cleaning DOI: {}, {}" . format ( doi_string , e ) )...
def _check_contact ( self ) : """Returns True if gripper is in contact with an object ."""
collision = False for contact in self . sim . data . contact [ : self . sim . data . ncon ] : if ( self . sim . model . geom_id2name ( contact . geom1 ) in self . finger_names or self . sim . model . geom_id2name ( contact . geom2 ) in self . finger_names ) : collision = True break return collision
def configure_logger ( level , format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' ) : # type : ( int , str ) - > None """Set logger configuration . Args : level ( int ) : Logger level format ( str ) : Logger format"""
logging . basicConfig ( format = format , level = level ) if level >= logging . INFO : logging . getLogger ( 'boto3' ) . setLevel ( logging . INFO ) logging . getLogger ( 's3transfer' ) . setLevel ( logging . INFO ) logging . getLogger ( 'botocore' ) . setLevel ( logging . WARN )
def score ( self , X , eval_metric = 'acc' , num_batch = None , batch_end_callback = None , reset = True ) : """Run the model given an input and calculate the score as assessed by an evaluation metric . Parameters X : mxnet . DataIter eval _ metric : metric . metric The metric for calculating score . nu...
# setup metric if not isinstance ( eval_metric , metric . EvalMetric ) : eval_metric = metric . create ( eval_metric ) X = self . _init_iter ( X , None , is_train = False ) if reset : X . reset ( ) data_shapes = X . provide_data data_names = [ x [ 0 ] for x in data_shapes ] type_dict = dict ( ( key , value . dt...
def tange_pth ( v , temp , v0 , gamma0 , a , b , theta0 , n , z , t_ref = 300. , three_r = 3. * constants . R ) : """calculate thermal pressure for the Tange equation : param v : unit - cell volume in A ^ 3 : param temp : temperature in K : param v0 : unit - cell volume in A ^ 3 at 1 bar : param gamma0 : Gr...
v_mol = vol_uc2mol ( v , z ) gamma = tange_grun ( v , v0 , gamma0 , a , b ) theta = tange_debyetemp ( v , v0 , gamma0 , a , b , theta0 ) xx = theta / temp debye = debye_E ( xx ) if t_ref == 0. : debye0 = 0. else : xx0 = theta / t_ref debye0 = debye_E ( xx0 ) Eth0 = three_r * n * t_ref * debye0 Eth = three_r...
def verify_strain_options_multi_ifo ( opts , parser , ifos ) : """Sanity check provided strain arguments . Parses the strain data CLI options and verifies that they are consistent and reasonable . Parameters opt : object Result of parsing the CLI with OptionParser , or any object with the required attri...
for ifo in ifos : for opt_group in ensure_one_opt_groups : ensure_one_opt_multi_ifo ( opts , parser , ifo , opt_group ) required_opts_multi_ifo ( opts , parser , ifo , required_opts_list )
def true_range ( arg , high_col = 'high' , low_col = 'low' , close_col = 'close' , skipna = 0 ) : """http : / / en . wikipedia . org / wiki / Average _ true _ range The greatest of the following : - Current High less the current Low - Current High less the previous Close ( absolute value ) - Curre nt Low le...
_ensure_col ( arg , high_col = high_col , low_col = low_col , close_col = close_col ) yclose = arg [ close_col ] . shift ( 1 ) low , high = arg [ low_col ] , arg [ high_col ] mx = pd . DataFrame ( { 'a' : high , 'b' : yclose } ) . max ( axis = 1 , skipna = skipna ) mn = pd . DataFrame ( { 'a' : low , 'b' : yclose } ) ....
def search ( self , search_text = None , response_type = None , params = None ) : """Function to request economic data series that match search text . ` < https : / / research . stlouisfed . org / docs / api / fred / series _ search . html > ` _ : arg str search _ text : The words to match against economic data...
path = '/series/search?' params [ 'search_text' ] = search_text response_type = response_type if response_type else self . response_type if response_type != 'xml' : params [ 'file_type' ] = 'json' response = _get_request ( self . url_root , self . api_key , path , response_type , params , self . ssl_verify ) return...
def locate_point ( nodes , x_val , y_val ) : r"""Find the parameter corresponding to a point on a curve . . . note : : This assumes that the curve : math : ` B ( s , t ) ` defined by ` ` nodes ` ` lives in : math : ` \ mathbf { R } ^ 2 ` . Args : nodes ( numpy . ndarray ) : The nodes defining a B | eacute...
# First , reduce to the true degree of x ( s ) and y ( s ) . zero1 = _curve_helpers . full_reduce ( nodes [ [ 0 ] , : ] ) - x_val zero2 = _curve_helpers . full_reduce ( nodes [ [ 1 ] , : ] ) - y_val # Make sure we have the lowest degree in front , to make the polynomial # solve have the fewest number of roots . if zero...
def update_policy ( self , defaultHeaders ) : """rewrite update policy so that additional pins are added and not overwritten"""
if self . inputs is not None : for k , v in defaultHeaders . items ( ) : if k not in self . inputs : self . inputs [ k ] = v if k == 'pins' : self . inputs [ k ] = self . inputs [ k ] + defaultHeaders [ k ] return self . inputs else : return self . inputs
def input ( self ) : """Returns a file - like object representing the request body ."""
if self . _input is None : input_file = self . environ [ 'wsgi.input' ] content_length = self . content_length or 0 self . _input = WsgiInput ( input_file , self . content_length ) return self . _input
def local_attr ( self , name , context = None ) : """Get the list of assign nodes associated to the given name . Assignments are looked for in both this class and in parents . : returns : The list of assignments to the given name . : rtype : list ( NodeNG ) : raises AttributeInferenceError : If no attribute...
result = [ ] if name in self . locals : result = self . locals [ name ] else : class_node = next ( self . local_attr_ancestors ( name , context ) , None ) if class_node : result = class_node . locals [ name ] result = [ n for n in result if not isinstance ( n , node_classes . DelAttr ) ] if result :...
def query_ssos ( self , target_name , lunation_count = None ) : """Send a query to the SSOS web service , looking for available observations using the given track . : param target _ name : name of target to query against SSOIS db : param lunation _ count : ignored : rtype : SSOSData"""
# we observe ~ a week either side of new moon # but we don ' t know when in the dark run the discovery happened # so be generous with the search boundaries , add extra 2 weeks # current date just has to be the night of the triplet , from mp_ephem import horizons search_start_date = Time ( '1999-01-01' , scale = 'utc' )...
def shared_limit ( self , limit_value , scope , key_func = None , error_message = None , exempt_when = None ) : """decorator to be applied to multiple routes sharing the same rate limit . : param limit _ value : rate limit string or a callable that returns a string . : ref : ` ratelimit - string ` for more deta...
return self . __limit_decorator ( limit_value , key_func , True , scope , error_message = error_message , exempt_when = exempt_when )
def find_le ( self , k ) : 'Return last item with a key < = k . Raise ValueError if not found .'
i = bisect_right ( self . _keys , k ) if i : return self . _items [ i - 1 ] raise ValueError ( 'No item found with key at or below: %r' % ( k , ) )
def pyxb_is_v1 ( pyxb_obj ) : """Args : pyxb _ obj : PyXB object PyXB object holding an unknown type . Returns : bool : * * True * * if ` ` pyxb _ obj ` ` holds an API v1 type ."""
# TODO : Will not detect v1.2 as v1. return ( pyxb_obj . _element ( ) . name ( ) . namespace ( ) == d1_common . types . dataoneTypes_v1 . Namespace )
def get_default_context ( allow_fallback_standalone_context = True ) -> moderngl . Context : '''Default context'''
if ContextManager . ctx is None : try : ContextManager . ctx = moderngl . create_context ( ) except moderngl . Error : if allow_fallback_standalone_context : ContextManager . ctx = moderngl . create_standalone_context ( ) else : raise return ContextManager . ctx
def _tofile ( self , fh , pam = False ) : """Write Netbm file ."""
fh . seek ( 0 ) fh . write ( self . _header ( pam ) ) data = self . asarray ( copy = False ) if self . maxval == 1 : data = numpy . packbits ( data , axis = - 1 ) data . tofile ( fh )
def bbox ( hashcode ) : """decode a hashcode and get north , south , east and west border ."""
lat , lon , lat_length , lon_length = _decode_c2i ( hashcode ) if hasattr ( float , "fromhex" ) : latitude_delta = 180.0 / ( 1 << lat_length ) longitude_delta = 360.0 / ( 1 << lon_length ) latitude = _int_to_float_hex ( lat , lat_length ) * 90.0 longitude = _int_to_float_hex ( lon , lon_length ) * 180.0...
def callable_name ( callable_obj ) : """Attempt to return a meaningful name identifying a callable or generator"""
try : if ( isinstance ( callable_obj , type ) and issubclass ( callable_obj , param . ParameterizedFunction ) ) : return callable_obj . __name__ elif ( isinstance ( callable_obj , param . Parameterized ) and 'operation' in callable_obj . params ( ) ) : return callable_obj . operation . __name__ ...
def filter_boxes_inside_shape ( boxes , shape ) : """Args : boxes : ( nx4 ) , float shape : ( h , w ) Returns : indices : ( k , ) selection : ( kx4)"""
assert boxes . ndim == 2 , boxes . shape assert len ( shape ) == 2 , shape h , w = shape indices = np . where ( ( boxes [ : , 0 ] >= 0 ) & ( boxes [ : , 1 ] >= 0 ) & ( boxes [ : , 2 ] <= w ) & ( boxes [ : , 3 ] <= h ) ) [ 0 ] return indices , boxes [ indices , : ]
def parse_assignment ( self , stream ) : """AssignmentStmt : : = Name WSC AssignmentSymbol WSC Value StatementDelim"""
lineno = stream . lineno name = self . next_token ( stream ) self . ensure_assignment ( stream ) at_an_end = any ( ( self . has_end_group ( stream ) , self . has_end_object ( stream ) , self . has_end ( stream ) , self . has_next ( self . statement_delimiter , stream , 0 ) ) ) if at_an_end : value = self . broken_a...
def forward ( Q , p , G , h , A , b , Q_LU , S_LU , R , eps = 1e-12 , verbose = 0 , notImprovedLim = 3 , maxIter = 20 , solver = KKTSolvers . LU_PARTIAL ) : """Q _ LU , S _ LU , R = pre _ factor _ kkt ( Q , G , A )"""
nineq , nz , neq , nBatch = get_sizes ( G , A ) # Find initial values if solver == KKTSolvers . LU_FULL : D = torch . eye ( nineq ) . repeat ( nBatch , 1 , 1 ) . type_as ( Q ) x , s , z , y = factor_solve_kkt ( Q , D , G , A , p , torch . zeros ( nBatch , nineq ) . type_as ( Q ) , - h , - b if b is not None els...
def find_one ( self , filter = None , * args , ** kwargs ) : """Get a single document from the database . All arguments to : meth : ` find ` are also valid arguments for : meth : ` find _ one ` , although any ` limit ` argument will be ignored . Returns a single document , or ` ` None ` ` if no matching doc...
if ( filter is not None and not isinstance ( filter , collections . Mapping ) ) : filter = { "_id" : filter } cursor = self . find ( filter , * args , ** kwargs ) for result in cursor . limit ( - 1 ) : return result return None
def close ( self ) : """Close the database connection and render self invalid . Any subsequent re - use of self will raise an error ."""
self . _cursor . close ( ) self . _db . close ( ) self . _cursor = self . _db = self . _cache = None
def spi ( self , ** spi_args ) : """Returns an SPI interface , for the specified SPI * port * and * device * , or for the specified pins ( * clock _ pin * , * mosi _ pin * , * miso _ pin * , and * select _ pin * ) . Only one of the schemes can be used ; attempting to mix * port * and * device * with pin numbe...
spi_args , kwargs = self . _extract_spi_args ( ** spi_args ) shared = 'shared' if kwargs . pop ( 'shared' , False ) else 'exclusive' if kwargs : raise SPIBadArgs ( 'unrecognized keyword argument %s' % kwargs . popitem ( ) [ 0 ] ) for port , pins in SPI_HARDWARE_PINS . items ( ) : if all ( ( spi_args [ 'clock_pi...
def substitute_infinitives_as_subjects ( sent_str ) : """If an infinitive is used as a subject , substitute the gerund ."""
sent_doc = textacy . Doc ( sent_str , lang = 'en_core_web_lg' ) # inf _ pattern = r ' < PART > < VERB > + ' # To aux / auxpass * csubj inf_pattern = r'<PART><VERB>' # To aux / auxpass * csubj infinitives = textacy . extract . pos_regex_matches ( sent_doc , inf_pattern ) inf_subjs = [ ] # = > [ [ 0,1 ] , . . . ] for inf...
def perform_release ( context ) : """Executes the release process ."""
try : run_tests ( ) if not context . skip_changelog : generate_changelog ( context ) increment_version ( context ) build_distributions ( context ) install_package ( context ) upload_package ( context ) install_from_pypi ( context ) publish ( context ) except Exception : log ....
def create_mysql_cymysql ( self , ** kwargs ) : """: rtype : Engine"""
return self . _ce ( self . _ccs ( self . DialectAndDriver . mysql_cymysql ) , ** kwargs )
def _get_parts_of_format_string ( resolved_string , literal_texts , format_specs ) : """Inner function of reverse _ format , returns the resolved value for each field in pattern ."""
_text = resolved_string bits = [ ] if literal_texts [ - 1 ] != '' and _text . endswith ( literal_texts [ - 1 ] ) : _text = _text [ : - len ( literal_texts [ - 1 ] ) ] literal_texts = literal_texts [ : - 1 ] format_specs = format_specs [ : - 1 ] for i , literal_text in enumerate ( literal_texts ) : if li...
def save_model ( self , request , obj , form , change ) : """Provides a warning if the user is an active admin with no admin access ."""
super ( SitePermissionUserAdmin , self ) . save_model ( request , obj , form , change ) user = self . model . objects . get ( id = obj . id ) has_perms = len ( user . get_all_permissions ( ) ) > 0 has_sites = SitePermission . objects . filter ( user = user ) . count ( ) > 0 if user . is_active and user . is_staff and n...
def dfs_get_all_childs ( self , root ) : """Recursively get all sons of this node : param root : node to get sons : type root : : return : sons : rtype : list"""
self . nodes [ root ] [ 'dfs_loop_status' ] = 'DFS_CHECKED' ret = set ( ) # Me ret . add ( root ) # And my sons ret . update ( self . nodes [ root ] [ 'sons' ] ) for child in self . nodes [ root ] [ 'sons' ] : # I just don ' t care about already checked children if self . nodes [ child ] [ 'dfs_loop_status' ] == 'D...
def dispatch ( self , event , ev_msg ) : """Dispatch an event . event : name of the event ( str ) ev _ msg : non - optional arguments dictionary . Side effects : If an EventObject is not already registered with the EventManager , a new EventObject will be created and registered ."""
logger . debug ( 'dispatching: ' + event + ': ' + repr ( ev_msg ) ) eo = self . events . get ( event , None ) if eo : eo . dispatch ( ev_msg )
def _response ( self , in_response_to , consumer_url = None , status = None , issuer = None , sign = False , to_sign = None , sp_entity_id = None , encrypt_assertion = False , encrypt_assertion_self_contained = False , encrypted_advice_attributes = False , encrypt_cert_advice = None , encrypt_cert_assertion = None , si...
if not status : status = success_status_factory ( ) _issuer = self . _issuer ( issuer ) response = response_factory ( issuer = _issuer , in_response_to = in_response_to , status = status , sign_alg = sign_alg , digest_alg = digest_alg ) if consumer_url : response . destination = consumer_url self . _add_info ( ...
def render_template ( self , source , ** kwargs_context ) : r"""Render a template string using sandboxed environment . : param source : A string containing the page source . : param \ * \ * kwargs _ context : The context associated with the page . : returns : The rendered template ."""
return self . jinja_env . from_string ( source ) . render ( kwargs_context )
def copy_file_to_remote ( self , local_path , remote_path ) : """scp the local file to remote folder . : param local _ path : local path : param remote _ path : remote path"""
sftp_client = self . transport . open_sftp_client ( ) LOG . debug ( 'Copy the local file to remote. ' 'Source=%(src)s. Target=%(target)s.' % { 'src' : local_path , 'target' : remote_path } ) try : sftp_client . put ( local_path , remote_path ) except Exception as ex : LOG . error ( 'Failed to copy the local fil...
def search ( self , start_ts , end_ts ) : """Query Elasticsearch for documents in a time range . This method is used to find documents that may be in conflict during a rollback event in MongoDB ."""
return self . _stream_search ( index = self . meta_index_name , body = { "query" : { "range" : { "_ts" : { "gte" : start_ts , "lte" : end_ts } } } } , )
def QueryHowDoI ( Query , num_answers , full_text ) : '''Kicks off a subprocess to send the ' Query ' to HowDoI Prints the result , which in this program will route to a gooeyGUI window : param Query : text english question to ask the HowDoI web engine : return : nothing'''
howdoi_command = HOW_DO_I_COMMAND full_text_option = ' -a' if full_text else '' t = subprocess . Popen ( howdoi_command + ' \"' + Query + '\" -n ' + str ( num_answers ) + full_text_option , stdout = subprocess . PIPE ) ( output , err ) = t . communicate ( ) print ( '{:^88}' . format ( Query . rstrip ( ) ) ) print ( '_'...
def copy ( self , keys = None ) : """Return a copy of the segmentlistdict object . The return value is a new object with a new offsets attribute , with references to the original keys , and shallow copies of the segment lists . Modifications made to the offset dictionary or segmentlists in the object return...
if keys is None : keys = self new = self . __class__ ( ) for key in keys : new [ key ] = _shallowcopy ( self [ key ] ) dict . __setitem__ ( new . offsets , key , self . offsets [ key ] ) return new
def search ( self , q , ** kwargs ) : """You can pass in any of the Summon Search API parameters ( without the " s . " prefix ) . For example to remove highlighting : result = api . search ( " Web " , hl = False ) See the Summon API documentation for the full list of possible parameters : http : / / api ....
params = { "s.q" : q } for k , v in kwargs . items ( ) : params [ "s." + k ] = v r = self . _get ( "/2.0.0/search" , params ) return r
def get_parsed_cells ( iw_data , rules = None ) : """Parses iwlist output into a list of networks . @ param list iw _ data Output from iwlist scan . A list of strings . @ return list properties : Name , Address , Quality , Channel , Frequency , Encryption , Signal Level , Noise Level , Bit Rates , Mode ."...
# Here ' s a dictionary of rules that will be applied to the description # of each cell . The key will be the name of the column in the table . # The value is a function defined above . rules = rules or { "Name" : get_name , "Quality" : get_quality , "Channel" : get_channel , "Frequency" : get_frequency , "Encryption" ...
def add_legends ( self , xhists = True , yhists = False , scatter = True , ** kwargs ) : """Add legends to axes ."""
axs = [ ] if xhists : axs . extend ( self . hxs ) if yhists : axs . extend ( self . hys ) if scatter : axs . extend ( self . ax ) for ax in axs : ax . legend ( ** kwargs )
def graph_nodes_from_subtree ( self , node_source , include_root_node = False ) : """Finds all nodes of a tree that is connected to ` node _ source ` and are ( except ` node _ source ` ) not part of the ring of ` node _ source ` ( traversal of graph from ` node _ source ` excluding nodes along ring ) . Example ...
if node_source in self . _graph . nodes ( ) : # get all nodes that are member of a ring node_ring = [ ] for ring in self . rings_nodes ( include_root_node = include_root_node ) : if node_source in ring : node_ring = ring break # result set nodes_subtree = set ( ) # ge...
def upgrade ( config , revision , ** kwargs ) : """Upgrade database ."""
with alembic_lock ( config . registry [ "sqlalchemy.engine" ] , config . alembic_config ( ) ) as alembic_config : alembic . command . upgrade ( alembic_config , revision , ** kwargs )
def python_executable ( check = True , short = False ) : r"""Args : short ( bool ) : ( default = False ) Returns : str : Example : > > > # ENABLE _ DOCTEST > > > from utool . util _ cplat import * # NOQA > > > short = False > > > result = python _ executable ( short ) > > > print ( result )"""
if not check : python_exe = 'python' else : from os . path import isdir python_exe_long = unixpath ( sys . executable ) python_exe = python_exe_long if short : python_exe_short = basename ( python_exe_long ) found = search_env_paths ( python_exe_short , key_list = [ 'PATH' ] , verbos...
def init_population ( self , population_size , graph_max_layer , graph_min_layer ) : """initialize populations for evolution tuner"""
population = [ ] graph = Graph ( max_layer_num = graph_max_layer , min_layer_num = graph_min_layer , inputs = [ Layer ( LayerType . input . value , output = [ 4 , 5 ] , size = 'x' ) , Layer ( LayerType . input . value , output = [ 4 , 5 ] , size = 'y' ) ] , output = [ Layer ( LayerType . output . value , inputs = [ 4 ]...
def percentile ( a , q ) : """Compute the qth percentile of the data along the specified axis . Simpler version than the numpy version that always flattens input arrays . Examples > > > a = [ [ 10 , 7 , 4 ] , [ 3 , 2 , 1 ] ] > > > percentile ( a , 20) 2.0 > > > percentile ( a , 50) 3.5 > > > percent...
if not a : return None if isinstance ( q , ( float , int ) ) : qq = [ q ] elif isinstance ( q , ( tuple , list ) ) : qq = q else : raise ValueError ( "Quantile type {} not understood" . format ( type ( q ) ) ) if isinstance ( a , ( float , int ) ) : a = [ a ] for i in range ( len ( qq ) ) : if q...
def run ( generate_pks , show_pks , host , port , uri ) : """Connect sandman to < URI > and start the API server / admin interface ."""
app . config [ 'SQLALCHEMY_DATABASE_URI' ] = uri app . config [ 'SANDMAN_GENERATE_PKS' ] = generate_pks app . config [ 'SANDMAN_SHOW_PKS' ] = show_pks app . config [ 'SERVER_HOST' ] = host app . config [ 'SERVER_PORT' ] = port activate ( name = 'sandmanctl' ) app . run ( host = host , port = int ( port ) , debug = True...
def rewrite_elife_funding_awards ( json_content , doi ) : """rewrite elife funding awards"""
# remove a funding award if doi == "10.7554/eLife.00801" : for i , award in enumerate ( json_content ) : if "id" in award and award [ "id" ] == "par-2" : del json_content [ i ] # add funding award recipient if doi == "10.7554/eLife.04250" : recipients_for_04250 = [ { "type" : "person" , "nam...
def run ( self , ** kwargs ) : """call the power flow solution routine Returns bool True for success , False for fail"""
ret = None # initialization Y matrix and inital guess self . pre ( ) t , _ = elapsed ( ) # call solution methods if self . config . method == 'NR' : ret = self . newton ( ) elif self . config . method == 'DCPF' : ret = self . dcpf ( ) elif self . config . method in ( 'FDPF' , 'FDBX' , 'FDXB' ) : ret = self ...
def system_monitor_temp_threshold_marginal_threshold ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) system_monitor = ET . SubElement ( config , "system-monitor" , xmlns = "urn:brocade.com:mgmt:brocade-system-monitor" ) temp = ET . SubElement ( system_monitor , "temp" ) threshold = ET . SubElement ( temp , "threshold" ) marginal_threshold = ET . SubElement ( threshold , "marginal-thr...
def _set_box ( self ) : """Set the box size for the molecular assembly"""
net_volume = 0.0 for idx , mol in enumerate ( self . mols ) : length = max ( [ np . max ( mol . cart_coords [ : , i ] ) - np . min ( mol . cart_coords [ : , i ] ) for i in range ( 3 ) ] ) + 2.0 net_volume += ( length ** 3.0 ) * float ( self . param_list [ idx ] [ 'number' ] ) length = net_volume ** ( 1.0 / 3.0 ...
def help_center_user_segment_show ( self , id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / help _ center / user _ segments # show - user - segment"
api_path = "/api/v2/help_center/user_segments/{id}.json" api_path = api_path . format ( id = id ) return self . call ( api_path , ** kwargs )
def local_time ( unix_time , utc_offset , microseconds ) : """Returns a UNIX time as a broken down time for a particular transition type . : type unix _ time : int : type utc _ offset : int : type microseconds : int : rtype : tuple"""
year = EPOCH_YEAR seconds = int ( math . floor ( unix_time ) ) # Shift to a base year that is 400 - year aligned . if seconds >= 0 : seconds -= 10957 * SECS_PER_DAY year += 30 # = = 2000 else : seconds += ( 146097 - 10957 ) * SECS_PER_DAY year -= 370 # = = 1600 seconds += utc_offset # Handle years i...
def compute_qkv ( query_antecedent , memory_antecedent , total_key_depth , total_value_depth , q_filter_width = 1 , kv_filter_width = 1 , q_padding = "VALID" , kv_padding = "VALID" , vars_3d_num_heads = 0 , layer_collection = None ) : """Computes query , key and value . Args : query _ antecedent : a Tensor with...
if memory_antecedent is None : memory_antecedent = query_antecedent q = compute_attention_component ( query_antecedent , total_key_depth , q_filter_width , q_padding , "q" , vars_3d_num_heads = vars_3d_num_heads , layer_collection = layer_collection ) k = compute_attention_component ( memory_antecedent , total_key_...
def debounce ( interval_s , keyed_by = None ) : """Debounce calls to this function until interval _ s seconds have passed ."""
def wrapper ( func ) : timers = { } lock = threading . Lock ( ) @ functools . wraps ( func ) def debounced ( * args , ** kwargs ) : call_args = inspect . getcallargs ( func , * args , ** kwargs ) key = call_args [ keyed_by ] if keyed_by else None def run ( ) : with lo...
def AdjustDescriptor ( self , fields ) : """Payload - aware metadata processor ."""
for f in fields : if f . name == "args_rdf_name" : f . name = "payload_type" if f . name == "args" : f . name = "payload" return fields
def _attribs ( self , name = None , description = None ) : """Form an attributes dictionary from keyword args ."""
a = { } if name : a [ 'name' ] = name if description : a [ 'description' ] = description return a
async def print_what_is_playing ( loop ) : """Find a device and print what is playing ."""
print ( 'Discovering devices on network...' ) atvs = await pyatv . scan_for_apple_tvs ( loop , timeout = 5 ) if not atvs : print ( 'no device found' , file = sys . stderr ) return print ( 'Connecting to {0}' . format ( atvs [ 0 ] . address ) ) atv = pyatv . connect_to_apple_tv ( atvs [ 0 ] , loop ) try : pl...
def get_resources ( self , ids , cache = True ) : """Retrieve dax resources for serverless policies or related resources"""
client = local_session ( self . manager . session_factory ) . client ( 'dax' ) return client . describe_clusters ( ClusterNames = ids ) . get ( 'Clusters' )
def _get_weight_size ( self , data , n_local_subj ) : """Calculate the size of weight for this process Parameters data : a list of 2D array , each in shape [ n _ voxel , n _ tr ] The fMRI data from multi - subject . n _ local _ subj : int Number of subjects allocated to this process . Returns weight _...
weight_size = np . zeros ( 1 ) . astype ( int ) local_weight_offset = np . zeros ( n_local_subj ) . astype ( int ) for idx , subj_data in enumerate ( data ) : if idx > 0 : local_weight_offset [ idx ] = weight_size [ 0 ] weight_size [ 0 ] += self . K * subj_data . shape [ 1 ] return weight_size , local_w...
def open ( self , name , mode = 'rb' ) : """Retrieves the specified file from storage . : param name : file name : type name : str : param mode : mode to open the file with : type mode : str : rtype : : class : ` ~ django : django . core . files . File `"""
return self . get_storage ( name ) . open ( name , mode )
def search ( self , ** args ) : """Checks email inbox every 15 seconds that match the criteria up until timeout . Search criteria should be keyword args eg TO = " selenium @ gmail . com " . See _ _ imap _ search docstring for list of valid criteria . If content _ type is not defined , will return a list o...
if "content_type" not in args . keys ( ) : content_type = None elif "HTML" in args [ "content_type" ] : content_type = self . HTML del args [ "content_type" ] elif "PLAIN" in args [ "content_type" ] : content_type = self . PLAIN del args [ "content_type" ] elif args [ "content_type" ] : content_...
def trainable_params ( m : nn . Module ) -> ParamList : "Return list of trainable params in ` m ` ."
res = filter ( lambda p : p . requires_grad , m . parameters ( ) ) return res
def normalize ( self , inplace : bool = False , percent : bool = False ) -> "HistogramBase" : """Normalize the histogram , so that the total weight is equal to 1. Parameters inplace : If True , updates itself . If False ( default ) , returns copy percent : If True , normalizes to percent instead of 1 . Defaul...
if inplace : self /= self . total * ( .01 if percent else 1 ) return self else : return self / self . total * ( 100 if percent else 1 )
def get_items_batch ( self , item_request_data , project = None ) : """GetItemsBatch . Post for retrieving a set of items given a list of paths or a long path . Allows for specifying the recursionLevel and version descriptors for each path . : param : class : ` < TfvcItemRequestData > < azure . devops . v5_0 . ...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) content = self . _serialize . body ( item_request_data , 'TfvcItemRequestData' ) response = self . _send ( http_method = 'POST' , location_id = 'fe6f827b-5f64-480f-b8af-1eca3b80e833' , ve...
def is_executable ( exe_name ) : """Check if Input is Executable This methid checks if the input executable exists . Parameters exe _ name : str Executable name Returns Bool result of test Raises TypeError For invalid input type"""
if not isinstance ( exe_name , str ) : raise TypeError ( 'Executable name must be a string.' ) def is_exe ( fpath ) : return os . path . isfile ( fpath ) and os . access ( fpath , os . X_OK ) fpath , fname = os . path . split ( exe_name ) if not fpath : res = any ( [ is_exe ( os . path . join ( path , exe_n...
def _unpack_edition ( cls , value ) : """Unpack its elements and set the attributes in wfn accordingly . Parse out the five elements : ~ edition ~ software edition ~ target sw ~ target hw ~ other : param string value : Value of edition attribute : returns : Dictionary with parts of edition attribute : exc...
components = value . split ( CPEComponent2_3_URI . SEPARATOR_PACKED_EDITION ) d = dict ( ) ed = components [ 1 ] sw_ed = components [ 2 ] t_sw = components [ 3 ] t_hw = components [ 4 ] oth = components [ 5 ] ck = CPEComponent . ATT_EDITION d [ ck ] = CPE2_3_URI . _create_component ( ck , ed ) ck = CPEComponent . ATT_S...
def put_scancode ( self , scancode ) : """Sends a scancode to the keyboard . in scancode of type int raises : class : ` VBoxErrorIprtError ` Could not send scan code to virtual keyboard ."""
if not isinstance ( scancode , baseinteger ) : raise TypeError ( "scancode can only be an instance of type baseinteger" ) self . _call ( "putScancode" , in_p = [ scancode ] )
def delete ( self , token_id , * args , ** kwargs ) : """Revokes a personal access token ."""
return self . client . _put ( "{0}/revoked" . format ( self . _url ( token_id ) ) , None , * args , ** kwargs )
def write ( self , fptr ) : """Write an XML box to file ."""
read_buffer = ET . tostring ( self . xml . getroot ( ) , encoding = 'utf-8' ) fptr . write ( struct . pack ( '>I4s' , len ( read_buffer ) + 8 , b'xml ' ) ) fptr . write ( read_buffer )
def extractInfo ( self , otherInfoObject ) : """> > > from fontMath . test . test _ mathInfo import _ TestInfoObject , _ testData > > > from fontMath . mathFunctions import _ roundNumber > > > info1 = MathInfo ( _ TestInfoObject ( ) ) > > > info2 = info1 * 2.5 > > > info3 = _ TestInfoObject ( ) > > > info...
for attr , ( formatter , factorIndex ) in _infoAttrs . items ( ) : if hasattr ( self , attr ) : v = getattr ( self , attr ) if v is not None : if formatter is not None : v = formatter ( v ) setattr ( otherInfoObject , attr , v ) if hasattr ( self , "postscriptWeig...
def formatfundbjson ( fundbjson ) : """格式化集思录返回的json数据 , 以字典形式保存"""
result = { } for row in fundbjson [ "rows" ] : cell = row [ "cell" ] fundb_id = cell [ "fundb_id" ] result [ fundb_id ] = cell return result
def pprint ( data , names = '' , title = '' , formats = { } ) : """Prints tables with a bit of formatting Parameters data : ( sequence , dict , table ) The data to print in the table names : sequence The column names title : str ( optional ) The title of the table formats : dict A dictionary of co...
# Make the data into a table if it isn ' t already if type ( data ) != at . Table : data = at . Table ( data , names = names ) # Make a copy pdata = data . copy ( ) # Put the title in the metadata try : title = title or pdata . meta [ 'name' ] except : pass # Shorten the column names for slimmer data for ol...
def _check_feature ( self , feature , info , mode ) : """Private helper method performing the order check . : param feature : the feature to check . : param info : the info dict containing the before and after constraints : param mode : after | before string : return : None"""
op = dict ( before = operator . gt , after = operator . lt ) [ mode ] feature_pos = self . get_feature_position ( feature ) if feature_pos is not None : # only proceed if the the feature exists in the current feature list for other in info . get ( mode , [ ] ) : other_pos = self . get_feature_position ( oth...
def delete_from_index ( self , key ) : "Delete references from the index of the key old value ( s ) ."
old_value = self . data [ key ] keys = set ( old_value . keys ( ) ) . intersection ( self . indexes . keys ( ) ) for index_name in keys : if old_value [ index_name ] in self . indexes [ index_name ] : del self . indexes [ index_name ] [ old_value [ index_name ] ]
def main ( unused_argv ) : """Freeze a model to a GraphDef proto ."""
if FLAGS . use_tpu : dual_net . freeze_graph_tpu ( FLAGS . model_path ) else : dual_net . freeze_graph ( FLAGS . model_path )
def __dump_stack ( self ) : """Dump the shell stack in a human friendly way . An example output is : 0 PlayBoy 1 └ ─ ─ foo - prompt : foo @ [ ] 2 └ ─ ─ karPROMPT : kar @ [ ] 3 └ ─ ─ DEBUG : debug @ [ ' shell ' ]"""
maxdepth = len ( self . _mode_stack ) maxdepth_strlen = len ( str ( maxdepth ) ) index_width = 4 - ( - maxdepth_strlen ) % 4 + 4 index_str = lambda i : '{:<{}d}' . format ( i , index_width ) self . stdout . write ( index_str ( 0 ) + self . root_prompt ) self . stdout . write ( '\n' ) tree_prefix = '└── ' for i in range...
def channel_view ( x : Tensor ) -> Tensor : "Make channel the first axis of ` x ` and flatten remaining axes"
return x . transpose ( 0 , 1 ) . contiguous ( ) . view ( x . shape [ 1 ] , - 1 )
def gettext ( self , msgid , stream = sys . stdout , splitter = "--text follows this line--\n" ) : """Get the first text part we can find and print it as a message . This is a simple cowpath , most of the time you want the first plain part . ' msgid ' is the message to be used ' stream ' is printed to with th...
for hdr , part in self . _get ( msgid ) : if part . get_content_type ( ) == "text/plain" : for name , val in hdr : # Use the subtype , since we ' re printing just that - tidy it up first if name . lower ( ) == "content-type" : val = part [ "content-type" ] val = " " ....
def mget ( self , * keys ) : """- > # list of values at the specified @ keys"""
keys = list ( map ( self . get_key , keys ) ) return list ( map ( self . _loads , self . _client . mget ( * keys ) ) )
def get_membership_cache ( self , group_ids = None , is_active = True ) : """Build a dict cache with the group membership info . Keyed off the group id and the values are a 2 element list of entity id and entity kind id ( same values as the membership model ) . If no group ids are passed , then all groups will ...
membership_queryset = EntityGroupMembership . objects . filter ( Q ( entity__isnull = True ) | ( Q ( entity__isnull = False ) & Q ( entity__is_active = is_active ) ) ) if is_active is None : membership_queryset = EntityGroupMembership . objects . all ( ) if group_ids : membership_queryset = membership_queryset ...
def best_sell_2 ( self ) : """量縮價跌 : rtype : bool"""
result = self . data . value [ - 1 ] < self . data . value [ - 2 ] and self . data . price [ - 1 ] < self . data . price [ - 2 ] return result
def cmd_cammsg_old ( self , args ) : '''cammsg _ old'''
print ( "Sent old DIGICAM_CONTROL" ) self . master . mav . digicam_control_send ( self . settings . target_system , # target _ system 0 , # target _ component 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 )
def phenotypes ( ) : """Add phenotype ( s ) to the case model ."""
ind_id = request . form [ 'ind_id' ] phenotype_id = request . form [ 'phenotype_id' ] if not phenotype_id : return abort ( 500 , 'no phenotype_id submitted' ) ind_obj = app . db . individual ( ind_id ) try : added_terms = app . db . add_phenotype ( ind_obj , phenotype_id ) if added_terms is None : f...
def bulk_copy ( self , ids ) : """Bulk copy a set of users . : param ids : Int list of user IDs . : return : : class : ` users . User < users . User > ` list"""
schema = UserSchema ( ) return self . service . bulk_copy ( self . base , self . RESOURCE , ids , schema )
def addSkip ( self , test , reason ) : """registers a test as skipped : param test : test to register : param reason : reason why the test was skipped"""
super ( ) . addSkip ( test , reason ) self . test_info ( test ) self . _call_test_results ( 'addSkip' , test , reason )
def this_week_day ( base_date , weekday ) : """Finds coming weekday"""
day_of_week = base_date . weekday ( ) # If today is Tuesday and the query is ` this monday ` # We should output the next _ week monday if day_of_week > weekday : return next_week_day ( base_date , weekday ) start_of_this_week = base_date - timedelta ( days = day_of_week + 1 ) day = start_of_this_week + timedelta ( ...
def Type_string ( self , text , interval = 0 , dl = 0 ) : """键盘输入字符串 , interval是字符间输入时间间隔 , 单位 " 秒 " """
self . Delay ( dl ) self . keyboard . type_string ( text , interval )
def _storage_purge_all ( delete = False , verbosity = 0 ) : """Purge unreferenced storages ."""
orphaned_storages = Storage . objects . filter ( data = None ) if verbosity >= 1 : if orphaned_storages . exists ( ) : logger . info ( __ ( "Unreferenced storages ({}):" , orphaned_storages . count ( ) ) ) for storage_id in orphaned_storages . values_list ( 'id' , flat = True ) : logger ...
def add_release ( self , release ) : """Add a release object if it does not already exist"""
for r in self . releases : if r . version == release . version : return self . releases . append ( release )
def register_formatter ( field_typestr ) : """Decorate a configuration field formatter function to register it with the ` get _ field _ formatter ` accessor . This decorator also performs common helpers for the formatter functions : - Does type checking on the field argument passed to a formatter . - Assemb...
def decorator_register ( formatter ) : @ functools . wraps ( formatter ) def wrapped_formatter ( * args , ** kwargs ) : field_name = args [ 0 ] field = args [ 1 ] field_id = args [ 2 ] # Before running the formatter , do type checking field_type = get_type ( field_typestr...
def read_node ( self , name , ** kwargs ) : # noqa : E501 """read _ node # noqa : E501 read the specified Node # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . read _ node ( name , async _ req =...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . read_node_with_http_info ( name , ** kwargs ) # noqa : E501 else : ( data ) = self . read_node_with_http_info ( name , ** kwargs ) # noqa : E501 return data