signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def string_to_datetime ( date ) : """Return a datetime . datetime instance with tzinfo . I . e . a timezone aware datetime instance . Acceptable formats for input are : * 2012-01-10T12:13:14 * 2012-01-10T12:13:14.98765 * 2012-01-10T12:13:14.98765 + 03:00 * 2012-01-10T12:13:14.98765Z * 2012-01-10 12:13...
if date is None : return None if isinstance ( date , datetime . datetime ) : if not date . tzinfo : date = date . replace ( tzinfo = UTC ) return date if isinstance ( date , list ) : date = 'T' . join ( date ) if isinstance ( date , basestring ) : if len ( date ) <= len ( '2000-01-01' ) : ...
def write ( self , msg ) : """Writes msg to the current output stream ( either standard out or dev / null ) . If a log has been registered , append msg to the log . PARAMTERS : msg - - str"""
self . _current_stream . write ( msg ) for log in self . _logs . values ( ) : log . append ( msg )
def transparency ( self ) : """Does the current object contain any transparency . Returns transparency : bool , does the current visual contain transparency"""
if 'vertex_colors' in self . _data : a_min = self . _data [ 'vertex_colors' ] [ : , 3 ] . min ( ) elif 'face_colors' in self . _data : a_min = self . _data [ 'face_colors' ] [ : , 3 ] . min ( ) else : return False return bool ( a_min < 255 )
def _cache_provider_details ( conn = None ) : '''Provide a place to hang onto results of - - list - [ locations | sizes | images ] so we don ' t have to go out to the API and get them every time .'''
DETAILS [ 'avail_locations' ] = { } DETAILS [ 'avail_sizes' ] = { } DETAILS [ 'avail_images' ] = { } locations = avail_locations ( conn ) images = avail_images ( conn ) sizes = avail_sizes ( conn ) for key , location in six . iteritems ( locations ) : DETAILS [ 'avail_locations' ] [ location [ 'name' ] ] = location...
def get_superpxl_intensities ( im , suppxls ) : """Calculates mean intensities of pixels in superpixels inputs : im . . . grayscale image , ndarray [ MxN ] suppxls . . . image with suppxls labels , ndarray - same shape as im outputs : suppxl _ intens . . . vector with suppxls mean intensities"""
n_suppxl = np . int ( suppxls . max ( ) + 1 ) suppxl_intens = np . zeros ( n_suppxl ) for i in range ( n_suppxl ) : sup = suppxls == i vals = im [ np . nonzero ( sup ) ] try : suppxl_intens [ i ] = np . mean ( vals ) except : suppxl_intens [ i ] = - 1 return suppxl_intens
def set_qualifier ( self , value ) : """Set the qualifier for the element . Verifies the element is allowed to have a qualifier , and throws an exception if not ."""
if self . allows_qualifier : self . qualifier = value . strip ( ) else : raise UNTLStructureException ( 'Element "%s" does not allow a qualifier' % ( self . tag , ) )
def _ack ( self , message_id , subscription_id , ** kwargs ) : """Acknowledge receipt of a message . This only makes sense when the ' acknowledgement ' flag was set for the relevant subscription . : param message _ id : ID of the message to be acknowledged : param subscription : ID of the relevant subscriptio...
self . _conn . ack ( message_id , subscription_id , ** kwargs )
def next ( self ) : """return one dict which contains " data " and " label " """
if self . iter_next ( ) : self . data , self . label = self . _read ( ) return { self . data_name : self . data [ 0 ] [ 1 ] , self . label_name : self . label [ 0 ] [ 1 ] } else : raise StopIteration
def add_url_rule ( self , rule , endpoint = None , view_func = None , provide_automatic_options = None , register_with_babel = False , ** options ) : """Like : meth : ` ~ flask . Flask . add _ url _ rule ` , but if ` ` register _ with _ babel ` ` is True , then we also allow the Babel Bundle an opportunity to reg...
if self . unchained . babel_bundle and register_with_babel : self . unchained . babel_bundle . add_url_rule ( self , rule , endpoint = endpoint , view_func = view_func , provide_automatic_options = provide_automatic_options , ** options ) return super ( ) . add_url_rule ( rule , endpoint , view_func , provide_autom...
def _remove_blacklisted ( self , directories ) : """Attempts to remove the blacklisted directories from ` directories ` and then returns whatever is left in the set . Called from the ` collect _ directories ` method ."""
directories = util . to_absolute_paths ( directories ) directories = util . remove_from_set ( directories , self . blacklisted_directories ) return directories
def get_path_signature ( self , path ) : """generate a unique signature for file contained in path"""
if not os . path . exists ( path ) : return None if os . path . isdir ( path ) : merge = { } for root , dirs , files in os . walk ( path ) : for name in files : full_name = os . path . join ( root , name ) merge [ full_name ] = os . stat ( full_name ) return merge else : ...
def visit_assignname ( self , node , parent , node_name = None ) : """visit a node and return a AssignName node"""
newnode = nodes . AssignName ( node_name , getattr ( node , "lineno" , None ) , getattr ( node , "col_offset" , None ) , parent , ) self . _save_assignment ( newnode ) return newnode
def create_or_update_record ( self , dns_type , name , content , ** kwargs ) : """Create a dns record . Update it if the record already exists . : param dns _ type : : param name : : param content : : param kwargs : : return :"""
try : return self . update_record ( dns_type , name , content , ** kwargs ) except RecordNotFound : return self . create_record ( dns_type , name , content , ** kwargs )
def _check_valid_data ( self , data ) : """Checks that the incoming data is a 2 x # elements ndarray of ints . Parameters data : : obj : ` numpy . ndarray ` The data to verify . Raises ValueError If the data is not of the correct shape or type ."""
if data . dtype . type != np . int8 and data . dtype . type != np . int16 and data . dtype . type != np . int32 and data . dtype . type != np . int64 and data . dtype . type != np . uint8 and data . dtype . type != np . uint16 and data . dtype . type != np . uint32 and data . dtype . type != np . uint64 : raise Val...
def _handle_response ( self , msg_id , result = None , error = None ) : """Handle a response from the client ."""
request_future = self . _server_request_futures . pop ( msg_id , None ) if not request_future : log . warn ( "Received response to unknown message id %s" , msg_id ) return if error is not None : log . debug ( "Received error response to message %s: %s" , msg_id , error ) request_future . set_exception (...
def find_types_added_to_unions ( old_schema : GraphQLSchema , new_schema : GraphQLSchema ) -> List [ DangerousChange ] : """Find types added to union . Given two schemas , returns a list containing descriptions of any dangerous changes in the new _ schema related to adding types to a union type ."""
old_type_map = old_schema . type_map new_type_map = new_schema . type_map types_added_to_union = [ ] for new_type_name , new_type in new_type_map . items ( ) : old_type = old_type_map . get ( new_type_name ) if not ( is_union_type ( old_type ) and is_union_type ( new_type ) ) : continue old_type = c...
def run_defense_work ( self , work_id ) : """Runs one defense work . Args : work _ id : ID of the piece of work to run Returns : elapsed _ time _ sec , submission _ id - elapsed time and id of the submission Raises : WorkerError : if error occurred during execution ."""
class_batch_id = ( self . defense_work . work [ work_id ] [ 'output_classification_batch_id' ] ) class_batch = self . class_batches . read_batch_from_datastore ( class_batch_id ) adversarial_batch_id = class_batch [ 'adversarial_batch_id' ] submission_id = class_batch [ 'submission_id' ] cloud_result_path = class_batch...
def save ( self , name , file ) : """Saves new content to the file specified by name . The content should be a proper File object or any python file - like object , ready to be read from the beginning ."""
# Get the proper name for the file , as it will actually be saved . if name is None : name = file . name if not hasattr ( file , 'chunks' ) : file = File ( file , name = name ) name = self . get_available_name ( name ) name = self . _save ( name , file ) # Store filenames with forward slashes , even on Windows ...
def QueueQueryTasks ( self , queue , limit = 1 ) : """Retrieves tasks from a queue without leasing them . This is good for a read only snapshot of the tasks . Args : queue : The task queue that this task belongs to , usually client . Queue ( ) where client is the ClientURN object you want to schedule msgs o...
prefix = DataStore . QUEUE_TASK_PREDICATE_PREFIX all_tasks = [ ] for _ , serialized , ts in self . ResolvePrefix ( queue , prefix , timestamp = DataStore . ALL_TIMESTAMPS ) : task = rdf_flows . GrrMessage . FromSerializedString ( serialized ) task . leased_until = ts all_tasks . append ( task ) return all_t...
def _get_history_lines ( self ) : """Returns list of history entries ."""
history_file_name = self . _get_history_file_name ( ) if os . path . isfile ( history_file_name ) : with io . open ( history_file_name , 'r' , encoding = 'utf-8' , errors = 'ignore' ) as history_file : lines = history_file . readlines ( ) if settings . history_limit : lines = lines [ - s...
def concat ( self , other_datatable , inplace = False ) : """Concatenates two DataTables together , as long as column names are identical ( ignoring order ) . The resulting DataTable ' s columns are in the order of the table whose ` concat ` method was called ."""
if not isinstance ( other_datatable , DataTable ) : raise TypeError ( "`concat` requires a DataTable, not a %s" % type ( other_datatable ) ) # if the self table is empty , we can just return the other table # if we need to do it in place , we just copy over the columns if not self . fields : if inplace : ...
def path ( self ) : """Path of this node on Studip . Looks like Coures / folder / folder / document . Respects the renaming policies defined in the namemap"""
if self . parent is None : return self . title return join ( self . parent . path , self . title )
def check_input_types ( * types , ** validkeys ) : """This is a function decorator to check all input parameters given to decorated function are in expected types . The checks can be skipped by specify skip _ input _ checks = True in decorated function . : param tuple types : expected types of input paramet...
def decorator ( function ) : @ functools . wraps ( function ) def wrap_func ( * args , ** kwargs ) : if args [ 0 ] . _skip_input_check : # skip input check return function ( * args , ** kwargs ) # drop class object self inputs = args [ 1 : ] if ( len ( inputs ) > len ...
def _create_arg_dict ( self , tenant_id , data , in_sub , out_sub ) : """Create the argument dictionary ."""
in_seg , in_vlan = self . get_in_seg_vlan ( tenant_id ) out_seg , out_vlan = self . get_out_seg_vlan ( tenant_id ) in_ip_dict = self . get_in_ip_addr ( tenant_id ) out_ip_dict = self . get_out_ip_addr ( tenant_id ) excl_list = [ in_ip_dict . get ( 'subnet' ) , out_ip_dict . get ( 'subnet' ) ] arg_dict = { 'tenant_id' :...
def RebuildMerkleRoot ( self ) : """Rebuild the merkle root of the block"""
logger . debug ( "Rebuilding merkle root!" ) if self . Transactions is not None and len ( self . Transactions ) > 0 : self . MerkleRoot = MerkleTree . ComputeRoot ( [ tx . Hash for tx in self . Transactions ] )
def exists ( self , full_path ) : """Check that self . new _ path ( full _ path ) exists ."""
if path . exists ( self . new_path ( full_path ) ) : return self . new_path ( full_path )
def get_inventory_of_component ( self , component ) : """Retrieve inventory of a component Retrieve detailed inventory information for only the requested component ."""
self . oem_init ( ) if component == 'System' : return self . _get_zero_fru ( ) self . init_sdr ( ) for fruid in self . _sdr . fru : if self . _sdr . fru [ fruid ] . fru_name == component : return self . _oem . process_fru ( fru . FRU ( ipmicmd = self , fruid = fruid , sdr = self . _sdr . fru [ fruid ] )...
def _get_source_sum ( source_hash , file_path , saltenv ) : '''Extract the hash sum , whether it is in a remote hash file , or just a string .'''
ret = dict ( ) schemes = ( 'salt' , 'http' , 'https' , 'ftp' , 'swift' , 's3' , 'file' ) invalid_hash_msg = ( "Source hash '{0}' format is invalid. It must be in " "the format <hash type>=<hash>" ) . format ( source_hash ) source_hash = six . text_type ( source_hash ) source_hash_scheme = _urlparse ( source_hash ) . sc...
def get_socket ( dname , protocol , host , dno ) : """socket = get _ socket ( dname , protocol , host , dno ) Connect to the display specified by DNAME , PROTOCOL , HOST and DNO , which are the corresponding values from a previous call to get _ display ( ) . Return SOCKET , a new socket object connected to th...
modname = _socket_mods . get ( platform , _default_socket_mod ) mod = _relative_import ( modname ) return mod . get_socket ( dname , protocol , host , dno )
def read_instance ( self , cls , sdmxobj , offset = None , first_only = True ) : '''If cls in _ paths and matches , return an instance of cls with the first XML element , or , if first _ only is False , a list of cls instances for all elements found , If no matches were found , return None .'''
if offset : try : base = self . _paths [ offset ] ( sdmxobj . _elem ) [ 0 ] except IndexError : return None else : base = sdmxobj . _elem result = self . _paths [ cls ] ( base ) if result : if first_only : return cls ( self , result [ 0 ] ) else : return [ cls ( self ...
def spkt_welch_density ( x , param ) : """This feature calculator estimates the cross power spectral density of the time series x at different frequencies . To do so , the time series is first shifted from the time domain to the frequency domain . The feature calculators returns the power spectrum of the differ...
freq , pxx = welch ( x , nperseg = min ( len ( x ) , 256 ) ) coeff = [ config [ "coeff" ] for config in param ] indices = [ "coeff_{}" . format ( i ) for i in coeff ] if len ( pxx ) <= np . max ( coeff ) : # There are fewer data points in the time series than requested coefficients # filter coefficients that are not co...
def pprint ( data , tag_lookup , indent = 0 ) : """Return a pretty formatted string of parsed DMAP data ."""
output = '' if isinstance ( data , dict ) : for key , value in data . items ( ) : tag = tag_lookup ( key ) if isinstance ( value , ( dict , list ) ) and tag . type is not read_bplist : output += '{0}{1}: {2}\n' . format ( indent * ' ' , key , tag ) output += pprint ( value , ...
def setup ( cls , cron_cfg = "cron" ) : """Set up the runtime environment ."""
random . seed ( ) logging_cfg = cls . LOGGING_CFG if "%s" in logging_cfg : logging_cfg = logging_cfg % ( cron_cfg if "--cron" in sys . argv [ 1 : ] else "scripts" , ) logging_cfg = os . path . expanduser ( logging_cfg ) if os . path . exists ( logging_cfg ) : logging . HERE = os . path . dirname ( logging_cfg )...
def _set_vault_view ( self , session ) : """Sets the underlying vault view to match current view"""
if self . _vault_view == COMPARATIVE : try : session . use_comparative_vault_view ( ) except AttributeError : pass else : try : session . use_plenary_vault_view ( ) except AttributeError : pass
def chars2gloss ( chars ) : """Get the TLS basic gloss for a characters ."""
out = [ ] chars = gbk2big5 ( chars ) for char in chars : tmp = [ ] if char in _cd . TLS : for entry in _cd . TLS [ char ] : baxter = _cd . TLS [ char ] [ entry ] [ 'UNIHAN_GLOSS' ] if baxter != '?' : tmp += [ baxter ] out += [ ',' . join ( tmp ) ] return out
def set_analysisnotebook ( self , ** data ) : """Set attributes for ANALYSISNOTEBOOK tag Parameters * * data : dict { name : value } for the attributes to be set . Examples > > > from pgmpy . readwrite . XMLBeliefNetwork import XBNWriter > > > writer = XBNWriter ( ) > > > writer . set _ analysisnotebo...
for key , value in data . items ( ) : self . network . set ( str ( key ) , str ( value ) )
def data ( self , profile_data ) : """Set data for the widget . : param profile _ data : profile data . : type profile _ data : dict It will replace the previous data ."""
default_profile = generate_default_profile ( ) self . clear ( ) for hazard in sorted ( default_profile . keys ( ) ) : classifications = default_profile [ hazard ] hazard_widget_item = QTreeWidgetItem ( ) hazard_widget_item . setData ( 0 , Qt . UserRole , hazard ) hazard_widget_item . setText ( 0 , get_n...
def add_mrp_service ( self , info , address ) : """Add a new MediaRemoteProtocol device to discovered list ."""
if self . protocol and self . protocol != PROTOCOL_MRP : return name = info . properties [ b'Name' ] . decode ( 'utf-8' ) self . _handle_service ( address , name , conf . MrpService ( info . port ) )
def get_releasenotes ( project_dir = os . curdir , bugtracker_url = '' ) : """Retrieves the release notes , from the RELEASE _ NOTES file ( if in a package ) or generates it from the git history . Args : project _ dir ( str ) : Path to the git repo of the project . bugtracker _ url ( str ) : Url to the bug ...
releasenotes = '' pkg_info_file = os . path . join ( project_dir , 'PKG-INFO' ) releasenotes_file = os . path . join ( project_dir , 'RELEASE_NOTES' ) if os . path . exists ( pkg_info_file ) and os . path . exists ( releasenotes_file ) : with open ( releasenotes_file ) as releasenotes_fd : releasenotes = re...
def namedb_account_transaction_save ( cur , address , token_type , new_credit_value , new_debit_value , block_id , vtxindex , txid , existing_account ) : """Insert the new state of an account at a particular point in time . The data must be for a never - before - seen ( txid , block _ id , vtxindex ) set in the a...
if existing_account is None : existing_account = { } accounts_insert = { 'address' : address , 'type' : token_type , 'credit_value' : '{}' . format ( new_credit_value ) , 'debit_value' : '{}' . format ( new_debit_value ) , 'lock_transfer_block_id' : existing_account . get ( 'lock_transfer_block_id' , 0 ) , # unlock...
def get_target ( self ) : """Reads the android target based on project . properties file . Returns A string containing the project target ( android - 23 being the default if none is found )"""
with open ( '%s/project.properties' % self . path ) as f : for line in f . readlines ( ) : matches = re . findall ( r'^target=(.*)' , line ) if len ( matches ) == 0 : continue return matches [ 0 ] . replace ( '\n' , '' ) return 'android-%s' % ( config . sdk_version )
def idle_task ( self ) : '''called on idle'''
if self . threat_timeout_timer . trigger ( ) : self . check_threat_timeout ( ) if self . threat_detection_timer . trigger ( ) : self . perform_threat_detection ( )
def _CheckPacketSize ( cursor ) : """Checks that MySQL packet size is big enough for expected query size ."""
cur_packet_size = int ( _ReadVariable ( "max_allowed_packet" , cursor ) ) if cur_packet_size < MAX_PACKET_SIZE : raise Error ( "MySQL max_allowed_packet of {0} is required, got {1}. " "Please set max_allowed_packet={0} in your MySQL config." . format ( MAX_PACKET_SIZE , cur_packet_size ) )
async def ornot ( func , * args , ** kwargs ) : '''Calls func and awaits it if a returns a coroutine . Note : This is useful for implementing a function that might take a telepath proxy object or a local object , and you must call a non - async method on that object . This is also useful when calling a call...
retn = func ( * args , ** kwargs ) if iscoro ( retn ) : return await retn return retn
def top_by_func ( self , sort_func ) : """Return home / away by player info for the players on each team who come in first according to the provided sorting function . Will perform ascending sort . : param sort _ func : function that yields the sorting quantity : returns : dict of the form ` ` { ' home / away...
res = self . sort_players ( sort_func = sort_func , reverse = True ) return { 'home' : res [ 'home' ] [ 0 ] , 'away' : res [ 'away' ] [ 0 ] }
def as_format ( item , format_str = '.2f' ) : """Map a format string over a pandas object ."""
if isinstance ( item , pd . Series ) : return item . map ( lambda x : format ( x , format_str ) ) elif isinstance ( item , pd . DataFrame ) : return item . applymap ( lambda x : format ( x , format_str ) )
def execute ( self ) : """Execute the actions necessary to perform a ` molecule destroy ` and returns None . : return : None"""
self . print_info ( ) if self . _config . command_args . get ( 'destroy' ) == 'never' : msg = "Skipping, '--destroy=never' requested." LOG . warn ( msg ) return if self . _config . driver . delegated and not self . _config . driver . managed : msg = 'Skipping, instances are delegated.' LOG . warn ( ...
def create_datasource ( jboss_config , name , datasource_properties , profile = None ) : '''Create datasource in running jboss instance jboss _ config Configuration dictionary with properties specified above . name Datasource name datasource _ properties A dictionary of datasource properties to be creat...
log . debug ( "======================== MODULE FUNCTION: jboss7.create_datasource, name=%s, profile=%s" , name , profile ) ds_resource_description = __get_datasource_resource_description ( jboss_config , name , profile ) operation = '/subsystem=datasources/data-source="{name}":add({properties})' . format ( name = name ...
def _api_history ( self , plugin , nb = 0 ) : """Glances API RESTful implementation . Return the JSON representation of a given plugin history Limit to the last nb items ( all if nb = 0) HTTP / 200 if OK HTTP / 400 if plugin is not found HTTP / 404 if others error"""
response . content_type = 'application/json; charset=utf-8' if plugin not in self . plugins_list : abort ( 400 , "Unknown plugin %s (available plugins: %s)" % ( plugin , self . plugins_list ) ) # Update the stat self . __update__ ( ) try : # Get the JSON value of the stat ID statval = self . stats . get_plugin ...
def get_question_passers ( self , number : str ) -> list : """ๅ–ๅพ—่ชฒ็จ‹ไธญ็‰นๅฎš้กŒ็›ฎ้€š้Ž่€…ๅˆ—่กจ"""
try : # ๆ“ไฝœๆ‰€้œ€่ณ‡่จŠ params = { 'HW_ID' : number } # ๅ–ๅพ—่ณ‡ๆ–™ response = self . __session . get ( self . __url + '/success.jsp' , params = params , timeout = 0.5 , verify = False ) soup = BeautifulSoup ( response . text , 'html.parser' ) # ๆ•ด็†้€š้Ž่€…่ณ‡่จŠ passers = [ ] for tag in soup . find_all ( 'tr' ) : # ...
def log_level ( level ) : """Attempt to convert the given argument into a log level . Log levels are represented as integers , where higher values are more severe . If the given level is already an integer , it is simply returned . If the given level is a string that can be converted into an integer , it is ...
from six import string_types if isinstance ( level , int ) : return level if isinstance ( level , string_types ) : try : return int ( level ) except ValueError : pass try : return getattr ( logging , level . upper ( ) ) except AttributeError : pass raise ValueError ( ...
def set_ ( name , setting = None , policy_class = None , computer_policy = None , user_policy = None , cumulative_rights_assignments = True , adml_language = 'en-US' ) : '''Ensure the specified policy is set name the name of a single policy to configure setting the configuration setting for the single named...
ret = { 'name' : name , 'result' : True , 'changes' : { } , 'comment' : '' } policy_classes = [ 'machine' , 'computer' , 'user' , 'both' ] if not setting and not computer_policy and not user_policy : msg = 'At least one of the parameters setting, computer_policy, or user_policy' msg = msg + ' must be specified....
def mk_dx_dy_from_geotif_layer ( geotif ) : """Extracts the change in x and y coordinates from the geotiff file . Presently only supports WGS - 84 files ."""
ELLIPSOID_MAP = { 'WGS84' : 'WGS-84' } ellipsoid = ELLIPSOID_MAP [ geotif . grid_coordinates . wkt ] d = distance ( ellipsoid = ellipsoid ) dx = geotif . grid_coordinates . x_axis dy = geotif . grid_coordinates . y_axis dX = np . zeros ( ( dy . shape [ 0 ] - 1 ) ) for j in xrange ( len ( dX ) ) : dX [ j ] = d . mea...
def _mksocket ( host , port , q , done , stop ) : """Returns a tcp socket to ( host / port ) . Retries forever if connection fails"""
s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) s . settimeout ( 2 ) attempt = 0 while not stop . is_set ( ) : try : s . connect ( ( host , port ) ) return s except Exception as ex : # Simple exponential backoff : sleep for 1,2,4,8,16,30,30 . . . time . sleep ( min ( 30 ,...
def emit ( self , key , value ) : """Handle an output key / value pair . Reporting progress is strictly necessary only when using a Python record writer , because sending an output key / value pair is an implicit progress report . To take advantage of this , however , we would be forced to flush the uplink ...
if self . __spilling : self . __actual_emit ( key , value ) else : # key must be hashable self . __cache . setdefault ( key , [ ] ) . append ( value ) self . __cache_size += sizeof ( key ) + sizeof ( value ) if self . __cache_size >= self . __spill_size : self . __spill_all ( ) self . progress (...
def write_example_config ( example_file_path : str ) : """Writes an example config file using the config values declared so far : param example _ file _ path : path to write to"""
document = tomlkit . document ( ) for header_line in _get_header ( ) : document . add ( tomlkit . comment ( header_line ) ) config_keys = _aggregate_config_values ( ConfigValue . config_values ) _add_config_values_to_toml_object ( document , config_keys ) _doc_as_str = document . as_string ( ) . replace ( f'"{_NOT_...
def iter_children ( self , key = None ) : u"""Iterates over children . : param key : A key for filtering children by tagname ."""
tag = None if key : tag = self . _get_aliases ( ) . get ( key ) if not tag : raise KeyError ( key ) for child in self . _xml . iterchildren ( tag = tag ) : if len ( child ) : yield self . __class__ ( child ) else : yield Literal ( child )
def onAutoIndentTriggered ( self ) : """Indent current line or selected lines"""
cursor = self . _qpart . textCursor ( ) startBlock = self . _qpart . document ( ) . findBlock ( cursor . selectionStart ( ) ) endBlock = self . _qpart . document ( ) . findBlock ( cursor . selectionEnd ( ) ) if startBlock != endBlock : # indent multiply lines stopBlock = endBlock . next ( ) block = startBlock ...
def variant_to_canonical_string ( obj ) : """Return a list containing the canonical string for the given object . The ` ` obj ` ` can be a list or a set of descriptor strings , or a Unicode string . If ` ` obj ` ` is a Unicode string , it will be split using spaces as delimiters . : param variant obj : the ob...
acc = [ DG_ALL_DESCRIPTORS . canonical_value ( p ) for p in variant_to_list ( obj ) ] acc = sorted ( [ a for a in acc if a is not None ] ) return u" " . join ( acc )
def _create_figure ( kwargs : Mapping [ str , Any ] ) -> dict : """Create basic dictionary object with figure properties ."""
return { "$schema" : "https://vega.github.io/schema/vega/v3.json" , "width" : kwargs . pop ( "width" , DEFAULT_WIDTH ) , "height" : kwargs . pop ( "height" , DEFAULT_HEIGHT ) , "padding" : kwargs . pop ( "padding" , DEFAULT_PADDING ) }
def disconnect ( self ) : """Disconnect from event stream ."""
_LOGGING . debug ( 'Disconnecting from stream: %s' , self . name ) self . kill_thrd . set ( ) self . thrd . join ( ) _LOGGING . debug ( 'Event stream thread for %s is stopped' , self . name ) self . kill_thrd . clear ( )
def export_data_object_info ( bpmn_diagram , data_object_params , output_element ) : """Adds DataObject node attributes to exported XML element : param bpmn _ diagram : BPMNDiagramGraph class instantion representing a BPMN process diagram , : param data _ object _ params : dictionary with given subprocess param...
output_element . set ( consts . Consts . is_collection , data_object_params [ consts . Consts . is_collection ] )
def _CheckIsLink ( self , file_entry ) : """Checks the is _ link find specification . Args : file _ entry ( FileEntry ) : file entry . Returns : bool : True if the file entry matches the find specification , False if not ."""
if definitions . FILE_ENTRY_TYPE_LINK not in self . _file_entry_types : return False return file_entry . IsLink ( )
def base_url ( self ) -> _URL : """The base URL for the page . Supports the ` ` < base > ` ` tag ( ` learn more < https : / / www . w3schools . com / tags / tag _ base . asp > ` _ ) ."""
# Support for < base > tag . base = self . find ( 'base' , first = True ) if base : result = base . attrs . get ( 'href' , '' ) . strip ( ) if result : return result # Parse the url to separate out the path parsed = urlparse ( self . url ) . _asdict ( ) # Remove any part of the path after the last ' / '...
def pack ( self , out : IO ) : """Write the MethodTable to the file - like object ` out ` . . . note : : Advanced usage only . You will typically never need to call this method as it will be called for you when saving a ClassFile . : param out : Any file - like object providing ` write ( ) `"""
out . write ( pack ( '>H' , len ( self ) ) ) for method in self . _table : method . pack ( out )
def keyword_search ( rows , ** kwargs ) : """Takes a list of dictionaries and finds all the dictionaries where the keys and values match those found in the keyword arguments . Keys in the row data have ' ' and ' - ' replaced with ' _ ' , so they can match the keyword argument parsing . For example , the keywo...
results = [ ] if not kwargs : return results # Allows us to transform the key and do lookups like _ _ contains and # _ _ startswith matchers = { 'default' : lambda s , v : s == v , 'contains' : lambda s , v : v in s , 'startswith' : lambda s , v : s . startswith ( v ) , 'lower_value' : lambda s , v : s . lower ( ) ...
def get_openstack_cloud ( auth = None ) : '''Return an openstack _ cloud'''
if auth is None : auth = __salt__ [ 'config.option' ] ( 'keystone' , { } ) if 'shade_oscloud' in __context__ : if __context__ [ 'shade_oscloud' ] . auth == auth : return __context__ [ 'shade_oscloud' ] __context__ [ 'shade_oscloud' ] = shade . openstack_cloud ( ** auth ) return __context__ [ 'shade_oscl...
def get_support_variables ( polynomial ) : """Gets the support of a polynomial ."""
support = [ ] if is_number_type ( polynomial ) : return support for monomial in polynomial . expand ( ) . as_coefficients_dict ( ) : mon , _ = __separate_scalar_factor ( monomial ) symbolic_support = flatten ( split_commutative_parts ( mon ) ) for s in symbolic_support : if isinstance ( s , Pow ...
def stderr ( ) : """Returns the stderr as a byte stream in a Py2 / PY3 compatible manner Returns io . BytesIO Byte stream of stderr"""
# We write all of the data to stderr with bytes , typically io . BytesIO . stderr in Python2 # accepts bytes but Python3 does not . This is due to a type change on the attribute . To keep # this consistent , we leave Python2 the same and get the . buffer attribute on stderr in Python3 byte_stderr = sys . stderr if sys ...
def list_holds ( pattern = __HOLD_PATTERN , full = True ) : r'''. . versionchanged : : 2016.3.0,2015.8.4,2015.5.10 Function renamed from ` ` pkg . get _ locked _ pkgs ` ` to ` ` pkg . list _ holds ` ` . List information on locked packages . . note : : Requires the appropriate ` ` versionlock ` ` plugin pack...
_check_versionlock ( ) out = __salt__ [ 'cmd.run' ] ( [ _yum ( ) , 'versionlock' , 'list' ] , python_shell = False ) ret = [ ] for line in salt . utils . itertools . split ( out , '\n' ) : match = _get_hold ( line , pattern = pattern , full = full ) if match is not None : ret . append ( match ) return r...
def move_in_8 ( library , session , space , offset , length , extended = False ) : """Moves an 8 - bit block of data from the specified address space and offset to local memory . Corresponds to viMoveIn8 * functions of the VISA library . : param library : the visa library wrapped by ctypes . : param session :...
buffer_8 = ( ViUInt8 * length ) ( ) if extended : ret = library . viMoveIn8Ex ( session , space , offset , length , buffer_8 ) else : ret = library . viMoveIn8 ( session , space , offset , length , buffer_8 ) return list ( buffer_8 ) , ret
def reload_me ( * args , ignore_patterns = [ ] ) : """Reload currently running command with given args"""
command = [ sys . executable , sys . argv [ 0 ] ] command . extend ( args ) reload ( * command , ignore_patterns = ignore_patterns )
def _remove_event_source ( awsclient , evt_source , lambda_arn ) : """Given an event _ source dictionary , create the object and remove the event source ."""
event_source_obj = _get_event_source_obj ( awsclient , evt_source ) if event_source_obj . exists ( lambda_arn ) : event_source_obj . remove ( lambda_arn )
def find_external_metabolites ( model ) : """Return all metabolites in the external compartment ."""
ex_comp = find_external_compartment ( model ) return [ met for met in model . metabolites if met . compartment == ex_comp ]
def shutdown ( cls ) : """Close all connections on in all pools"""
for pid in list ( cls . _pools . keys ( ) ) : cls . _pools [ pid ] . shutdown ( ) LOGGER . info ( 'Shutdown complete, all pooled connections closed' )
def fwdl_status_output_fwdl_entries_message_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) fwdl_status = ET . Element ( "fwdl_status" ) config = fwdl_status output = ET . SubElement ( fwdl_status , "output" ) fwdl_entries = ET . SubElement ( output , "fwdl-entries" ) message_id = ET . SubElement ( fwdl_entries , "message-id" ) message_id . text = kwargs . pop ( 'message_id'...
def pair_visual ( original , adversarial , figure = None ) : """This function displays two images : the original and the adversarial sample : param original : the original input : param adversarial : the input after perturbations have been applied : param figure : if we ' ve already displayed images , use the...
import matplotlib . pyplot as plt # Squeeze the image to remove single - dimensional entries from array shape original = np . squeeze ( original ) adversarial = np . squeeze ( adversarial ) # Ensure our inputs are of proper shape assert ( len ( original . shape ) == 2 or len ( original . shape ) == 3 ) # To avoid creat...
def _raise_on_invalid_client ( self , request ) : """Raise on failed client authentication ."""
if self . request_validator . client_authentication_required ( request ) : if not self . request_validator . authenticate_client ( request ) : log . debug ( 'Client authentication failed, %r.' , request ) raise InvalidClientError ( request = request ) elif not self . request_validator . authenticate...
def copy ( self ) : """Copy text to clipboard"""
if not self . selectedIndexes ( ) : return ( row_min , row_max , col_min , col_max ) = get_idx_rect ( self . selectedIndexes ( ) ) index = header = False df = self . model ( ) . df obj = df . iloc [ slice ( row_min , row_max + 1 ) , slice ( col_min , col_max + 1 ) ] output = io . StringIO ( ) obj . to_csv ( output ...
def expr ( args ) : """% prog expr block exp layout napus . bed Plot a composite figure showing synteny and the expression level between homeologs in two tissues - total 4 lists of values . block file contains the gene pairs between AN and CN ."""
from jcvi . graphics . base import red_purple as default_cm p = OptionParser ( expr . __doc__ ) opts , args , iopts = p . set_image_options ( args , figsize = "8x5" ) if len ( args ) != 4 : sys . exit ( not p . print_help ( ) ) block , exp , layout , napusbed = args fig = plt . figure ( 1 , ( iopts . w , iopts . h ...
def ks_unif_pelz_good ( samples , statistic ) : """Approximates the statistic distribution by a transformed Li - Chien formula . This ought to be a bit more accurate than using the Kolmogorov limit , but should only be used with large squared sample count times statistic . See : doi : 10.18637 / jss . v039 . ...
x = 1 / statistic r2 = 1 / samples rx = sqrt ( r2 ) * x r2x = r2 * x r2x2 = r2x * x r4x = r2x * r2 r4x2 = r2x2 * r2 r4x3 = r2x2 * r2x r5x3 = r4x2 * rx r5x4 = r4x3 * rx r6x3 = r4x2 * r2x r7x5 = r5x4 * r2x r9x6 = r7x5 * r2x r11x8 = r9x6 * r2x2 a1 = rx * ( - r6x3 / 108 + r4x2 / 18 - r4x / 36 - r2x / 3 + r2 / 6 + 2 ) a2 = ...
def commit ( self ) : """Commit this transaction ."""
if not self . _parent . _is_active : raise exc . InvalidRequestError ( "This transaction is inactive" ) yield from self . _do_commit ( ) self . _is_active = False
def __analizar_observaciones ( self , ret ) : "Comprueba y extrae observaciones si existen en la respuesta XML"
self . Observaciones = [ obs [ "codigoDescripcion" ] for obs in ret . get ( 'arrayObservaciones' , [ ] ) ] self . Obs = '\n' . join ( [ "%(codigo)s: %(descripcion)s" % obs for obs in self . Observaciones ] )
def diversity ( layer ) : """Encourage diversity between each batch element . A neural net feature often responds to multiple things , but naive feature visualization often only shows us one . If you optimize a batch of images , this objective will encourage them all to be different . In particular , it cac...
def inner ( T ) : layer_t = T ( layer ) batch_n , _ , _ , channels = layer_t . get_shape ( ) . as_list ( ) flattened = tf . reshape ( layer_t , [ batch_n , - 1 , channels ] ) grams = tf . matmul ( flattened , flattened , transpose_a = True ) grams = tf . nn . l2_normalize ( grams , axis = [ 1 , 2 ] ...
def _construct_timeseries ( self , timeseries , constraints = { } ) : """wraps response _ from for timeseries calls , returns the resulting dict"""
self . response_from ( timeseries , constraints ) if self . response == None : return None return { 'data' : self . response [ 'data' ] , 'period' : self . response [ 'period' ] , 'start time' : datetime . datetime . fromtimestamp ( self . response [ 'start_time' ] ) , 'end time' : datetime . datetime . fromtimesta...
def scramble_mutation ( random , candidate , args ) : """Return the mutants created by scramble mutation on the candidates . This function performs scramble mutation . It randomly chooses two locations along the candidate and scrambles the values within that slice . . . Arguments : random - - the random n...
rate = args . setdefault ( 'mutation_rate' , 0.1 ) if random . random ( ) < rate : size = len ( candidate ) p = random . randint ( 0 , size - 1 ) q = random . randint ( 0 , size - 1 ) p , q = min ( p , q ) , max ( p , q ) s = candidate [ p : q + 1 ] random . shuffle ( s ) return candidate [ ...
def parse_exchange_table_file ( f ) : """Parse a space - separated file containing exchange compound flux limits . The first two columns contain compound IDs and compartment while the third column contains the lower flux limits . The fourth column is optional and contains the upper flux limit ."""
for line in f : line , _ , comment = line . partition ( '#' ) line = line . strip ( ) if line == '' : continue # A line can specify lower limit only ( useful for # medium compounds ) , or both lower and upper limit . fields = line . split ( None ) if len ( fields ) < 2 or len ( field...
def _sexagesimalize_to_int ( value , places = 0 ) : """Decompose ` value ` into units , minutes , seconds , and second fractions . This routine prepares a value for sexagesimal display , with its seconds fraction expressed as an integer with ` places ` digits . The result is a tuple of five integers : ` ` (...
sign = int ( np . sign ( value ) ) value = abs ( value ) power = 10 ** places n = int ( 7200 * power * value + 1 ) // 2 n , fraction = divmod ( n , power ) n , seconds = divmod ( n , 60 ) n , minutes = divmod ( n , 60 ) return sign , n , minutes , seconds , fraction
def cherry_pick ( self , branch , ** kwargs ) : """Cherry - pick a commit into a branch . Args : branch ( str ) : Name of target branch * * kwargs : Extra options to send to the server ( e . g . sudo ) Raises : GitlabAuthenticationError : If authentication is not correct GitlabCherryPickError : If the c...
path = '%s/%s/cherry_pick' % ( self . manager . path , self . get_id ( ) ) post_data = { 'branch' : branch } self . manager . gitlab . http_post ( path , post_data = post_data , ** kwargs )
def K2OSiO2 ( self , Left = 35 , Right = 79 , X0 = 30 , X1 = 90 , X_Gap = 7 , Base = 0 , Top = 19 , Y0 = 1 , Y1 = 19 , Y_Gap = 19 , FontSize = 12 , xlabel = r'$SiO_2 wt\%$' , ylabel = r'$K_2O wt\%$' , width = 12 , height = 12 , dpi = 300 ) : self . setWindowTitle ( 'K2OSiO2 diagram ' ) self . axes . clear ( ) ...
all_labels = [ ] all_colors = [ ] all_markers = [ ] all_alpha = [ ] for i in range ( len ( self . _df ) ) : target = self . _df . at [ i , 'Label' ] color = self . _df . at [ i , 'Color' ] marker = self . _df . at [ i , 'Marker' ] alpha = self . _df . at [ i , 'Alpha' ] if target not in self . SVM_l...
def list_streams ( self , session_id ) : """Returns a list of Stream objects that contains information of all the streams in a OpenTok session , with the following attributes : - count : An integer that indicates the number of streams in the session - items : List of the Stream objects"""
endpoint = self . endpoints . get_stream_url ( session_id ) response = requests . get ( endpoint , headers = self . json_headers ( ) , proxies = self . proxies , timeout = self . timeout ) if response . status_code == 200 : return StreamList ( response . json ( ) ) elif response . status_code == 400 : raise Get...
def length ( self ) : """Gets the length of the Vector"""
return math . sqrt ( ( self . x * self . x ) + ( self . y * self . y ) + ( self . z * self . z ) + ( self . w * self . w ) )
def is_excluded_for_sdesc ( self , sdesc , is_tpl = False ) : """Check whether this host should have the passed service * description * be " excluded " or " not included " . : param sdesc : service description : type sdesc : : param is _ tpl : True if service is template , otherwise False : type is _ tpl ...
if not is_tpl and self . service_includes : return sdesc not in self . service_includes if self . service_excludes : return sdesc in self . service_excludes return False
def check_async ( paths , options , rootdir = None ) : """Check given paths asynchronously . : return list : list of errors"""
LOGGER . info ( 'Async code checking is enabled.' ) path_queue = Queue . Queue ( ) result_queue = Queue . Queue ( ) for num in range ( CPU_COUNT ) : worker = Worker ( path_queue , result_queue ) worker . setDaemon ( True ) LOGGER . info ( 'Start worker #%s' , ( num + 1 ) ) worker . start ( ) for path in...
def market_snapshot ( self , prefix = False ) : """return all market quotation snapshot : param prefix : if prefix is True , return quotation dict ' s stock _ code key start with sh / sz market flag"""
return self . get_stock_data ( self . stock_list , prefix = prefix )
def scan ( pattern , string , * args , ** kwargs ) : """Returns True if pattern . search ( Sentence ( string ) ) may yield matches . If is often faster to scan prior to creating a Sentence and searching it ."""
return compile ( pattern , * args , ** kwargs ) . scan ( string )
def active_classification ( keywords , exposure_key ) : """Helper to retrieve active classification for an exposure . : param keywords : Hazard layer keywords . : type keywords : dict : param exposure _ key : The exposure key . : type exposure _ key : str : returns : The active classification key . None i...
classifications = None if 'classification' in keywords : return keywords [ 'classification' ] if 'layer_mode' in keywords and keywords [ 'layer_mode' ] == layer_mode_continuous [ 'key' ] : classifications = keywords [ 'thresholds' ] . get ( exposure_key ) elif 'value_maps' in keywords : classifications = ke...
def headerData ( self , section , orientation , role = Qt . DisplayRole ) : """Set header data"""
if role != Qt . DisplayRole : return None if orientation == Qt . Vertical : return six . text_type ( self . color_da . cmap [ section ] . values ) return super ( ColormapModel , self ) . headerData ( section , orientation , role )
def js_query ( self , query : str ) -> Awaitable : """Send query to related DOM on browser . : param str query : single string which indicates query type ."""
if self . connected : self . js_exec ( query , self . __reqid ) fut = Future ( ) # type : Future [ str ] self . __tasks [ self . __reqid ] = fut self . __reqid += 1 return fut f = Future ( ) # type : Future [ None ] f . set_result ( None ) return f
def _create_fw_fab_dev ( self , tenant_id , drvr_name , fw_dict ) : """This routine calls the Tenant Edge routine if FW Type is TE ."""
if fw_dict . get ( 'fw_type' ) == fw_constants . FW_TENANT_EDGE : self . _create_fw_fab_dev_te ( tenant_id , drvr_name , fw_dict )