signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def check_if_win ( self ) : """Here are counted the flags . Is checked if the user win ."""
self . flagcount = 0 win = True for x in range ( 0 , len ( self . mine_matrix [ 0 ] ) ) : for y in range ( 0 , len ( self . mine_matrix ) ) : if self . mine_matrix [ y ] [ x ] . state == 1 : self . flagcount += 1 if not self . mine_matrix [ y ] [ x ] . has_mine : win ...
def get_sample ( self , md5 ) : """Get a sample from the DataStore . Args : md5 : the md5 of the sample Returns : A dictionary of meta data about the sample which includes a [ ' raw _ bytes ' ] key that contains the raw bytes . Raises : Workbench . DataNotFound if the sample is not found ."""
# First we try a sample , if we can ' t find one we try getting a sample _ set . sample = self . data_store . get_sample ( md5 ) if not sample : return { 'sample_set' : { 'md5_list' : self . get_sample_set ( md5 ) } } return { 'sample' : sample }
def to_json ( self ) : """Inherit doc ."""
json = { "name" : self . __class__ . __name__ , "num_ranges" : len ( self . _iters ) } for i in xrange ( len ( self . _iters ) ) : json_item = self . _iters [ i ] . to_json ( ) query_spec = json_item [ "query_spec" ] item_name = json_item [ "name" ] # Delete and move one level up del json_item [ "qu...
def get_statements ( self , reprocess = False ) : """General method to create statements ."""
if self . _statements is None or reprocess : # Handle the case that there is no content . if self . content is None : self . _statements = [ ] return [ ] # Map to the different processors . if self . reader == ReachReader . name : if self . format == formats . JSON : # Process the re...
def coordination_geometry_symmetry_measures_standard ( self , coordination_geometry , algo , points_perfect = None , optimization = None ) : """Returns the symmetry measures for a set of permutations ( whose setup depends on the coordination geometry ) for the coordination geometry " coordination _ geometry " . S...
# permutations _ symmetry _ measures = np . zeros ( len ( algo . permutations ) , # np . float ) if optimization == 2 : permutations_symmetry_measures = [ None ] * len ( algo . permutations ) permutations = list ( ) algos = list ( ) local2perfect_maps = list ( ) perfect2local_maps = list ( ) for...
def reset_sequence ( cls , value = None , force = False ) : """Reset the sequence counter . Args : value ( int or None ) : the new ' next ' sequence value ; if None , recompute the next value from _ setup _ next _ sequence ( ) . force ( bool ) : whether to force - reset parent sequence counters in a facto...
cls . _meta . reset_sequence ( value , force = force )
def register_actor ( name , actor_handle ) : """Register a named actor under a string key . Args : name : The name of the named actor . actor _ handle : The actor object to be associated with this name"""
if not isinstance ( name , str ) : raise TypeError ( "The name argument must be a string." ) if not isinstance ( actor_handle , ray . actor . ActorHandle ) : raise TypeError ( "The actor_handle argument must be an ActorHandle " "object." ) actor_name = _calculate_key ( name ) pickled_state = pickle . dumps ( ac...
def transformer_moe_8k ( ) : """Hyper parameters specifics for long sequence generation ."""
hparams = transformer_moe_base ( ) hparams . batch_size = 8192 hparams . max_length = 0 # max _ length = = batch _ size hparams . eval_drop_long_sequences = True hparams . min_length_bucket = 256 # Avoid cyclic problems for big batches hparams . default_ff = "sep" hparams . hidden_size = 1024 return hparams
def _show_info ( app ) : """显示系统信息"""
print ( "Server start on port {0} (processes: {1}) ..." . format ( app . port , app . processes ) ) print ( "Start time: {0}" . format ( datetime . now ( ) . isoformat ( " " ) ) ) print print ( "Parameters:" ) for k in sorted ( dir ( __conf__ ) ) : if k . startswith ( "__" ) : continue print ( " {0:<20...
def unwrap ( node ) : """Remove a node , replacing it with its children ."""
for child in list ( node . childNodes ) : node . parentNode . insertBefore ( child , node ) remove_node ( node )
def parse_config ( self , config_file ) : """Given a configuration file , read in and interpret the results : param config _ file : : return :"""
with open ( config_file , 'r' ) as f : config = json . load ( f ) self . params = config if self . params [ 'proxy' ] [ 'proxy_type' ] : self . params [ 'proxy' ] = { self . params [ 'proxy' ] [ 'proxy_type' ] : self . params [ 'proxy' ] [ 'proxy_url' ] }
def datetime ( anon , obj , field , val ) : """Returns a random datetime"""
return anon . faker . datetime ( field = field )
def logout ( self ) : """Log currently authenticated user out , invalidating any existing tokens ."""
# Remove token from local cache # MAINT : need to expire token on server data = self . _read_uaa_cache ( ) if self . uri in data : for client in data [ self . uri ] : if client [ 'id' ] == self . client [ 'id' ] : data [ self . uri ] . remove ( client ) with open ( self . _cache_path , 'w' ) as ...
def multiplicity ( keys , axis = semantics . axis_default ) : """return the multiplicity of each key , or how often it occurs in the set Parameters keys : indexable object Returns ndarray , [ keys . size ] , int the number of times each input item occurs in the set"""
index = as_index ( keys , axis ) return index . count [ index . inverse ]
def tunnel_open ( self ) : '''Open tunnel'''
if ( self . server . is_server_running ( ) == 'no' or self . server . is_server_running ( ) == 'maybe' ) : print ( "Error: Sorry, you need to have the server running to open a " "tunnel. Try 'server on' first." ) else : self . tunnel . open ( )
def rollback ( self ) : """Do journal rollback"""
# Close the journal for writing , if this is an automatic rollback following a crash , # the file descriptor will not be open , so don ' t need to do anything . if self . journal != None : self . journal . close ( ) self . journal = None # Read the journal journ_list = [ ] with open ( self . j_file ) as fle : f...
def catch ( checker , * a , ** kw ) : """Helper for tests - catch error and return it as dict"""
try : return checker ( * a , ** kw ) except DataError as error : return error
def rand_imancon ( X , rho ) : """Iman - Conover Method to generate random ordinal variables ( Implementation adopted from Ekstrom , 2005) x : ndarray < obs x cols > matrix with " cols " ordinal variables that are uncorrelated . rho : ndarray Spearman Rank Correlation Matrix Links * Iman , R . L . ,...
import numpy as np import scipy . stats as sstat import scipy . special as sspec # data prep n , d = X . shape # Ordering T = np . corrcoef ( X , rowvar = 0 ) Q = np . linalg . cholesky ( T ) invQ = np . linalg . inv ( Q ) # inv ( Q ) P = np . linalg . cholesky ( rho ) S = np . dot ( invQ , P ) # S = P * inv ( Q ) # ge...
def pythonize ( self , val ) : """Convert value into a list : : * split value ( or each element if value is a list ) on coma char * strip split values : param val : value to convert : type val : str : return : list corresponding to value : rtype : list"""
if isinstance ( val , list ) : return [ s . strip ( ) if hasattr ( s , "strip" ) else s for s in list_split ( val , self . split_on_comma ) if hasattr ( s , "strip" ) and s . strip ( ) != '' or self . keep_empty ] return [ s . strip ( ) if hasattr ( s , "strip" ) else s for s in to_split ( val , self . split_on_com...
def _spelling_pipeline ( self , sources , options , personal_dict ) : """Check spelling pipeline ."""
for source in self . _pipeline_step ( sources , options , personal_dict ) : # Don ' t waste time on empty strings if source . _has_error ( ) : yield Results ( [ ] , source . context , source . category , source . error ) elif not source . text or source . text . isspace ( ) : continue else :...
def compose_post ( apikey , resize , rotation , noexif ) : """composes basic post requests"""
check_rotation ( rotation ) check_resize ( resize ) post_data = { 'formatliste' : ( '' , 'og' ) , 'userdrehung' : ( '' , rotation ) , 'apikey' : ( '' , apikey ) } if resize and 'x' in resize : width , height = [ x . strip ( ) for x in resize . split ( 'x' ) ] post_data [ 'udefb' ] = ( '' , width ) post_data...
def get_external_id ( self , submission_id ) : """Returns human readable submission external ID . Args : submission _ id : internal submission ID . Returns : human readable ID ."""
submission = self . find_by_id ( submission_id ) if not submission : return None if 'team_id' in submission . participant_id : return submission . participant_id [ 'team_id' ] elif 'baseline_id' in submission . participant_id : return 'baseline_' + submission . participant_id [ 'baseline_id' ] else : re...
def do_pass ( self , element , decl , pseudo ) : """No longer valid way to set processing pass ."""
log ( WARN , u"Old-style pass as declaration not allowed.{}" . format ( decl . value ) . encpde ( 'utf-8' ) )
def _bins_to_json ( h2 ) : """Create GeoJSON representation of histogram bins Parameters h2 : physt . histogram _ nd . Histogram2D A histogram of coordinates ( in degrees ) Returns geo _ json : dict"""
south = h2 . get_bin_left_edges ( 0 ) north = h2 . get_bin_right_edges ( 0 ) west = h2 . get_bin_left_edges ( 1 ) east = h2 . get_bin_right_edges ( 1 ) return { "type" : "FeatureCollection" , "features" : [ { "type" : "Feature" , "geometry" : { "type" : "Polygon" , # Note that folium and GeoJson have them swapped "coor...
def detect_column_renamings ( self , table_differences ) : """Try to find columns that only changed their names . : type table _ differences : TableDiff"""
rename_candidates = { } for added_column_name , added_column in table_differences . added_columns . items ( ) : for removed_column in table_differences . removed_columns . values ( ) : if len ( self . diff_column ( added_column , removed_column ) ) == 0 : if added_column . get_name ( ) not in re...
def fetch ( self ) : """Fetch a NumberInstance : returns : Fetched NumberInstance : rtype : twilio . rest . pricing . v1 . voice . number . NumberInstance"""
params = values . of ( { } ) payload = self . _version . fetch ( 'GET' , self . _uri , params = params , ) return NumberInstance ( self . _version , payload , number = self . _solution [ 'number' ] , )
def write_input ( self , output_dir = "." , make_dir_if_not_present = True ) : """Write VASP input to a directory . Args : output _ dir ( str ) : Directory to write to . Defaults to current directory ( " . " ) . make _ dir _ if _ not _ present ( bool ) : Create the directory if not present . Defaults to T...
if make_dir_if_not_present and not os . path . exists ( output_dir ) : os . makedirs ( output_dir ) for k , v in self . items ( ) : with zopen ( os . path . join ( output_dir , k ) , "wt" ) as f : f . write ( v . __str__ ( ) )
def get_new_edges ( self , level ) : """Get new edges from the pattern graph for the graph search algorithm The level argument denotes the distance of the new edges from the starting vertex in the pattern graph ."""
if level == 0 : edges0 = [ ( 0 , 1 ) , ( 0 , 2 ) ] elif level >= ( self . max_size - 1 ) // 2 : edges0 = [ ] else : l2 = level * 2 edges0 = [ ( l2 - 1 , l2 + 1 ) , ( l2 , l2 + 2 ) ] return edges0 , [ ]
def download_loci ( self ) : """Uses a multi - threaded approach to download allele files"""
# Setup the multiprocessing pool . pool = multiprocessing . Pool ( processes = self . threads ) # Map the list of loci URLs to the download method pool . map ( self . download_threads , self . loci_url ) pool . close ( ) pool . join ( )
def _import_symbol ( import_path , setting_name ) : """Import a class or function by name ."""
mod_name , class_name = import_path . rsplit ( '.' , 1 ) # import module try : mod = import_module ( mod_name ) cls = getattr ( mod , class_name ) except ImportError as e : __ , __ , exc_traceback = sys . exc_info ( ) frames = traceback . extract_tb ( exc_traceback ) if len ( frames ) > 1 : ...
def save_pdf ( self , save_model = True ) : """Save the receipt as a PDF related to this model . The related : class : ` ~ . Receipt ` should be validated first , of course . : param bool save _ model : If True , immediately save this model instance ."""
from django_afip . views import ReceiptPDFView if not self . receipt . is_validated : raise exceptions . DjangoAfipException ( _ ( 'Cannot generate pdf for non-authorized receipt' ) ) self . pdf_file = File ( BytesIO ( ) , name = '{}.pdf' . format ( uuid . uuid4 ( ) . hex ) ) render_pdf ( template = 'receipts/code_...
def fast_clone ( self , VM , clone_name , mem = None ) : """Create a ' fast ' clone of a VM . This means we make a snapshot of the disk and copy some of the settings and then create a new VM based on the snapshot and settings The VM is transient so when it is shutdown it deletes itself : param VM : The VM t...
disks = VM . get_disks ( ) ints = VM . get_interfaces ( ) count = 0 new_disks = [ ] for disk in disks : pool = disk . pool new_disk_name = '{0}-disk{1}' . format ( clone_name , count ) count += 1 new_disk = pool . create_backed_vol ( new_disk_name , disk ) new_disks . append ( new_disk ) for inter i...
def get_heap ( self , * args , ** kwargs ) : """Return a new heap which contains all the new items and item descriptors since the last call . This is a convenience wrapper around : meth : ` add _ to _ heap ` ."""
heap = Heap ( self . _flavour ) self . add_to_heap ( heap , * args , ** kwargs ) return heap
def from_dict ( cls , tx , skip_schema_validation = True ) : """Transforms a Python dictionary to a Transaction object . Args : tx _ body ( dict ) : The Transaction to be transformed . Returns : : class : ` ~ bigchaindb . common . transaction . Transaction `"""
operation = tx . get ( 'operation' , Transaction . CREATE ) if isinstance ( tx , dict ) else Transaction . CREATE cls = Transaction . resolve_class ( operation ) if not skip_schema_validation : cls . validate_id ( tx ) cls . validate_schema ( tx ) inputs = [ Input . from_dict ( input_ ) for input_ in tx [ 'inpu...
def transform ( self , X ) : """Embeds data points in the learned linear embedding space . Transforms samples in ` ` X ` ` into ` ` X _ embedded ` ` , samples inside a new embedding space such that : ` ` X _ embedded = X . dot ( L . T ) ` ` , where ` ` L ` ` is the learned linear transformation ( See : class ...
X_checked = check_input ( X , type_of_inputs = 'classic' , estimator = self , preprocessor = self . preprocessor_ , accept_sparse = True ) return X_checked . dot ( self . transformer_ . T )
def decrypt_document ( self , document_id , encrypted_content ) : """Decrypt a previously encrypted content using the secret store keys identified by document _ id . Note that decryption requires permission already granted to the consumer account . : param document _ id : hex str id of document to use for enc...
return self . _secret_store_client ( self . _account ) . decrypt_document ( remove_0x_prefix ( document_id ) , encrypted_content )
def generate_phonetic_representation ( self , word ) : """Returns a generated phonetic representation for a word . : param str word : a word to be phoneticized . : return : A list of phonemes representing the phoneticized word . This method is used for words for which there is no pronunication entry in the ...
with NamedTemporaryFile ( ) as temp_file : # Write the word to a temp file temp_file . write ( word ) # todo - clean up this messy t2p path t2pargs = [ os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , 't2p/t2p' ) ) , '-transcribe' , os . path . join ( data_path , 'cmudict.0.7a.tre...
def write_how_much ( self , file ) : """Write component quantities to a table ."""
report = CaseReport ( self . case ) col1_header = "Attribute" col1_width = 24 col2_header = "P (MW)" col3_header = "Q (MVAr)" col_width = 8 sep = "=" * col1_width + " " + "=" * col_width + " " + "=" * col_width + "\n" # Row headers file . write ( sep ) file . write ( "%s" % col1_header . center ( col1_width ) ) file . ...
def get_other_props ( all_props , reserved_props ) : # type : ( Dict , Tuple ) - > Optional [ Dict ] """Retrieve the non - reserved properties from a dictionary of properties @ args reserved _ props : The set of reserved properties to exclude"""
if hasattr ( all_props , 'items' ) and callable ( all_props . items ) : return dict ( [ ( k , v ) for ( k , v ) in list ( all_props . items ( ) ) if k not in reserved_props ] ) return None
def update ( self , incident_id , name = None , message = None , status = None , visible = None , component_id = None , component_status = None , notify = None , created_at = None , template = None , tpl_vars = None ) : """Update an Incident : param int incident _ id : Incident ID : param str name : Name of the...
data = ApiParams ( ) data [ 'name' ] = name data [ 'message' ] = message data [ 'status' ] = status data [ 'visible' ] = visible data [ 'component_id' ] = component_id data [ 'component_status' ] = component_status data [ 'notify' ] = notify data [ 'created_at' ] = created_at data [ 'template' ] = template data [ 'vars...
def glob_files ( root_dir , includes = None , excludes = None , gitignore = None ) : """Powerful and flexible utility to search and tag files using patterns . : param root _ dir : directory where we start the search : param includes : list or iterator of include pattern tuples ( pattern , tag ) : param exclud...
# docu here : https : / / docs . python . org / 3 / library / pathlib . html if not includes : includes = [ '**' ] else : # we need to iterate multiple times ( iterator safeguard ) includes = list ( includes ) if excludes : # we need to iterate multiple times ( iterator safeguard ) excludes = list ( exclude...
def OnInsertRows ( self , event ) : """Insert the maximum of 1 and the number of selected rows"""
bbox = self . grid . selection . get_bbox ( ) if bbox is None or bbox [ 1 ] [ 0 ] is None : # Insert rows at cursor ins_point = self . grid . actions . cursor [ 0 ] - 1 no_rows = 1 else : # Insert at lower edge of bounding box ins_point = bbox [ 0 ] [ 0 ] - 1 no_rows = self . _get_no_rowscols ( bbox ) [...
def AutorizarLiquidacion ( self ) : "Generar o ajustar una liquidación única y obtener del CAE"
# limpio los elementos que no correspondan por estar vacios : for campo in [ "guia" , "dte" , "gasto" , "tributo" ] : if campo in self . solicitud and not self . solicitud [ campo ] : del self . solicitud [ campo ] for item in self . solicitud [ 'itemDetalleLiquidacion' ] : if not item . get ( "liquidac...
def simplify ( self ) : """Return a new equivalent unit object with a simplified unit expression > > > import unyt as u > > > unit = ( u . m * * 2 / u . cm ) . simplify ( ) > > > unit 100 * m"""
expr = self . expr self . expr = _cancel_mul ( expr , self . registry ) return self
def attention_mask_ignore_padding ( inputs , dtype = tf . float32 ) : """Bias for encoder - decoder attention . Args : inputs : a mtf . Tensor with shape [ . . . , length _ dim ] dtype : a tf . dtype Returns : a mtf . Tensor with shape [ . . . , memory _ length _ dim ]"""
inputs = rename_length_to_memory_length ( inputs ) return mtf . cast ( mtf . equal ( inputs , 0 ) , dtype ) * - 1e9
def get_line_segments ( line ) : """Split up a line into lhs , rhs , comment , flags lhs ist defined as the leftmost assignment ( line does not need to be an assignment ) : param line : : return : lhs , rhs , comment"""
line = line . strip ( ) tokens = tk . generate_tokens ( io . StringIO ( line ) . readline ) equality_signs = [ - 1 ] comment_tuple = None , "" for i , t in enumerate ( tokens ) : if t . type == tk . COMMENT : # store string _ index and comment string comment_tuple = t . start [ 1 ] , t . string if t . t...
def call ( self , command , ** kwargs ) : """Make a request to DynamoDB using the raw botocore API Parameters command : str The name of the Dynamo command to execute * * kwargs : dict The parameters to pass up in the request Raises exc : : class : ` ~ . DynamoDBError ` Returns data : dict"""
for hook in self . _hooks [ 'precall' ] : hook ( self , command , kwargs ) op = getattr ( self . client , command ) attempt = 0 while True : try : data = op ( ** kwargs ) break except ClientError as e : exc = translate_exception ( e , kwargs ) attempt += 1 if isinstan...
def add_constituency_tree ( self , my_tree ) : """Adds a constituency tree to the constituency layer @ type my _ tree : L { Ctree } @ param my _ tree : the constituency tree object"""
if self . constituency_layer is None : self . constituency_layer = Cconstituency ( ) self . root . append ( self . constituency_layer . get_node ( ) ) self . constituency_layer . add_tree ( my_tree )
def _styleof ( expr , styles ) : """Merge style dictionaries in order"""
style = dict ( ) for expr_filter , sty in styles : if expr_filter ( expr ) : style . update ( sty ) return style
def backup_db ( aws_access_key_id , aws_secret_access_key , bucket_name , s3_folder , database , mysql_host , mysql_port , db_user , db_pass , db_backups_dir , backup_aging_time ) : """dumps databases into / backups , uploads to s3 , deletes backups older than a month fab - f . / fabfile . py backup _ dbs : par...
# Connect to the bucket bucket = s3_bucket ( aws_access_key_id , aws_secret_access_key , bucket_name ) key = boto . s3 . key . Key ( bucket ) bucketlist = bucket . list ( ) pat = "[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]-%s.sql.bz2" % database sql_file = '%s-%s.sql' % ( dt . now ( ) ....
def time ( self , * args , ** kwargs ) : """NAME : time PURPOSE : return the times at which the orbit is sampled INPUT : t - ( default : integration times ) time at which to get the time ( for consistency reasons ) ; default is to return the list of times at which the orbit is sampled ro = ( Object - wi...
if len ( args ) == 0 : try : return self . t except AttributeError : return 0. else : return args [ 0 ]
def install_documentation ( path = "./Litho1pt0-Notebooks" ) : """Install the example notebooks for litho1pt0 in the given location WARNING : If the path exists , the Notebook files will be written into the path and will overwrite any existing files with which they collide . The default path ( " . / Litho1pt0...
# # Question - overwrite or not ? shutils fails if directory exists . Notebooks_Path = _pkg_resources . resource_filename ( 'litho1pt0' , 'Notebooks' ) ct = _dir_util . copy_tree ( Notebooks_Path , path , preserve_mode = 1 , preserve_times = 1 , preserve_symlinks = 1 , update = 0 , verbose = 1 , dry_run = 0 ) return
def write_to_manifest ( self ) : """Overwrites the section of the manifest with the featureconfig ' s value"""
self . manifest . remove_section ( self . feature_name ) self . manifest . add_section ( self . feature_name ) for k , v in self . raw_dict . items ( ) : self . manifest . set ( self . feature_name , k , v )
def write_to_datastore ( self ) : """Writes all image batches to the datastore ."""
client = self . _datastore_client with client . no_transact_batch ( ) as client_batch : for batch_id , batch_data in iteritems ( self . _data ) : batch_key = client . key ( self . _entity_kind_batches , batch_id ) batch_entity = client . entity ( batch_key ) for k , v in iteritems ( batch_da...
def system_drop_keyspace ( self , keyspace ) : """drops a keyspace and any column families that are part of it . returns the new schema id . Parameters : - keyspace"""
self . _seqid += 1 d = self . _reqs [ self . _seqid ] = defer . Deferred ( ) self . send_system_drop_keyspace ( keyspace ) return d
def should_reuse_driver ( self , scope , test_passed , context = None ) : """Check if the driver should be reused : param scope : execution scope ( function , module , class or session ) : param test _ passed : True if the test has passed : param context : behave context : returns : True if the driver shoul...
reuse_driver = self . config . getboolean_optional ( 'Driver' , 'reuse_driver' ) reuse_driver_session = self . config . getboolean_optional ( 'Driver' , 'reuse_driver_session' ) restart_driver_after_failure = ( self . config . getboolean_optional ( 'Driver' , 'restart_driver_after_failure' ) or self . config . getboole...
def read_csv ( * args , ** kwargs ) : """Like pandas . read _ csv , only little smarter : check left column to see if it should be the index _ col > > > read _ csv ( os . path . join ( DATA _ PATH , ' mavis - batey - greetings . csv ' ) ) . head ( ) sentence is _ greeting 0 It was a strange little outfit in t...
kwargs . update ( { 'low_memory' : False } ) if isinstance ( args [ 0 ] , pd . DataFrame ) : df = args [ 0 ] else : logger . info ( 'Reading CSV with `read_csv(*{}, **{})`...' . format ( args , kwargs ) ) df = pd . read_csv ( * args , ** kwargs ) if looks_like_index ( df [ df . columns [ 0 ] ] ) : df = ...
def iterate_over_file ( self , fasta_path ) : """Generator that yields identifiers paired with sequences ."""
with self . _open ( fasta_path ) as f : for line in f : line = line . rstrip ( ) if len ( line ) == 0 : continue # have to slice into a bytes object or else I get a single integer first_char = line [ 0 : 1 ] if first_char == b">" : id_and_seq = self . ...
def finder_for_path ( path ) : """Return a resource finder for a path , which should represent a container . : param path : The path . : return : A : class : ` ResourceFinder ` instance for the path ."""
result = None # calls any path hooks , gets importer into cache pkgutil . get_importer ( path ) loader = sys . path_importer_cache . get ( path ) finder = _finder_registry . get ( type ( loader ) ) if finder : module = _dummy_module module . __file__ = os . path . join ( path , '' ) module . __loader__ = lo...
def without_operations_touching ( self , qubits : Iterable [ raw_types . Qid ] ) : """Returns an equal moment , but without ops on the given qubits . Args : qubits : Operations that touch these will be removed . Returns : The new moment ."""
qubits = frozenset ( qubits ) if not self . operates_on ( qubits ) : return self return Moment ( operation for operation in self . operations if qubits . isdisjoint ( frozenset ( operation . qubits ) ) )
def dimensions ( self ) : """Returns dimensions as ( x , y ) tuple ."""
return ( self . xmax - self . xmin , self . ymax - self . ymin )
def set_id ( self , id = '$' ) : """Set the last - read message id for the stream within the context of the parent : py : class : ` ConsumerGroup ` . By default this will be the special " $ " identifier , meaning all messages are marked as having been read . : param id : id of last - read message ( or " $ " )...
return self . database . xgroup_setid ( self . key , self . group , id )
def main ( ) : """Main function , called when run as an application ."""
global server_address # check the version if ( sys . version_info [ : 2 ] != ( 2 , 5 ) ) : sys . stderr . write ( "Python 2.5 only\n" ) sys . exit ( 1 ) # parse the command line arguments parser = ArgumentParser ( description = __doc__ ) parser . add_argument ( "host" , nargs = '?' , help = "address of host (de...
def log ( func ) : """打印函数运行日志的装饰器 : param func : : return :"""
# wraps 这个装饰器会将 func 的 doc 和 _ _ name _ _ 复制过来 # 否则在 wrapper 中调用 func . _ _ name _ _ 输出的就是 wrapper @ wraps ( func ) def wrapper ( * args , ** kwargs ) : print ( 'before call %s' % func . __name__ ) ret = func ( * args , ** kwargs ) print ( 'after call %s' % func . __name__ ) return ret return wrapper
def formatted_prefix ( self , ** format_info ) : """Gets a dict with format info , and formats a prefix template with that info . For example : if our prefix template is : ' some _ file _ { groups [ 0 ] } _ { file _ number } ' And we have this method called with : formatted _ prefix ( groups = [ US ] , file...
prefix_name = self . prefix_template . format ( ** format_info ) file_number = format_info . pop ( 'file_number' , 0 ) if prefix_name == self . prefix_template : prefix_name += '{:04d}' . format ( file_number ) for key , value in format_info . iteritems ( ) : if value and not self . _has_key_info ( key ) : ...
def clear_job_cache ( hours = 24 ) : '''Forcibly removes job cache folders and files on a minion . . . versionadded : : 2018.3.0 WARNING : The safest way to clear a minion cache is by first stopping the minion and then deleting the cache files before restarting it . CLI Example : . . code - block : : bash...
threshold = time . time ( ) - hours * 60 * 60 for root , dirs , files in salt . utils . files . safe_walk ( os . path . join ( __opts__ [ 'cachedir' ] , 'minion_jobs' ) , followlinks = False ) : for name in dirs : try : directory = os . path . join ( root , name ) mtime = os . path ....
def from_request ( cls , request ) : """Create new TransientShardState from webapp request ."""
mapreduce_spec = MapreduceSpec . from_json_str ( request . get ( "mapreduce_spec" ) ) mapper_spec = mapreduce_spec . mapper input_reader_spec_dict = json . loads ( request . get ( "input_reader_state" ) , cls = json_util . JsonDecoder ) input_reader = mapper_spec . input_reader_class ( ) . from_json ( input_reader_spec...
def firmware_download_input_protocol_type_sftp_protocol_sftp_host_key_check ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) firmware_download = ET . Element ( "firmware_download" ) config = firmware_download input = ET . SubElement ( firmware_download , "input" ) protocol_type = ET . SubElement ( input , "protocol-type" ) sftp_protocol = ET . SubElement ( protocol_type , "sftp-protocol" ) sftp = ET . SubEl...
def ensembl_request ( self , ext , headers ) : """obtain sequence via the ensembl REST API"""
self . attempt += 1 if self . attempt > 5 : raise ValueError ( "too many attempts, figure out why its failing" ) response , status , requested_headers = self . open_url ( self . server + ext , headers = headers ) # we might end up passing too many simultaneous requests , or too many # requests per hour , just wait ...
def parse_s3_url ( url ) : """Returns an ( s3 bucket , key name / prefix ) tuple from a url with an s3 scheme Args : url ( str ) : Returns : tuple : A tuple containing : str : S3 bucket name str : S3 key"""
parsed_url = urlparse ( url ) if parsed_url . scheme != "s3" : raise ValueError ( "Expecting 's3' scheme, got: {} in {}" . format ( parsed_url . scheme , url ) ) return parsed_url . netloc , parsed_url . path . lstrip ( '/' )
def log ( x , context = None ) : """Return the natural logarithm of x ."""
return _apply_function_in_current_context ( BigFloat , mpfr . mpfr_log , ( BigFloat . _implicit_convert ( x ) , ) , context , )
def GetDWORD ( self , buff , idx = 0 ) : '''Internal method . Reads a double word ( 4 bytes ) from a buffer .'''
result = buff [ idx ] + ( buff [ idx + 1 ] << 8 ) + ( buff [ idx + 2 ] << 16 ) + ( buff [ idx + 3 ] << 24 ) if result == 0xFFFFFFFF : result = 0 return result
def add_state ( self , state_name , initial_state , batch_size = None ) : """Adds a state to the state saver . Args : state _ name : The name of this state . initial _ state : The initial state vector . Only zeros are supported . batch _ size : The batch _ size or None for unknown ."""
state_shape = initial_state . get_shape ( ) . as_list ( ) full_shape = [ batch_size ] + state_shape if not batch_size : # TODO ( ) : - 1 is now reserved for unknown , so this should be # updated , but that requires coordination with the binary and is # checkpoint incompatible . # TODO ( eiderman ) : When we make the ab...
def close ( self , code = 3000 , message = 'Go away!' ) : """Close session or endpoint connection . ` code ` Closing code ` message ` Close message"""
if self . state != CLOSED : try : self . conn . on_close ( ) except : LOG . debug ( "Failed to call on_close()." , exc_info = True ) finally : self . state = CLOSED self . close_reason = ( code , message ) self . conn = None # Bump stats self . stats . on_sess...
def nanopub_stats ( ctx , input_fn ) : """Collect statistics on nanopub file input _ fn can be json , jsonl or yaml and additionally gzipped"""
counts = { "nanopubs" : 0 , "assertions" : { "total" : 0 , "subject_only" : 0 , "nested" : 0 , "relations" : { } } , } for np in bnf . read_nanopubs ( input_fn ) : if "nanopub" in np : counts [ "nanopubs" ] += 1 counts [ "assertions" ] [ "total" ] += len ( np [ "nanopub" ] [ "assertions" ] ) ...
def file_content ( self , value ) : """The Base64 encoded content of the attachment : param value : The Base64 encoded content of the attachment : type value : FileContent , string"""
if isinstance ( value , FileContent ) : self . _file_content = value else : self . _file_content = FileContent ( value )
def isReadOnly ( self ) : """Returns the read only for this widget from the editor . Differs per type , not all types support read only . : param text | < str >"""
if ( self . _editor and hasattr ( self . _editor , 'isReadOnly' ) ) : return self . _editor . isReadOnly ( ) return False
def _get_vswitch_name ( self , network_type , physical_network ) : """Get the vswitch name for the received network information ."""
if network_type != constants . TYPE_LOCAL : vswitch_name = self . _get_vswitch_for_physical_network ( physical_network ) else : vswitch_name = self . _local_network_vswitch if vswitch_name : return vswitch_name err_msg = _ ( "No vSwitch configured for physical network " "'%(physical_network)s'. Neutron netw...
def _ask_openapi ( ) : """Return whether we should create a ( new ) skeleton ."""
if Path ( 'openapi.yml' ) . exists ( ) : question = 'Override local openapi.yml with a new skeleton? (y/N) ' default = False else : question = 'Do you have REST endpoints and wish to create an API' ' skeleton in openapi.yml? (Y/n) ' default = True while True : answer = input ( question ) if answ...
def nPr ( n , r ) : """Calculates nPr . Args : n ( int ) : total number of items . r ( int ) : items to permute Returns : nPr ."""
f = math . factorial return int ( f ( n ) / f ( n - r ) )
def get_policy_type ( self , project , type_id ) : """GetPolicyType . Retrieve a specific policy type by ID . : param str project : Project ID or project name : param str type _ id : The policy ID . : rtype : : class : ` < PolicyType > < azure . devops . v5_0 . policy . models . PolicyType > `"""
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if type_id is not None : route_values [ 'typeId' ] = self . _serialize . url ( 'type_id' , type_id , 'str' ) response = self . _send ( http_method = 'GET' , location_id = '44096322-2d...
def parse_a2 ( a2_text , entities , tees_sentences ) : """Extracts events from a TEES a2 output into a networkx directed graph . Parameters a2 _ text : str Text of the TEES a2 file output , specifying the event graph sentences _ xml _ gz : str Filename with the TEES sentence segmentation in a gzipped xml ...
G = nx . DiGraph ( ) event_names = set ( ) # Put entities into the graph for entity_name in entities . keys ( ) : offset0 = entities [ entity_name ] . offsets [ 0 ] G . add_node ( entity_name , text = entities [ entity_name ] . entity_name , type = entities [ entity_name ] . entity_type , is_event = False , sen...
def capability ( cap , * wrap_exceptions ) : """Return a decorator , that registers function as capability . Also , all specified exceptions are caught and instead of them the : class : ` . WClientCapabilityError ` exception is raised : param cap : target function capability ( may be a str or : class : ` . WNet...
if isinstance ( cap , WNetworkClientCapabilities ) is True : cap = cap . value elif isinstance ( cap , str ) is False : raise TypeError ( 'Invalid capability type' ) def first_level_decorator ( decorated_function ) : def second_level_decorator ( original_function , * args , ** kwargs ) : if len ( wr...
def get_mockup_motor ( self , motor ) : """Gets the equivalent : class : ` ~ pypot . primitive . primitive . MockupMotor ` ."""
return next ( ( m for m in self . robot . motors if m . name == motor . name ) , None )
def get_main_for ( self , model ) : '''Returns main image for given model'''
try : return self . for_model ( model ) . get ( is_main = True ) except models . ObjectDoesNotExist : return None
def alert_stream ( self , reset_event , kill_event ) : """Open event stream ."""
_LOGGING . debug ( 'Stream Thread Started: %s, %s' , self . name , self . cam_id ) start_event = False parse_string = "" fail_count = 0 url = '%s/ISAPI/Event/notification/alertStream' % self . root_url # pylint : disable = too - many - nested - blocks while True : try : stream = self . hik_request . get ( u...
def list_features ( ctx , dataset , reverse , start , limit , output ) : """Get features of a dataset . Prints the features of the dataset as a GeoJSON feature collection . $ mapbox datasets list - features dataset - id All endpoints require authentication . An access token with ` datasets : read ` scope is...
stdout = click . open_file ( output , 'w' ) service = ctx . obj . get ( 'service' ) res = service . list_features ( dataset , reverse , start , limit ) if res . status_code == 200 : click . echo ( res . text , file = stdout ) else : raise MapboxCLIException ( res . text . strip ( ) )
def bind ( self , data_shapes , label_shapes = None , for_training = True , inputs_need_grad = False , force_rebind = False , shared_module = None , grad_req = 'write' ) : """Binds the symbols to construct executors . This is necessary before one can perform computation with the module . Parameters data _ sha...
raise NotImplementedError ( )
def getTraceIdsByAnnotation ( self , service_name , annotation , value , end_ts , limit , order ) : """Fetch trace ids with a particular annotation . Gets " limit " number of entries from before the " end _ ts " . When requesting based on time based annotations only pass in the first parameter , " annotation " ...
self . send_getTraceIdsByAnnotation ( service_name , annotation , value , end_ts , limit , order ) return self . recv_getTraceIdsByAnnotation ( )
def _serialize ( self , value , key , obj ) : """Output the URL for the endpoint , given the kwargs passed to ` ` _ _ init _ _ ` ` ."""
param_values = { } for name , attr_tpl in iteritems ( self . params ) : attr_name = _tpl ( str ( attr_tpl ) ) if attr_name : attribute_value = _get_value ( obj , attr_name , default = missing ) if attribute_value is None : return None if attribute_value is not missing : ...
def on_cluster_remove ( self , name ) : """Stops the cluster ' s associated discovery method from watching for changes to the cluster ' s nodes ."""
discovery_name = self . configurables [ Cluster ] [ name ] . discovery if discovery_name in self . configurables [ Discovery ] : self . configurables [ Discovery ] [ discovery_name ] . stop_watching ( self . configurables [ Cluster ] [ name ] ) self . kill_thread ( name ) self . sync_balancer_files ( )
def _notify_unload_dll ( self , event ) : """Notify the release of a loaded module . This is done automatically by the L { Debug } class , you shouldn ' t need to call it yourself . @ type event : L { UnloadDLLEvent } @ param event : Unload DLL event . @ rtype : bool @ return : C { True } to call the us...
lpBaseOfDll = event . get_module_base ( ) # # if self . has _ module ( lpBaseOfDll ) : # XXX this would trigger a scan if lpBaseOfDll in self . __moduleDict : self . _del_module ( lpBaseOfDll ) return True
def create ( model : ModelFactory , discount_factor : float , target_update_frequency : int , max_grad_norm : float , double_dqn : bool = False ) : """Vel factory function"""
return DistributionalDeepQLearning ( model_factory = model , discount_factor = discount_factor , double_dqn = double_dqn , target_update_frequency = target_update_frequency , max_grad_norm = max_grad_norm )
def _set_vlan ( self , v , load = False ) : """Setter method for vlan , mapped from YANG variable / overlay _ gateway / attach / vlan ( list ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ vlan is considered as a private method . Backends looking to populate this va...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = YANGListType ( "vid mac" , vlan . vlan , yang_name = "vlan" , rest_name = "vlan" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'vid mac' , extensions = { u'ta...
def modis1kmto250m ( lons1km , lats1km , cores = 1 ) : """Getting 250m geolocation for modis from 1km tiepoints . http : / / www . icare . univ - lille1 . fr / tutorials / MODIS _ geolocation"""
if cores > 1 : return _multi ( modis1kmto250m , lons1km , lats1km , 10 , cores ) cols1km = np . arange ( 1354 ) cols250m = np . arange ( 1354 * 4 ) / 4.0 along_track_order = 1 cross_track_order = 3 lines = lons1km . shape [ 0 ] rows1km = np . arange ( lines ) rows250m = ( np . arange ( lines * 4 ) - 1.5 ) / 4.0 sat...
def build_param_doc ( arg_names , arg_types , arg_descs , remove_dup = True ) : """Build argument docs in python style . arg _ names : list of str Argument names . arg _ types : list of str Argument type information . arg _ descs : list of str Argument description information . remove _ dup : boolean ...
param_keys = set ( ) param_str = [ ] for key , type_info , desc in zip ( arg_names , arg_types , arg_descs ) : if key in param_keys and remove_dup : continue if key == 'num_args' : continue param_keys . add ( key ) ret = '%s : %s' % ( key , type_info ) if len ( desc ) != 0 : ...
def delete_specific ( self , id , ** kwargs ) : """Removes a specific Build Configuration Set This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please define a ` callback ` function to be invoked when receiving the response . > > > def callback _ function ( res...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . delete_specific_with_http_info ( id , ** kwargs ) else : ( data ) = self . delete_specific_with_http_info ( id , ** kwargs ) return data
def create_resource ( cls , request_json ) : r"""Used to create a node in the database of type ' cls ' in response to a POST request . create _ resource should only \ be invoked on a resource when the client specifies a POST request . : param request _ json : a dictionary formatted according to the specificatio...
response = dict ( ) new_resource , location = None , None try : data = request_json [ 'data' ] if data [ 'type' ] != cls . __type__ : raise WrongTypeError ( 'type must match the type of the resource being created.' ) attributes = data . get ( 'attributes' ) if attributes : for x in attri...
def save ( self , record_key , record_data , overwrite = True , secret_key = '' ) : '''a method to create a record in the collection folder : param record _ key : string with name to assign to record ( see NOTES below ) : param record _ data : byte data for record body : param overwrite : [ optional ] boolean...
title = '%s.save' % self . __class__ . __name__ # validate inputs input_fields = { 'record_key' : record_key , 'secret_key' : secret_key } for key , value in input_fields . items ( ) : if value : object_title = '%s(%s=%s)' % ( title , key , str ( value ) ) self . fields . validate ( value , '.%s' % ...
def view_data_to_metric ( view_data , timestamp ) : """Convert a ViewData to a Metric at time ` timestamp ` . : type view _ data : : class : ` opencensus . stats . view _ data . ViewData ` : param view _ data : The ViewData to convert . : type timestamp : : class : ` datetime . datetime ` : param timestamp ...
if not view_data . tag_value_aggregation_data_map : return None md = view_data . view . get_metric_descriptor ( ) # TODO : implement gauges if is_gauge ( md . type ) : ts_start = None # pragma : NO COVER else : ts_start = view_data . start_time ts_list = [ ] for tag_vals , agg_data in view_data . tag_va...