signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def vars ( self , exclude_where = False , exclude_select = False ) : """: return : variables in query"""
def edges_get_all_vars ( e ) : output = set ( ) if is_text ( e . value ) : output . add ( e . value ) if is_expression ( e . value ) : output |= e . value . vars ( ) if e . domain . key : output . add ( e . domain . key ) if e . domain . where : output |= e . domain ....
def compile ( file ) : """Compile a Python program into byte code : param file : file to be compiled : raises check50 . Failure : if compilation fails e . g . if there is a SyntaxError"""
log ( _ ( "compiling {} into byte code..." ) . format ( file ) ) try : py_compile . compile ( file , doraise = True ) except py_compile . PyCompileError as e : log ( _ ( "Exception raised: " ) ) for line in e . msg . splitlines ( ) : log ( line ) raise Failure ( _ ( "{} raised while compiling {}...
def where_earliest ( cls , user_id ) : """Get earilest session by created _ at timestamp"""
return cls . query . filter_by ( user_id = user_id ) . order_by ( cls . created_at . asc ( ) ) . first ( )
def is_email_valid ( email ) : """Check if email is valid"""
pattern = re . compile ( r'[\w\.-]+@[\w\.-]+[.]\w+' ) return bool ( pattern . match ( email ) )
def _render ( self , value , format ) : """Writes javascript to call momentjs function"""
template = '<script>\ndocument.write(moment(\"{t}\").{f});\n</script>' return Markup ( template . format ( t = value , f = format ) )
def babel_extract ( fileobj , keywords , comment_tags , options ) : """Babel extraction method for Jinja templates . . . versionchanged : : 2.3 Basic support for translation comments was added . If ` comment _ tags ` is now set to a list of keywords for extraction , the extractor will try to find the best p...
extensions = set ( ) for extension in options . get ( 'extensions' , '' ) . split ( ',' ) : extension = extension . strip ( ) if not extension : continue extensions . add ( import_string ( extension ) ) if InternationalizationExtension not in extensions : extensions . add ( InternationalizationE...
def _get_biodata ( base_file , args ) : """Retrieve biodata genome targets customized by install parameters ."""
with open ( base_file ) as in_handle : config = yaml . safe_load ( in_handle ) config [ "install_liftover" ] = False config [ "genome_indexes" ] = args . aligners ann_groups = config . pop ( "annotation_groups" , { } ) config [ "genomes" ] = [ _setup_genome_annotations ( g , args , ann_groups ) for g in config [ "g...
def setMode ( self , mode , polarity , den , iovalue , data_length , reference , input_range , clock_enable , burn_out , channel ) : '''def setMode ( self , mode = self . AD7730 _ IDLE _ MODE , polarity = self . AD7730 _ UNIPOLAR _ MODE , den = self . AD7730 _ IODISABLE _ MODE , iovalue = 0b00 , data _ le...
mode_MSB = ( mode << 5 ) + ( polarity << 4 ) + ( den << 3 ) + ( iovalue << 1 ) + data_length mode_LSB = ( reference << 7 ) + ( 0b0 << 6 ) + ( input_range << 4 ) + ( clock_enable << 3 ) + ( burn_out << 2 ) + channel self . single_write ( self . AD7730_MODE_REG , [ mode_MSB , mode_LSB ] )
def _get_entry_link ( self , entry ) : """Returns a unique link for an entry"""
entry_link = None for link in entry . link : if '/data/' not in link . href and '/lh/' not in link . href : entry_link = link . href break return entry_link or entry . link [ 0 ] . href
def add_attrs ( self , symbol , ** kwargs ) : """Helper for setting symbol extension attributes"""
for key , val in kwargs . items ( ) : symbol . add_extension_attribute ( self . extension_name , key , val )
def process_read_exception ( exc , path , ignore = None ) : '''Common code for raising exceptions when reading a file fails The ignore argument can be an iterable of integer error codes ( or a single integer error code ) that should be ignored .'''
if ignore is not None : if isinstance ( ignore , six . integer_types ) : ignore = ( ignore , ) else : ignore = ( ) if exc . errno in ignore : return if exc . errno == errno . ENOENT : raise CommandExecutionError ( '{0} does not exist' . format ( path ) ) elif exc . errno == errno . EACCES : ...
def process_notice ( self , notice ) : """This method is called on notices that need processing . Here , we call ` ` on _ object ` ` and ` ` on _ account ` ` slots ."""
id = notice [ "id" ] _a , _b , _ = id . split ( "." ) if id in self . subscription_objects : self . on_object ( notice ) elif "." . join ( [ _a , _b , "x" ] ) in self . subscription_objects : self . on_object ( notice ) elif id [ : 4 ] == "2.6." : # Treat account updates separately self . on_account ( notic...
def tfidf_corpus ( docs = CORPUS ) : """Count the words in a corpus and return a TfidfVectorizer ( ) as well as all the TFIDF vecgtors for the corpus Args : docs ( iterable of strs ) : a sequence of documents ( strings ) Returns : ( TfidfVectorizer , tfidf _ vectors )"""
vectorizer = TfidfVectorizer ( ) vectorizer = vectorizer . fit ( docs ) return vectorizer , vectorizer . transform ( docs )
def popone ( self , key , * default ) : """Remove first of given key and return corresponding value . If key is not found , default is returned if given . > > > m = MutableMultiMap ( [ ( ' a ' , 1 ) , ( ' b ' , 2 ) , ( ' b ' , 3 ) , ( ' c ' , 4 ) ] ) > > > m . popone ( ' b ' ) > > > m . items ( ) [ ( ' a ...
try : value = self [ key ] except KeyError : if default : return default [ 0 ] raise # Delete this one . self . _remove_pairs ( [ self . _key_ids [ self . _conform_key ( key ) ] . pop ( 0 ) ] ) return value
def extract_listing ( pid ) : """Extract listing ; return list of tuples ( artist ( s ) , title , label ) ."""
print ( "Extracting tracklisting..." ) listing_etree = open_listing_page ( pid + '/segments.inc' ) track_divs = listing_etree . xpath ( '//div[@class="segment__track"]' ) listing = [ ] for track_div in track_divs : try : artist_names = track_div . xpath ( './/span[@property="byArtist"]' '//span[@class="arti...
def get_poll_options ( tweet ) : """Get the text in the options of a poll as a list - If there is no poll in the Tweet , return an empty list - If the Tweet is in activity - streams format , raise ' NotAvailableError ' Args : tweet ( Tweet or dict ) : A Tweet object or dictionary Returns : list : list o...
if is_original_format ( tweet ) : try : poll_options_text = [ ] for p in tweet [ "entities" ] [ "polls" ] : for o in p [ "options" ] : poll_options_text . append ( o [ "text" ] ) return poll_options_text except KeyError : return [ ] else : raise No...
def delete ( self , tname , where = None , where_not = None , columns = None , astype = None ) : '''Delete records from the provided table . Parameters , matching and output are identical to ` find ( ) ` . Parameters tname : str Table to delete records from . where : dict or None ( default ` None ` ) Di...
tname = self . _check_tname ( tname ) where = PandasDatabase . _check_conditions ( where ) where_not = PandasDatabase . _check_conditions ( where_not ) columns = PandasDatabase . _check_type_iter ( str , columns ) # Find the rows to be deleted delrows = self . find ( tname , where = where , where_not = where_not , asty...
def retry ( retry_count ) : """Retry decorator used during file upload and download ."""
def func ( f ) : @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : for backoff in range ( retry_count ) : try : return f ( * args , ** kwargs ) except Exception : time . sleep ( 2 ** backoff ) else : raise SbgError ...
def raw ( key = None ) : '''Return the raw pillar data that is available in the module . This will show the pillar as it is loaded as the _ _ pillar _ _ dict . CLI Example : . . code - block : : bash salt ' * ' pillar . raw With the optional key argument , you can select a subtree of the pillar raw data...
if key : ret = __pillar__ . get ( key , { } ) else : ret = __pillar__ return ret
def export ( self , top = True ) : """Exports object to its string representation . Args : top ( bool ) : if True appends ` internal _ name ` before values . All non list objects should be exported with value top = True , all list objects , that are embedded in as fields inlist objects should be exported ...
out = [ ] if top : out . append ( self . _internal_name ) out . append ( self . _to_str ( self . number_of_records_per_hour ) ) out . append ( self . _to_str ( self . data_period_name_or_description ) ) out . append ( self . _to_str ( self . data_period_start_day_of_week ) ) out . append ( self . _to_str ( self . d...
def tocimxml ( self , ignore_host = False , ignore_namespace = False ) : """Return the CIM - XML representation of this CIM instance path , as an object of an appropriate subclass of : term : ` Element ` . If the instance path has no namespace specified or if ` ignore _ namespace ` is ` True ` , the returned ...
kbs = [ ] # We no longer check that the keybindings is a NocaseDict because we # ensure that in the keybindings ( ) property setter method . for key , value in self . keybindings . items ( ) : # Keybindings can be integers , booleans , strings or references . # References can only by instance names . if isinstance ...
def parse_django_adminopt_node ( env , sig , signode ) : """A copy of sphinx . directives . CmdoptionDesc . parse _ signature ( )"""
from sphinx . domains . std import option_desc_re count = 0 firstname = '' for m in option_desc_re . finditer ( sig ) : optname , args = m . groups ( ) if count : signode += addnodes . desc_addname ( ', ' , ', ' ) signode += addnodes . desc_name ( optname , optname ) signode += addnodes . desc_a...
def iter_file_commands ( self ) : """Iterator returning FileCommand objects . If an invalid file command is found , the line is silently pushed back and iteration ends ."""
while True : line = self . next_line ( ) if line is None : break elif len ( line ) == 0 or line . startswith ( b'#' ) : continue # Search for file commands in order of likelihood elif line . startswith ( b'M ' ) : yield self . _parse_file_modify ( line [ 2 : ] ) elif line...
def log ( ctx , archive_name ) : '''Get the version log for an archive'''
_generate_api ( ctx ) ctx . obj . api . get_archive ( archive_name ) . log ( )
def interpolate_timestamp ( capture_times ) : '''Interpolate time stamps in case of identical timestamps'''
timestamps = [ ] num_file = len ( capture_times ) time_dict = OrderedDict ( ) if num_file < 2 : return capture_times # trace identical timestamps ( always assume capture _ times is sorted ) time_dict = OrderedDict ( ) for i , t in enumerate ( capture_times ) : if t not in time_dict : time_dict [ t ] = {...
def _pcolormesh_array2d ( self , array , * args , ** kwargs ) : """Render an ` ~ gwpy . types . Array2D ` using ` Axes . pcolormesh `"""
x = numpy . concatenate ( ( array . xindex . value , array . xspan [ - 1 : ] ) ) y = numpy . concatenate ( ( array . yindex . value , array . yspan [ - 1 : ] ) ) xcoord , ycoord = numpy . meshgrid ( x , y , copy = False , sparse = True ) return self . pcolormesh ( xcoord , ycoord , array . value . T , * args , ** kwarg...
def _build_params ( self ) : '''método que constrói o dicionario com os parametros que serão usados na requisição HTTP Post ao PagSeguro Returns : Um dicionário com os parametros definidos no objeto Payment .'''
params = { } params [ 'email' ] = self . email params [ 'token' ] = self . token params [ 'currency' ] = self . currency # Atributos opcionais if self . receiver_email : params [ 'receiver_email' ] = self . receiver_email if self . reference : params [ 'reference' ] = self . reference if self . extra_amount : ...
def init ( project_name ) : """build a minimal flask project"""
# the destination path dst_path = os . path . join ( os . getcwd ( ) , project_name ) start_init_info ( dst_path ) # create dst path _mkdir_p ( dst_path ) os . chdir ( dst_path ) # create files init_code ( 'manage.py' , _manage_basic_code ) init_code ( 'requirement.txt' , _requirement_code ) # create app / app_path = o...
def hscan ( self , name , cursor = 0 , match = None , count = None ) : """Incrementally return key / value slices in a hash . Also return a cursor indicating the scan position . ` ` match ` ` allows for filtering the keys by pattern ` ` count ` ` allows for hint the minimum number of returns"""
with self . pipe as pipe : f = Future ( ) res = pipe . hscan ( self . redis_key ( name ) , cursor = cursor , match = match , count = count ) def cb ( ) : data = { } m_decode = self . memberparse . decode for k , v in res [ 1 ] . items ( ) : k = m_decode ( k ) ...
def get_staking_cutoff ( self , round_num = 0 , tournament = 1 ) : """Compute staking cutoff for the given round and tournament . Args : round _ num ( int , optional ) : The round you are interested in , defaults to current round . tournament ( int , optional ) : ID of the tournament , defaults to 1 Retur...
query = ''' query($number: Int! $tournament: Int!) { rounds(number: $number tournament: $tournament) { selection { outcome pCutoff bCutoff } } ...
def run ( self , args ) : """Generate dummy strings for all source po files ."""
configuration = self . configuration source_messages_dir = configuration . source_messages_dir for locale , converter in zip ( configuration . dummy_locales , [ Dummy ( ) , Dummy2 ( ) , ArabicDummy ( ) ] ) : print ( 'Processing source language files into dummy strings, locale "{}"' . format ( locale ) ) for sou...
def GpuUsage ( ** kargs ) : """Get the current GPU usage of available GPUs"""
usage = ( False , None ) gpu_status = { 'vent_usage' : { 'dedicated' : [ ] , 'mem_mb' : { } } } path_dirs = PathDirs ( ** kargs ) path_dirs . host_config ( ) template = Template ( template = path_dirs . cfg_file ) # get running jobs using gpus try : d_client = docker . from_env ( ) c = d_client . containers . l...
def web_err ( i ) : """Input : { http - http object type - content type bin - bytes to output Output : { return - 0"""
http = i [ 'http' ] tp = i [ 'type' ] bin = i [ 'bin' ] try : bin = bin . decode ( 'utf-8' ) except Exception as e : pass if tp == 'json' : rx = ck . dumps_json ( { 'dict' : { 'return' : 1 , 'error' : bin } } ) if rx [ 'return' ] > 0 : bin2 = rx [ 'error' ] . encode ( 'utf8' ) else : ...
def response ( code , ** kwargs ) : """Generic HTTP JSON response method : param code : HTTP code ( int ) : param kwargs : Data structure for response ( dict ) : return : HTTP Json response"""
_ret_json = jsonify ( kwargs ) resp = make_response ( _ret_json , code ) resp . headers [ "Content-Type" ] = "application/json; charset=utf-8" return resp
def commit_and_run ( self , commit , conf , command = "sh" ) : """Commit this container id and run the provided command in it and clean up afterwards"""
image_hash = None try : image_hash = conf . harpoon . docker_api . commit ( commit ) [ "Id" ] new_conf = conf . clone ( ) new_conf . bash = NotSpecified new_conf . command = command new_conf . image_name = image_hash new_conf . container_id = None new_conf . container_name = "{0}-interventio...
def admin_url ( model , url , object_id = None ) : """Returns the URL for the given model and admin url name ."""
opts = model . _meta url = "admin:%s_%s_%s" % ( opts . app_label , opts . object_name . lower ( ) , url ) args = ( ) if object_id is not None : args = ( object_id , ) return reverse ( url , args = args )
def on_task ( self , task , response ) : '''Deal one task'''
start_time = time . time ( ) response = rebuild_response ( response ) try : assert 'taskid' in task , 'need taskid in task' project = task [ 'project' ] updatetime = task . get ( 'project_updatetime' , None ) md5sum = task . get ( 'project_md5sum' , None ) project_data = self . project_manager . get...
def _request_process_json_bulk ( self , response_data ) : """Handle bulk JSON response Return : ( string ) : The response data ( string ) : The response status"""
status = 'Failure' data = response_data . get ( self . request_entity , [ ] ) if data : status = 'Success' return data , status
def import_cluster_template ( self , api_cluster_template , add_repositories = False ) : """Create a cluster according to the provided template @ param api _ cluster _ template : cluster template to import @ param add _ repositories : if true the parcels repositories in the cluster template will be added . @ ...
return self . _post ( "importClusterTemplate" , ApiCommand , False , api_cluster_template , params = dict ( addRepositories = add_repositories ) , api_version = 12 )
def aggr ( array , op , initial_value , ty ) : """Computes the aggregate of elements in the array . Args : array ( WeldObject / Numpy . ndarray ) : Input array to aggregate op ( str ) : Op string used to aggregate the array ( + / * ) initial _ value ( int ) : Initial value for aggregation ty ( WeldType ) ...
weld_obj = WeldObject ( encoder_ , decoder_ ) array_var = weld_obj . update ( array ) if isinstance ( array , WeldObject ) : array_var = array . obj_id weld_obj . dependencies [ array_var ] = array weld_template = """ result( for( %(array)s, merger[%(ty)s,%(op)s], |b,...
def list_market_profit_and_loss ( self , market_ids , include_settled_bets = None , include_bsp_bets = None , net_of_commission = None , session = None , lightweight = None ) : """Retrieve profit and loss for a given list of OPEN markets . : param list market _ ids : List of markets to calculate profit and loss ...
params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'listMarketProfitAndLoss' ) ( response , elapsed_time ) = self . request ( method , params , session ) return self . process_response ( response , resources . MarketProfitLoss , elapsed_time , lightweight )
def update_payload ( self , fields = None ) : """Rename ` ` system _ ids ` ` to ` ` system _ uuids ` ` ."""
payload = super ( HostCollection , self ) . update_payload ( fields ) if 'system_ids' in payload : payload [ 'system_uuids' ] = payload . pop ( 'system_ids' ) return payload
def component_title ( component ) : """Label , title and caption Title is the label text plus the title text Title may contain italic tag , etc ."""
title = u'' label_text = u'' title_text = u'' if component . get ( 'label' ) : label_text = component . get ( 'label' ) if component . get ( 'title' ) : title_text = component . get ( 'title' ) title = unicode_value ( label_text ) if label_text != '' and title_text != '' : title += ' ' title += unicode_valu...
def winnow_by_keys ( dct , keys = None , filter_func = None ) : """separates a dict into has - keys and not - has - keys pairs , using either a list of keys or a filtering function ."""
has = { } has_not = { } for key in dct : key_passes_check = False if keys is not None : key_passes_check = key in keys elif filter_func is not None : key_passes_check = filter_func ( key ) if key_passes_check : has [ key ] = dct [ key ] else : has_not [ key ] = dct [ ...
def list ( self , networkipv4 = None , ipv4 = None ) : """List all DHCPRelayIPv4. : param : networkipv4 : networkipv4 id - list all dhcprelay filtering by networkipv4 id ipv4 : ipv4 id - list all dhcprelay filtering by ipv4 id : return : Following dictionary : " networkipv4 " : < networkipv4 _ id > , " id...
uri = 'api/dhcprelayv4/?' if networkipv4 : uri += 'networkipv4=%s&' % networkipv4 if ipv4 : uri += 'ipv4=%s' % ipv4 return self . get ( uri )
def delete_queue ( queues ) : """Delete the given queues ."""
current_queues . delete ( queues = queues ) click . secho ( 'Queues {} have been deleted.' . format ( queues or current_queues . queues . keys ( ) ) , fg = 'green' )
def validate ( self , instance , value ) : # pylint : disable = inconsistent - return - statements """Check if input is a valid string based on the choices"""
if not isinstance ( value , string_types ) : self . error ( instance , value ) for key , val in self . choices . items ( ) : test_value = value if self . case_sensitive else value . upper ( ) test_key = key if self . case_sensitive else key . upper ( ) test_val = val if self . case_sensitive else [ _ . ...
def get_area ( self ) : """Compute area as the sum of the mesh cells area values ."""
mesh = self . mesh _ , _ , _ , area = mesh . get_cell_dimensions ( ) return numpy . sum ( area )
def encode ( g , top = None , cls = PENMANCodec , ** kwargs ) : """Serialize the graph * g * from * top * to PENMAN notation . Args : g : the Graph object top : the node identifier for the top of the serialized graph ; if unset , the original top of * g * is used cls : serialization codec class kwargs :...
codec = cls ( ** kwargs ) return codec . encode ( g , top = top )
def remove_renderer ( self , rend ) : '''Remove a renderer from the current view . * * Example * * rend = v . add _ renderer ( AtomRenderer ) v . remove _ renderer ( rend ) . . versionadded : : 0.3'''
if rend in self . widget . renderers : self . widget . renderers . remove ( rend ) else : raise Exception ( "The renderer is not in this viewer" )
def _find_caller ( self ) : """Find the stack frame of the caller so that we can note the source file name , line number , and function name ."""
rv = ( '(unknown file)' , 0 , '(unknown function)' , '(code not available)' , [ ] , None ) f = inspect . currentframe ( ) while hasattr ( f , 'f_code' ) : co = f . f_code filename = os . path . normcase ( co . co_filename ) # When lggr is imported as a module , the ` _ src _ file ` filename ends # in ' ...
def place ( vertices_resources , nets , machine , constraints ) : """Assigns vertices to chips in Reverse - Cuthill - McKee ( RCM ) order . The ` RCM < https : / / en . wikipedia . org / wiki / Cuthill % E2%80%93McKee _ algorithm > ` _ algorithm ( in graph - centric terms ) is a simple breadth - first - search ...
return sequential_place ( vertices_resources , nets , machine , constraints , rcm_vertex_order ( vertices_resources , nets ) , rcm_chip_order ( machine ) )
def _fix_valid_indices ( cls , valid_indices , insertion_index , dim ) : """Add indices for H & S inserted elements ."""
# TODO : make this accept an immutable sequence for valid _ indices # ( a tuple ) and return an immutable sequence rather than mutating an # argument . indices = np . array ( sorted ( valid_indices [ dim ] ) ) slice_index = np . sum ( indices <= insertion_index ) indices [ slice_index : ] += 1 indices = np . insert ( i...
def parse_line ( self , text , fh = None ) : """Parse a line into whatever TAP category it belongs ."""
match = self . ok . match ( text ) if match : return self . _parse_result ( True , match , fh ) match = self . not_ok . match ( text ) if match : return self . _parse_result ( False , match , fh ) if self . diagnostic . match ( text ) : return Diagnostic ( text ) match = self . plan . match ( text ) if matc...
def normalize_data_values ( type_string , data_value ) : """Decodes utf - 8 bytes to strings for abi string values . eth - abi v1 returns utf - 8 bytes for string values . This can be removed once eth - abi v2 is required ."""
_type = parse_type_string ( type_string ) if _type . base == "string" : if _type . arrlist is not None : return tuple ( ( normalize_to_text ( value ) for value in data_value ) ) else : return normalize_to_text ( data_value ) return data_value
def list_worksheets ( self ) : """List what worksheet keys exist Returns a list of tuples of the form : ( WORKSHEET _ ID , WORKSHEET _ NAME ) You can then retrieve the specific WORKSHEET _ ID in the future by constructing a new GSpreadsheet ( worksheet = WORKSHEET _ ID , . . . )"""
worksheets = self . get_worksheets ( ) return [ ( x . link [ 3 ] . href . split ( '/' ) [ - 1 ] , x . title . text ) for x in worksheets . entry ]
def remove ( self , address ) : """Remove an address or multiple addresses : param address : list of addresses to remove : type address : str or list [ str ]"""
recipients = [ ] if isinstance ( address , str ) : address = { address } # set elif isinstance ( address , ( list , tuple ) ) : address = set ( address ) for recipient in self . _recipients : if recipient . address not in address : recipients . append ( recipient ) if len ( recipients ) != len (...
def adjust_level ( logger , level ) : """Increase a logger ' s verbosity up to the requested level . : param logger : The logger to change ( a : class : ` ~ logging . Logger ` object ) . : param level : The log level to enable ( a string or number ) . This function is used by functions like : func : ` install...
level = level_to_number ( level ) if logger . getEffectiveLevel ( ) > level : logger . setLevel ( level )
def fetch ( bank , key ) : '''Fetch a key value .'''
_init_client ( ) query = "SELECT data FROM {0} WHERE bank='{1}' AND etcd_key='{2}'" . format ( _table_name , bank , key ) cur , _ = run_query ( client , query ) r = cur . fetchone ( ) cur . close ( ) if r is None : return { } return __context__ [ 'serial' ] . loads ( r [ 0 ] )
def previous_theme ( self ) : """Cycle to preview the previous theme from the internal list of themes ."""
theme = self . term . theme_list . previous ( self . term . theme ) while not self . term . check_theme ( theme ) : theme = self . term . theme_list . previous ( theme ) self . term . set_theme ( theme ) self . draw ( ) message = self . term . theme . display_string self . term . show_notification ( message , timeo...
def discover_and_apply ( self , directory = None , dry_run = False ) : """Retrieve the patches and try to apply them against the datamodel : param directory : Directory to search the patch in ( default : patches _ dir ) : param dry _ run : Don ' t actually apply the patches"""
directory = directory or self . patches_dir patches_dict = { p . base_version : p for p in self . discover ( directory ) } current_version = self . manifest . version if not patches_dict . get ( current_version ) : print ( 'No patch to apply' ) return if dry_run : msg = 'Datamodel should be in version %s !'...
def _load_from_file ( metadata , load_func ) : """Load configuration from a file . The file path is derived from an environment variable named after the service of the form FOO _ SETTINGS ."""
config_filename = get_config_filename ( metadata ) if config_filename is None : return dict ( ) with open ( config_filename , "r" ) as file_ : data = load_func ( file_ . read ( ) ) return dict ( data )
def format_row ( self , row , key , color ) : """For a given row from the table , format it ( i . e . floating points and color if applicable ) ."""
value = row [ key ] if isinstance ( value , bool ) or value is None : return '+' if value else '' if not isinstance ( value , Number ) : return value # determine if integer value is_integer = float ( value ) . is_integer ( ) template = '{}' if is_integer else '{:' + self . floatfmt + '}' # if numeric , there co...
def _is_ipv4 ( self , ip ) : """Return true if given arg is a valid IPv4 address"""
try : p = IPy . IP ( ip ) except ValueError : return False if p . version ( ) == 4 : return True return False
def get_version ( self ) : """Get game version ."""
return mgz . const . VERSIONS [ self . _header . version ] , str ( self . _header . sub_version ) [ : 5 ]
def _fromJSON ( cls , jsonobject ) : """Generates a new instance of : class : ` maspy . core . Ci ` from a decoded JSON object ( as generated by : func : ` maspy . core . Ci . _ reprJSON ( ) ` ) . : param jsonobject : decoded JSON object : returns : a new instance of : class : ` Ci `"""
newInstance = cls ( jsonobject [ 0 ] , jsonobject [ 1 ] ) attribDict = { } attribDict [ 'dataProcessingRef' ] = jsonobject [ 2 ] attribDict [ 'precursor' ] = jsonobject [ 3 ] attribDict [ 'product' ] = jsonobject [ 4 ] attribDict [ 'params' ] = [ tuple ( param ) for param in jsonobject [ 5 ] ] attribDict [ 'attrib' ] =...
def runlist_create ( name , ** kwargs ) : """Create runlist and upload it into the storage ."""
ctx = Context ( ** kwargs ) ctx . execute_action ( 'runlist:create' , ** { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , 'name' : name , } )
def verify_predictions ( predictions ) : """Ensures that predictions is stored as a numpy array and checks that all values are either 0 or 1."""
# Check that it contains only zeros and ones predictions = np . array ( predictions , copy = False ) if not np . array_equal ( predictions , predictions . astype ( bool ) ) : raise ValueError ( "predictions contains invalid values. " + "The only permitted values are 0 or 1." ) if predictions . ndim == 1 : predi...
def _interactive_input_tensor_to_features_dict ( feature_map , hparams ) : """Convert the interactive input format ( see above ) to a dictionary . Args : feature _ map : dict with inputs . hparams : model hyperparameters Returns : a features dictionary , as expected by the decoder ."""
inputs = tf . convert_to_tensor ( feature_map [ "inputs" ] ) input_is_image = False if len ( inputs . get_shape ( ) ) < 3 else True x = inputs if input_is_image : x = tf . image . resize_images ( x , [ 299 , 299 ] ) x = tf . reshape ( x , [ 1 , 299 , 299 , - 1 ] ) x = tf . to_int32 ( x ) else : # Remove the...
def set_default_value ( self , data_id , value = EMPTY , initial_dist = 0.0 ) : """Set the default value of a data node in the dispatcher . : param data _ id : Data node id . : type data _ id : str : param value : Data node default value . . . note : : If ` EMPTY ` the previous default value is removed ...
self . deferred . append ( ( 'set_default_value' , _call_kw ( locals ( ) ) ) ) return self
def Animation_seekAnimations ( self , animations , currentTime ) : """Function path : Animation . seekAnimations Domain : Animation Method name : seekAnimations Parameters : Required arguments : ' animations ' ( type : array ) - > List of animation ids to seek . ' currentTime ' ( type : number ) - > Set...
assert isinstance ( animations , ( list , tuple ) ) , "Argument 'animations' must be of type '['list', 'tuple']'. Received type: '%s'" % type ( animations ) assert isinstance ( currentTime , ( float , int ) ) , "Argument 'currentTime' must be of type '['float', 'int']'. Received type: '%s'" % type ( currentTime ) subdo...
def reduce ( fname , reduction_factor ) : """Produce a submodel from ` fname ` by sampling the nodes randomly . Supports source models , site models and exposure models . As a special case , it is also able to reduce . csv files by sampling the lines . This is a debugging utility to reduce large computations ...
if fname . endswith ( '.csv' ) : with open ( fname ) as f : line = f . readline ( ) # read the first line if csv . Sniffer ( ) . has_header ( line ) : header = line all_lines = f . readlines ( ) else : header = None f . seek ( 0 ) ...
def check_connection ( self ) : """Try to open the local file . Under NT systems the case sensitivity is checked ."""
if ( self . parent_url is not None and not self . parent_url . startswith ( u"file:" ) ) : msg = _ ( "local files are only checked without parent URL or when the parent URL is also a file" ) raise LinkCheckerError ( msg ) if self . is_directory ( ) : self . set_result ( _ ( "directory" ) ) else : url = ...
def list ( self , ** params ) : """Retrieve all sources Returns all deal sources available to the user according to the parameters provided : calls : ` ` get / deal _ sources ` ` : param dict params : ( optional ) Search options . : return : List of dictionaries that support attriubte - style access , which...
_ , _ , deal_sources = self . http_client . get ( "/deal_sources" , params = params ) return deal_sources
def pprint ( obj , file_ = None ) : """Prints debug information for various public objects like methods , functions , constructors etc ."""
if file_ is None : file_ = sys . stdout # functions , methods if callable ( obj ) and hasattr ( obj , "_code" ) : obj . _code . pprint ( file_ ) return # classes if isinstance ( obj , type ) and hasattr ( obj , "_constructors" ) : constructors = obj . _constructors for names , func in sorted ( const...
def get_variant ( self , index = None ) : """Get the variant with the associated index . Returns : ` Variant ` object , or None if no variant with the given index exists ."""
for variant in self . iter_variants ( ) : if variant . index == index : return variant
def as_dictionary ( self , is_proof = True ) : """Return the DDO as a JSON dict . : param if is _ proof : if False then do not include the ' proof ' element . : return : dict"""
if self . _created is None : self . _created = DDO . _get_timestamp ( ) data = { '@context' : DID_DDO_CONTEXT_URL , 'id' : self . _did , 'created' : self . _created , } if self . _public_keys : values = [ ] for public_key in self . _public_keys : values . append ( public_key . as_dictionary ( ) ) ...
def create_or_update_alarm ( connection = None , name = None , metric = None , namespace = None , statistic = None , comparison = None , threshold = None , period = None , evaluation_periods = None , unit = None , description = '' , dimensions = None , alarm_actions = None , insufficient_data_actions = None , ok_action...
# clean up argument types , so that CLI works if threshold : threshold = float ( threshold ) if period : period = int ( period ) if evaluation_periods : evaluation_periods = int ( evaluation_periods ) if isinstance ( dimensions , six . string_types ) : dimensions = salt . utils . json . loads ( dimensio...
def keys ( self ) -> Iterator [ str ] : """return all possible paths one can take from this ApiNode"""
if self . param : yield self . param_name yield from self . paths . keys ( )
def create ( type_dict , * type_parameters ) : """StructFactory . create ( * type _ parameters ) expects : class name , ( ( binding requirement1 , ) , ( binding requirement2 , bound _ to _ scope ) , ( ( attribute _ name1 , attribute _ sig1 ( serialized ) ) , ( attribute _ name2 , attribute _ sig2 . . . ) ...
name , parameters = type_parameters for param in parameters : assert isinstance ( param , tuple ) typemap = dict ( ( attr , TypeSignature . deserialize ( param , type_dict ) ) for attr , param in parameters ) attributes = { 'TYPEMAP' : typemap } return TypeMetaclass ( str ( name ) , ( Structural , ) , attributes )
def insert_draft_child ( self , child_pid ) : """Insert a draft child to versioning ."""
if child_pid . status != PIDStatus . RESERVED : raise PIDRelationConsistencyError ( "Draft child should have status 'RESERVED'" ) if not self . draft_child : with db . session . begin_nested ( ) : super ( PIDNodeVersioning , self ) . insert_child ( child_pid , index = - 1 ) else : raise PIDRelationC...
def validate_and_discover ( self , context ) : """: type context : models . QualiDriverModels . AutoLoadCommandContext"""
logger = self . _get_logger ( context ) logger . info ( 'Autodiscovery started' ) si = None resource = None with CloudShellSessionContext ( context ) as cloudshell_session : self . _check_if_attribute_not_empty ( context . resource , ADDRESS ) resource = context . resource si = self . _check_if_vcenter_user...
def get_axes_ratio ( ax ) : """Return height / width ratio of the given Axes object . The ratio is calculated in ' display coordinate ' , defined in matplotlib document on transformation . Thus , the calculated ratio is what one would feels when the Axes is displayed to the her / him ."""
ax_bbox_points_in_fig_coord = ax . get_position ( ) . get_points ( ) ax_bbox_points_in_display_coord = [ ax . figure . transFigure . transform ( point ) for point in ax_bbox_points_in_fig_coord ] lower_left_coord , upper_right_coord = ax_bbox_points_in_display_coord ax_bbox_dimension_in_display_coord = upper_right_coor...
def _makeApiCall ( self , entry , * args , ** kwargs ) : """This function is used to dispatch calls to other functions for a given API Reference entry"""
x = self . _processArgs ( entry , * args , ** kwargs ) routeParams , payload , query , paginationHandler , paginationLimit = x route = self . _subArgsInRoute ( entry , routeParams ) # TODO : Check for limit being in the Query of the api ref if paginationLimit and 'limit' in entry . get ( 'query' , [ ] ) : query [ '...
def binormal_curve_single ( obj , u , normalize ) : """Evaluates the curve binormal vector at the given u parameter . Curve binormal is the cross product of the normal and the tangent vectors . The output returns a list containing the starting point ( i . e . origin ) of the vector and the vector itself . : p...
# Cross product of tangent and normal vectors gives binormal vector tan_vector = tangent_curve_single ( obj , u , normalize ) norm_vector = normal_curve_single ( obj , u , normalize ) point = tan_vector [ 0 ] vector = linalg . vector_cross ( tan_vector [ 1 ] , norm_vector [ 1 ] ) vector = linalg . vector_normalize ( ve...
def _updateCallSetIds ( self , variantFile ) : """Updates the call set IDs based on the specified variant file ."""
if len ( self . _callSetIdMap ) == 0 : for sample in variantFile . header . samples : self . addCallSetFromName ( sample )
def __get_user_env_vars ( self ) : """Return the user defined environment variables"""
return ( os . environ . get ( self . GP_URL_ENV_VAR ) , os . environ . get ( self . GP_INSTANCE_ID_ENV_VAR ) , os . environ . get ( self . GP_USER_ID_ENV_VAR ) , os . environ . get ( self . GP_PASSWORD_ENV_VAR ) , os . environ . get ( self . GP_IAM_API_KEY_ENV_VAR ) )
def adjust_bounding_box ( bounds1 , bounds2 ) : """If the bounds 2 corners are outside of bounds1 , they will be adjusted to bounds1 corners @ params bounds1 - The source bounding box bounds2 - The target bounding box that has to be within bounds1 @ return A bounding box tuple in ( y1 , x1 , y2 , x2 ) for...
# out of bound check # If it is completely outside of target bounds , return target bounds if ( ( bounds2 [ 0 ] > bounds1 [ 0 ] and bounds2 [ 2 ] > bounds1 [ 0 ] ) or ( bounds2 [ 2 ] < bounds1 [ 2 ] and bounds2 [ 2 ] < bounds1 [ 0 ] ) ) : return bounds1 if ( ( bounds2 [ 1 ] < bounds1 [ 1 ] and bounds2 [ 3 ] < bound...
def exception_format ( ) : """Convert exception info into a string suitable for display ."""
return "" . join ( traceback . format_exception ( sys . exc_info ( ) [ 0 ] , sys . exc_info ( ) [ 1 ] , sys . exc_info ( ) [ 2 ] ) )
def _preferredThemes ( self ) : """Return a list of themes in the order of preference that this user has selected via L { PrivateApplication . preferredTheme } ."""
themes = getInstalledThemes ( self . store . parent ) _reorderForPreference ( themes , self . preferredTheme ) return themes
def dummy_func ( arg1 , arg2 , arg3 = None , arg4 = [ 1 , 2 , 3 ] , arg5 = { } , ** kwargs ) : """test func for kwargs parseing"""
foo = kwargs . get ( 'foo' , None ) bar = kwargs . pop ( 'bar' , 4 ) foo2 = kwargs [ 'foo2' ] foobar = str ( foo ) + str ( bar ) + str ( foo2 ) return foobar
def _create_connection ( self ) : """Creates a transport channel . : return : transport channel instance : rtype : : class : ` fatbotslim . irc . tcp . TCP ` or : class : ` fatbotslim . irc . tcp . SSL `"""
transport = SSL if self . ssl else TCP return transport ( self . server , self . port )
def create ( self , card_data ) : """创建卡券 : param card _ data : 卡券信息 : return : 创建的卡券 ID"""
result = self . _post ( 'card/create' , data = card_data , result_processor = lambda x : x [ 'card_id' ] ) return result
def compare_params ( defined , existing , return_old_value = False ) : '''. . versionadded : : 2017.7 Compares Zabbix object definition against existing Zabbix object . : param defined : Zabbix object definition taken from sls file . : param existing : Existing Zabbix object taken from result of an API call ....
# Comparison of data types if not isinstance ( defined , type ( existing ) ) : raise SaltException ( 'Zabbix object comparison failed (data type mismatch). Expecting {0}, got {1}. ' 'Existing value: "{2}", defined value: "{3}").' . format ( type ( existing ) , type ( defined ) , existing , defined ) ) # Comparison ...
def parse_value_refarray ( self , tup_tree ) : """Parse a VALUE . REFARRAY element and return the array of instance paths or class paths it represents as a list of CIMInstanceName or CIMClassName objects , respectively . < ! ELEMENT VALUE . REFARRAY ( VALUE . REFERENCE | VALUE . NULL ) * >"""
self . check_node ( tup_tree , 'VALUE.REFARRAY' ) children = self . list_of_various ( tup_tree , ( 'VALUE.REFERENCE' , 'VALUE.NULL' ) ) return children
def load_from_filename ( self , file_name , sep = '\n' ) : """Utility function to load messages from a local filename to a queue"""
fp = open ( file_name , 'rb' ) n = self . load_from_file ( fp , sep ) fp . close ( ) return n
def visit_grouping ( self , grouping , asfrom = False , ** kwargs ) : """TODO :"""
return { 'type' : 'grouping' , 'grouping' : grouping . element . _compiler_dispatch ( self , ** kwargs ) }
def local_position_ned_encode ( self , time_boot_ms , x , y , z , vx , vy , vz ) : '''The filtered local position ( e . g . fused computer vision and accelerometers ) . Coordinate frame is right - handed , Z - axis down ( aeronautical frame , NED / north - east - down convention ) time _ boot _ ms : Timesta...
return MAVLink_local_position_ned_message ( time_boot_ms , x , y , z , vx , vy , vz )
def hex_to_rgb ( hex_value ) : """Convert a hexadecimal color value to a 3 - tuple of integers suitable for use in an ` ` rgb ( ) ` ` triplet specifying that color . The hexadecimal value will be normalized before being converted . Examples : > > > hex _ to _ rgb ( ' # fff ' ) (255 , 255 , 255) > > > he...
hex_digits = normalize_hex ( hex_value ) return tuple ( [ int ( s , 16 ) for s in ( hex_digits [ 1 : 3 ] , hex_digits [ 3 : 5 ] , hex_digits [ 5 : 7 ] ) ] )
def conn_options ( prs , conn ) : """Set options of connecting to TonicDNS API server Arguments : prs : parser object of argparse conn : dictionary of connection information"""
if conn . get ( 'server' ) and conn . get ( 'username' ) and conn . get ( 'password' ) : prs . set_defaults ( server = conn . get ( 'server' ) , username = conn . get ( 'username' ) , password = conn . get ( 'password' ) ) elif conn . get ( 'server' ) and conn . get ( 'username' ) : prs . set_defaults ( server ...