signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def chords ( chord_labels , intervals , fs , ** kwargs ) : """Synthesizes chord labels Parameters chord _ labels : list of str List of chord label strings . intervals : np . ndarray , shape = ( len ( chord _ labels ) , 2) Start and end times of each chord label fs : int Sampling rate to synthesize at ...
util . validate_intervals ( intervals ) # Convert from labels to chroma roots , interval_bitmaps , _ = chord . encode_many ( chord_labels ) chromagram = np . array ( [ np . roll ( interval_bitmap , root ) for ( interval_bitmap , root ) in zip ( interval_bitmaps , roots ) ] ) . T return chroma ( chromagram , intervals ,...
def readline ( self , timeout = None ) : # timeout is not in use """Read data from port and strip escape characters : param timeout : : return : Stripped line ."""
fil = self . port . makefile ( ) line = fil . readline ( ) return strip_escape ( line . strip ( ) )
def adjust_short_series ( self , timegrid , values ) : """Adjust a short time series to a longer timegrid . Normally , time series data to be read from a external data files should span ( at least ) the whole initialization time period of a HydPy project . However , for some variables which are only used fo...
idxs = [ timegrid [ hydpy . pub . timegrids . init . firstdate ] , timegrid [ hydpy . pub . timegrids . init . lastdate ] ] valcopy = values values = numpy . full ( self . seriesshape , self . initinfo [ 0 ] ) len_ = len ( valcopy ) jdxs = [ ] for idx in idxs : if idx < 0 : jdxs . append ( 0 ) elif idx ...
def version_option ( version = None , * param_decls , ** attrs ) : """Adds a ` ` - - version ` ` option which immediately ends the program printing out the version number . This is implemented as an eager option that prints the version and exits the program in the callback . : param version : the version numb...
if version is None : module = sys . _getframe ( 1 ) . f_globals . get ( '__name__' ) def decorator ( f ) : prog_name = attrs . pop ( 'prog_name' , None ) message = attrs . pop ( 'message' , '%(prog)s, version %(version)s' ) def callback ( ctx , param , value ) : if not value or ctx . resilient_p...
def cli ( ctx , list , fpga ) : """Manage FPGA boards ."""
if list : Resources ( ) . list_boards ( ) elif fpga : Resources ( ) . list_fpgas ( ) else : click . secho ( ctx . get_help ( ) )
def delete ( method , hmc , uri , uri_parms , logon_required ) : """Operation : Delete HBA ( requires DPM mode ) ."""
try : hba = hmc . lookup_by_uri ( uri ) except KeyError : raise InvalidResourceError ( method , uri ) partition = hba . manager . parent cpc = partition . manager . parent assert cpc . dpm_enabled check_valid_cpc_status ( method , uri , cpc ) check_partition_status ( method , uri , partition , invalid_statuses ...
def export_schema_to_dict ( back_references ) : """Exports the supported import / export schema to a dictionary"""
databases = [ Database . export_schema ( recursive = True , include_parent_ref = back_references ) ] clusters = [ DruidCluster . export_schema ( recursive = True , include_parent_ref = back_references ) ] data = dict ( ) if databases : data [ DATABASES_KEY ] = databases if clusters : data [ DRUID_CLUSTERS_KEY ]...
def make_stanza ( self ) : """Create and return a presence stanza with the current settings . : return : Presence stanza : rtype : : class : ` aioxmpp . Presence `"""
stanza = aioxmpp . Presence ( ) self . _state . apply_to_stanza ( stanza ) stanza . status . update ( self . _status ) return stanza
def get_genus_type_metadata ( self ) : """Overrides get _ genus _ type _ metadata of extended object"""
metadata = dict ( self . my_osid_object_form . _genus_type_metadata ) metadata . update ( { 'read_only' : True } ) return Metadata ( ** metadata )
def start ( self ) : '''Starts a server on the port provided in the : class : ` Server ` constructor in a separate thread : rtype : Server : returns : server instance for chaining'''
self . _handler = _create_handler_class ( self . _rules , self . _always_rules ) self . _server = HTTPServer ( ( '' , self . _port ) , self . _handler ) self . _thread = Thread ( target = self . _server . serve_forever , daemon = True ) self . _thread . start ( ) self . running = True return self
def _translate_args ( args , desired_locale = None ) : """Translates all the translatable elements of the given arguments object . This method is used for translating the translatable values in method arguments which include values of tuples or dictionaries . If the object is not a tuple or a dictionary the o...
if isinstance ( args , tuple ) : return tuple ( translate ( v , desired_locale ) for v in args ) if isinstance ( args , dict ) : translated_dict = { } for ( k , v ) in six . iteritems ( args ) : translated_v = translate ( v , desired_locale ) translated_dict [ k ] = translated_v return t...
def parse ( directive ) : """Given a string in the format ` scope : directive ` , or simply ` scope ` or ` directive ` , return a Placement object suitable for passing back over the websocket API ."""
if not directive : # Handle null case return None if isinstance ( directive , ( list , tuple ) ) : results = [ ] for d in directive : results . extend ( parse ( d ) ) return results if isinstance ( directive , ( dict , client . Placement ) ) : # We ' ve been handed something that we can simply h...
def find_package_indexes_in_dir ( self , simple_dir ) : """Given a directory that contains simple packages indexes , return a sorted list of normalized package names . This presumes every directory within is a simple package index directory ."""
packages = sorted ( { # Filter out all of the " non " normalized names here canonicalize_name ( x ) for x in os . listdir ( simple_dir ) } ) # Package indexes must be in directories , so ignore anything else . packages = [ x for x in packages if os . path . isdir ( os . path . join ( simple_dir , x ) ) ] return package...
def serialize ( self , include_class = True , save_dynamic = False , ** kwargs ) : """Serialize Singleton instance to a dictionary . This behaves identically to HasProperties . serialize , except it also saves the identifying name in the dictionary as well ."""
json_dict = super ( Singleton , self ) . serialize ( include_class = include_class , save_dynamic = save_dynamic , ** kwargs ) json_dict [ '_singleton_id' ] = self . _singleton_id return json_dict
def add_app_template_global ( self , func : Callable , name : Optional [ str ] = None ) -> None : """Add an application wide template global . This is designed to be used on the blueprint directly , and has the same arguments as : meth : ` ~ quart . Quart . add _ template _ global ` . An example usage , . ....
self . record_once ( lambda state : state . register_template_global ( func , name ) )
def encrypt ( self , message , sessionkey = None , ** prefs ) : """Encrypt a PGPMessage using this key . : param message : The message to encrypt . : type message : : py : obj : ` PGPMessage ` : optional param sessionkey : Provide a session key to use when encrypting something . Default is ` ` None ` ` . If...
user = prefs . pop ( 'user' , None ) uid = None if user is not None : uid = self . get_uid ( user ) else : uid = next ( iter ( self . userids ) , None ) if uid is None and self . parent is not None : uid = next ( iter ( self . parent . userids ) , None ) cipher_algo = prefs . pop ( 'cipher' , uid . ...
def create_output ( out , shape , dtype , mode = 'w+' , suffix = None ) : """Return numpy array where image data of shape and dtype can be copied . The ' out ' parameter may have the following values or types : None An empty array of shape and dtype is created and returned . numpy . ndarray An existing wr...
if out is None : return numpy . zeros ( shape , dtype ) if isinstance ( out , str ) and out [ : 6 ] == 'memmap' : import tempfile # noqa : delay import tempdir = out [ 7 : ] if len ( out ) > 7 else None if suffix is None : suffix = '.memmap' with tempfile . NamedTemporaryFile ( dir = tem...
def make_sources ( comp_key , comp_dict ) : """Make dictionary mapping component keys to a source or set of sources Parameters comp _ key : str Key used to access sources comp _ dict : dict Information used to build sources return ` OrderedDict ` maping comp _ key to ` fermipy . roi _ model . Source `...
srcdict = OrderedDict ( ) try : comp_info = comp_dict . info except AttributeError : comp_info = comp_dict try : spectrum = comp_dict . spectrum except AttributeError : spectrum = None model_type = comp_info . model_type if model_type == 'PointSource' : srcdict [ comp_key ] = make_point_source ( com...
def _init_request_logging ( self , app ) : """Sets up request logging unless ` ` APPINSIGHTS _ DISABLE _ REQUEST _ LOGGING ` ` is set in the Flask config . Args : app ( flask . Flask ) . the Flask application for which to initialize the extension ."""
enabled = not app . config . get ( CONF_DISABLE_REQUEST_LOGGING , False ) if not enabled : return self . _requests_middleware = WSGIApplication ( self . _key , app . wsgi_app , telemetry_channel = self . _channel ) app . wsgi_app = self . _requests_middleware
def _parse_title ( file_path ) : """Parse a title from a file name"""
title = file_path title = title . split ( '/' ) [ - 1 ] title = '.' . join ( title . split ( '.' ) [ : - 1 ] ) title = ' ' . join ( title . split ( '-' ) ) title = ' ' . join ( [ word . capitalize ( ) for word in title . split ( ' ' ) ] ) return title
def main_target_usage_requirements ( self , specification , project ) : """Returns the use requirement to use when declaraing a main target , which are obtained by - translating all specified property paths , and - adding project ' s usage requirements specification : Use - properties explicitly specified f...
assert is_iterable_typed ( specification , basestring ) assert isinstance ( project , ProjectTarget ) project_usage_requirements = project . get ( 'usage-requirements' ) # We don ' t use ' refine - from - user - input ' because I ' m not sure if : # - removing of parent ' s usage requirements makes sense # - refining o...
async def _recover_jobs ( self , agent_addr ) : """Recover the jobs sent to a crashed agent"""
for ( client_addr , job_id ) , ( agent , job_msg , _ ) in reversed ( list ( self . _job_running . items ( ) ) ) : if agent == agent_addr : await ZMQUtils . send_with_addr ( self . _client_socket , client_addr , BackendJobDone ( job_id , ( "crash" , "Agent restarted" ) , 0.0 , { } , { } , { } , "" , None , N...
def draw ( self , renderer ) : """Draw the children"""
dpi_cor = renderer . points_to_pixels ( 1. ) self . dpi_transform . clear ( ) self . dpi_transform . scale ( dpi_cor , dpi_cor ) for c in self . _children : c . draw ( renderer ) self . stale = False
def filesfile_string ( self ) : """String with the list of files and prefixes needed to execute ABINIT ."""
lines = [ ] app = lines . append app ( self . input_file . path ) # 1 ) Path of the input file app ( self . output_file . path ) # 2 ) Path of the output file app ( self . ddb_filepath ) # 3 ) Input derivative database e . g . t13 . ddb . in app ( self . md_filepath ) # 4 ) Output molecular dynamics e . g . t13 . md ap...
def raise_401 ( instance , authenticate , msg = None ) : """Abort the current request with a 401 ( Unauthorized ) response code . If the message is given it ' s output as an error message in the response body ( correctly converted to the requested MIME type ) . Outputs the WWW - Authenticate header as given b...
instance . response . status = 401 instance . response . headers [ 'WWW-Authenticate' ] = authenticate if msg : instance . response . body_raw = { 'error' : msg } raise ResponseException ( instance . response )
def cscore ( args ) : """% prog cscore blastfile > cscoreOut See supplementary info for sea anemone genome paper , C - score formula : cscore ( A , B ) = score ( A , B ) / max ( best score for A , best score for B ) A C - score of one is the same as reciprocal best hit ( RBH ) . Output file will be 3 - co...
from jcvi . utils . cbook import gene_name p = OptionParser ( cscore . __doc__ ) p . add_option ( "--cutoff" , default = .9999 , type = "float" , help = "Minimum C-score to report [default: %default]" ) p . add_option ( "--pct" , default = False , action = "store_true" , help = "Also include pct as last column [default...
def remove_all ( self , key ) : """Transactional implementation of : func : ` MultiMap . remove _ all ( key ) < hazelcast . proxy . multi _ map . MultiMap . remove _ all > ` : param key : ( object ) , the key of the entries to remove . : return : ( list ) , the collection of the values associated with the key...
check_not_none ( key , "key can't be none" ) return self . _encode_invoke ( transactional_multi_map_remove_codec , key = self . _to_data ( key ) )
def simxReadVisionSensor ( clientID , sensorHandle , operationMode ) : '''Please have a look at the function description / documentation in the V - REP user manual'''
detectionState = ct . c_ubyte ( ) auxValues = ct . POINTER ( ct . c_float ) ( ) auxValuesCount = ct . POINTER ( ct . c_int ) ( ) ret = c_ReadVisionSensor ( clientID , sensorHandle , ct . byref ( detectionState ) , ct . byref ( auxValues ) , ct . byref ( auxValuesCount ) , operationMode ) auxValues2 = [ ] if ret == 0 : ...
def add_integer_proxy_for ( self , label : str , shape : Collection [ int ] = None ) -> Vertex : """Creates a proxy vertex for the given label and adds to the sequence item"""
if shape is None : return Vertex . _from_java_vertex ( self . unwrap ( ) . addIntegerProxyFor ( _VertexLabel ( label ) . unwrap ( ) ) ) else : return Vertex . _from_java_vertex ( self . unwrap ( ) . addIntegerProxyFor ( _VertexLabel ( label ) . unwrap ( ) , shape ) )
def start ( self , wait = 60 , * , server_settings = { } , ** opts ) : """Start the cluster ."""
status = self . get_status ( ) if status == 'running' : return elif status == 'not-initialized' : raise ClusterError ( 'cluster in {!r} has not been initialized' . format ( self . _data_dir ) ) port = opts . pop ( 'port' , None ) if port == 'dynamic' : port = find_available_port ( ) extra_args = [ '--{}={}'...
def _inherit_outputs ( self , pipeline_name , already_defined , resolve_outputs = False ) : """Inherits outputs from a calling Pipeline . Args : pipeline _ name : The Pipeline class name ( used for debugging ) . already _ defined : Maps output name to stringified db . Key ( of _ SlotRecords ) of any exiting...
for name , slot_key in already_defined . iteritems ( ) : if not isinstance ( slot_key , db . Key ) : slot_key = db . Key ( slot_key ) slot = self . _output_dict . get ( name ) if slot is None : if self . _strict : raise UnexpectedPipelineError ( 'Inherited output named "%s" must ...
def _share_project ( self , destination , project , to_user , force_send , auth_role = '' , user_message = '' , share_users = None ) : """Send message to remote service to email / share project with to _ user . : param destination : str which type of sharing we are doing ( SHARE _ DESTINATION or DELIVER _ DESTINA...
from_user = self . remote_store . get_current_user ( ) share_user_ids = None if share_users : share_user_ids = [ share_user . id for share_user in share_users ] item = D4S2Item ( destination = destination , from_user_id = from_user . id , to_user_id = to_user . id , project_id = project . id , project_name = projec...
def get_code_num_rgb ( s : str ) -> Optional [ Tuple [ int , int , int ] ] : """Get rgb code numbers from an RGB escape code . Raises InvalidRgbEscapeCode if an invalid number is found ."""
parts = s . split ( ';' ) if len ( parts ) != 5 : raise InvalidRgbEscapeCode ( s , reason = 'Count is off.' ) rgbparts = parts [ - 3 : ] if not rgbparts [ 2 ] . endswith ( 'm' ) : raise InvalidRgbEscapeCode ( s , reason = 'Missing \'m\' on the end.' ) rgbparts [ 2 ] = rgbparts [ 2 ] . rstrip ( 'm' ) try : r...
def save ( self , * args , ** kwargs ) : """Save the person model so it updates his / her number of board connections field . Also updates name"""
self . name = str ( self . company . name ) + " --- " + str ( self . person ) super ( Director , self ) . save ( * args , ** kwargs ) # Call the " real " save ( ) method . other_directors = Director . objects . filter ( company = self . company ) for director in other_directors : director . person . save ( )
def _update_in_hdx ( self , object_type , id_field_name , file_to_upload = None , ** kwargs ) : # type : ( str , str , Optional [ str ] , Any ) - > None """Helper method to check if HDX object exists in HDX and if so , update it Args : object _ type ( str ) : Description of HDX object type ( for messages ) id...
self . _check_load_existing_object ( object_type , id_field_name ) # We load an existing object even thought it may well have been loaded already # to prevent an admittedly unlikely race condition where someone has updated # the object in the intervening time self . _merge_hdx_update ( object_type , id_field_name , fil...
def run ( self , writer , reader ) : """Pager entry point . In interactive mode ( terminal is a tty ) , run until ` ` process _ keystroke ( ) ` ` detects quit keystroke ( ' q ' ) . In non - interactive mode , exit after displaying all unicode points . : param writer : callable writes to output stream , rece...
self . _page_data = self . initialize_page_data ( ) self . _set_lastpage ( ) if not self . term . is_a_tty : self . _run_notty ( writer ) else : self . _run_tty ( writer , reader )
def unindex_objects ( mapping_type , ids , es = None , index = None ) : """Remove documents of a specified mapping _ type from the index . This allows for asynchronous deleting . If a mapping _ type extends Indexable , you can add a ` ` pre _ delete ` ` hook for the model that it ' s based on like this : : ...
if settings . ES_DISABLED : return for id_ in ids : mapping_type . unindex ( id_ , es = es , index = index )
def get_slice_nodes ( self , time_slice = 0 ) : """Returns the nodes present in a particular timeslice Parameters time _ slice : int The timeslice should be a positive value greater than or equal to zero Examples > > > from pgmpy . models import DynamicBayesianNetwork as DBN > > > dbn = DBN ( ) > > > ...
if not isinstance ( time_slice , int ) or time_slice < 0 : raise ValueError ( "The timeslice should be a positive value greater than or equal to zero" ) return [ ( node , time_slice ) for node in self . _nodes ( ) ]
def iter_cols ( self , start = None , end = None ) : """Iterate each of the Region cols in this region"""
start = start or 0 end = end or self . ncols for i in range ( start , end ) : yield self . iloc [ : , i ]
def stencil_grid ( S , grid , dtype = None , format = None ) : """Construct a sparse matrix form a local matrix stencil . Parameters S : ndarray matrix stencil stored in N - d array grid : tuple tuple containing the N grid dimensions dtype : data type of the result format : string sparse matrix fo...
S = np . asarray ( S , dtype = dtype ) grid = tuple ( grid ) if not ( np . asarray ( S . shape ) % 2 == 1 ) . all ( ) : raise ValueError ( 'all stencil dimensions must be odd' ) if len ( grid ) != np . ndim ( S ) : raise ValueError ( 'stencil dimension must equal number of grid\ dimens...
def magic ( adata , name_list = None , k = 10 , a = 15 , t = 'auto' , n_pca = 100 , knn_dist = 'euclidean' , random_state = None , n_jobs = None , verbose = False , copy = None , ** kwargs ) : """Markov Affinity - based Graph Imputation of Cells ( MAGIC ) API [ vanDijk18 ] _ . MAGIC is an algorithm for denoising ...
try : from magic import MAGIC except ImportError : raise ImportError ( 'Please install magic package via `pip install --user ' 'git+git://github.com/KrishnaswamyLab/MAGIC.git#subdirectory=python`' ) logg . info ( 'computing PHATE' , r = True ) needs_copy = not ( name_list is None or ( isinstance ( name_list , s...
async def create_http_connection ( loop , protocol_factory , host , port = 25105 , auth = None ) : """Create an HTTP session used to connect to the Insteon Hub ."""
protocol = protocol_factory ( ) transport = HttpTransport ( loop , protocol , host , port , auth ) _LOGGER . debug ( "create_http_connection Finished creating connection" ) return ( transport , protocol )
def _read2 ( self , length = None , use_compression = None , project = None , ** kwargs ) : ''': param length : Maximum number of bytes to be read : type length : integer : param project : project to use as context for this download ( may affect which billing account is billed for this download ) . If specifi...
if self . _file_length == None : desc = self . describe ( ** kwargs ) if desc [ "state" ] != "closed" : raise DXFileError ( "Cannot read from file until it is in the closed state" ) self . _file_length = int ( desc [ "size" ] ) # If running on a worker , wait for the first file download chunk # to c...
def get_qualifier_id ( self ) : """Gets the ` ` Qualifier Id ` ` for this authorization . return : ( osid . id . Id ) - the qualifier ` ` Id ` ` * compliance : mandatory - - This method must be implemented . *"""
# Implemented from template for osid . learning . Activity . get _ objective _ id if not bool ( self . _my_map [ 'qualifierId' ] ) : raise errors . IllegalState ( 'qualifier empty' ) return Id ( self . _my_map [ 'qualifierId' ] )
def report ( data ) : """Create a Rmd report for small RNAseq analysis"""
work_dir = dd . get_work_dir ( data [ 0 ] [ 0 ] ) out_dir = op . join ( work_dir , "report" ) safe_makedir ( out_dir ) summary_file = op . join ( out_dir , "summary.csv" ) with file_transaction ( summary_file ) as out_tx : with open ( out_tx , 'w' ) as out_handle : out_handle . write ( "sample_id,%s\n" % _g...
def _create_connection ( self ) : """Create a new websocket connection with proper headers ."""
logging . debug ( "Initializing new websocket connection." ) headers = { 'Authorization' : self . service . _get_bearer_token ( ) , 'Predix-Zone-Id' : self . ingest_zone_id , 'Content-Type' : 'application/json' , } url = self . ingest_uri logging . debug ( "URL=" + str ( url ) ) logging . debug ( "HEADERS=" + str ( hea...
def get_tagged_version_numbers ( series = 'stable' ) : """Retrieve git tags and find version numbers for a release series series - ' stable ' , ' oldstable ' , or ' testing '"""
releases = [ ] if series == 'testing' : # Testing releases always have a hyphen after the version number : tag_regex = re . compile ( '^refs/tags/cassandra-([0-9]+\.[0-9]+\.[0-9]+-.*$)' ) else : # Stable and oldstable releases are just a number : tag_regex = re . compile ( '^refs/tags/cassandra-([0-9]+\.[0-9]+\...
def detach ( self , dwProcessId , bIgnoreExceptions = False ) : """Detaches from a process currently being debugged . @ note : On Windows 2000 and below the process is killed . @ see : L { attach } , L { detach _ from _ all } @ type dwProcessId : int @ param dwProcessId : Global ID of a process to detach fr...
# Keep a reference to the process . We ' ll need it later . try : aProcess = self . system . get_process ( dwProcessId ) except KeyError : aProcess = Process ( dwProcessId ) # Determine if there is support for detaching . # This check should only fail on Windows 2000 and older . try : win32 . DebugActivePro...
def check_plugin ( self , plugin ) : """Check if the section is in the proper format vcf format . Args : vcf _ section ( dict ) : The information from a vcf section Returns : True is it is in the proper format"""
vcf_section = self [ plugin ] try : vcf_field = vcf_section [ 'field' ] if not vcf_field in self . vcf_columns : raise ValidateError ( "field has to be in {0}\n" "Wrong field name in plugin: {1}" . format ( self . vcf_columns , plugin ) ) if vcf_field == 'INFO' : try : info_key =...
def _fetchall ( self , query , vars , limit = None , offset = 0 ) : """Return multiple rows ."""
if limit is None : limit = current_app . config [ 'DEFAULT_PAGE_SIZE' ] query += ' LIMIT %s OFFSET %s' '' % ( limit , offset ) cursor = self . get_db ( ) . cursor ( ) self . _log ( cursor , query , vars ) cursor . execute ( query , vars ) return cursor . fetchall ( )
def show_events ( self , status = None , nids = None ) : """Print the Abinit events ( ERRORS , WARNIING , COMMENTS ) to stdout Args : status : if not None , only the tasks with this status are select nids : optional list of node identifiers used to filter the tasks ."""
nrows , ncols = get_terminal_size ( ) for task in self . iflat_tasks ( status = status , nids = nids ) : report = task . get_event_report ( ) if report : print ( make_banner ( str ( task ) , width = ncols , mark = "=" ) ) print ( report )
def _get_installed ( self ) : """Gets a list of the file paths to repo settings files that are being monitored by the CI server ."""
from utility import get_json # This is a little tricky because the data file doesn ' t just have a list # of installed servers . It also manages the script ' s database that tracks # the user ' s interactions with it . fulldata = get_json ( self . instpath , { } ) if "installed" in fulldata : return fulldata [ "ins...
def digicam_configure_send ( self , target_system , target_component , mode , shutter_speed , aperture , iso , exposure_type , command_id , engine_cut_off , extra_param , extra_value , force_mavlink1 = False ) : '''Configure on - board Camera Control System . target _ system : System ID ( uint8 _ t ) target _ c...
return self . send ( self . digicam_configure_encode ( target_system , target_component , mode , shutter_speed , aperture , iso , exposure_type , command_id , engine_cut_off , extra_param , extra_value ) , force_mavlink1 = force_mavlink1 )
def _find_export ( self , func ) : # type : ( Callable [ [ Tuple [ Any , EndpointDescription ] ] , bool ] ) - > Optional [ Tuple [ Any , EndpointDescription ] ] """Look for an export using the given lookup method The lookup method must accept a single parameter , which is a tuple containing a service instance a...
with self . _exported_instances_lock : for val in self . _exported_services . values ( ) : if func ( val ) : return val return None
def highlight ( __text : str , * , lexer : str = 'diff' , formatter : str = 'terminal' ) -> str : """Highlight text highlighted using ` ` pygments ` ` . Returns text untouched if colour output is not enabled . See also : : pypi : ` Pygments ` Args : _ _ text : Text to highlight lexer : Jinja lexer to use ...
if sys . stdout . isatty ( ) : lexer = get_lexer_by_name ( lexer ) formatter = get_formatter_by_name ( formatter ) __text = pyg_highlight ( __text , lexer , formatter ) return __text
def start ( queue , profile = None , tag = 'salt/engine/sqs' , owner_acct_id = None ) : '''Listen to sqs and fire message on event bus'''
if __opts__ . get ( '__role' ) == 'master' : fire_master = salt . utils . event . get_master_event ( __opts__ , __opts__ [ 'sock_dir' ] , listen = False ) . fire_event else : fire_master = __salt__ [ 'event.send' ] message_format = __opts__ . get ( 'sqs.message_format' , None ) sqs = _get_sqs_conn ( profile ) q...
def access_elementusers ( self , elementuser_id , access_id = None , tenant_id = None , api_version = "v2.0" ) : """Get all accesses for a particular user * * Parameters : * * : - * * elementuser _ id * * : Element User ID - * * access _ id * * : ( optional ) Access ID - * * tenant _ id * * : Tenant ID - ...
if tenant_id is None and self . _parent_class . tenant_id : # Pull tenant _ id from parent namespace cache . tenant_id = self . _parent_class . tenant_id elif not tenant_id : # No value for tenant _ id . raise TypeError ( "tenant_id is required but not set or cached." ) cur_ctlr = self . _parent_class . control...
def go_to_line ( self , line = None ) : """Go to line dialog"""
if line is not None : # When this method is called from the flileswitcher , a line # number is specified , so there is no need for the dialog . self . get_current_editor ( ) . go_to_line ( line ) else : if self . data : self . get_current_editor ( ) . exec_gotolinedialog ( )
def _newIdentifier ( self ) : """Make a new identifier for an as - yet uncreated model object . @ rtype : C { int }"""
id = self . _allocateID ( ) self . _idsToObjects [ id ] = self . _NO_OBJECT_MARKER self . _lastValues [ id ] = None return id
def requires_list ( self ) : """It is important that this property is calculated lazily . Getting the ' requires ' attribute may trigger a package load , which may be avoided if this variant is reduced away before that happens ."""
requires = self . variant . get_requires ( build_requires = self . building ) reqlist = RequirementList ( requires ) if reqlist . conflict : raise ResolveError ( "The package %s has an internal requirements conflict: %s" % ( str ( self ) , str ( reqlist ) ) ) return reqlist
async def create ( source_id : str , attrs : dict , cred_def_handle : int , name : str , price : str ) : """Creates a Class representing an Issuer Credential : param source _ id : Tag associated by user of sdk : param attrs : attributes that will form the credential : param cred _ def _ handle : Handle from p...
constructor_params = ( source_id , attrs , cred_def_handle , name , price ) c_source_id = c_char_p ( source_id . encode ( 'utf-8' ) ) c_cred_def_handle = c_uint32 ( cred_def_handle ) c_price = c_char_p ( price . encode ( 'utf-8' ) ) # default institution _ did in config is used as issuer _ did c_issuer_did = None c_dat...
def _send_string_selection ( self , string : str ) : """Use the mouse selection clipboard to send a string ."""
backup = self . clipboard . selection # Keep a backup of current content , to restore the original afterwards . if backup is None : logger . warning ( "Tried to backup the X PRIMARY selection content, but got None instead of a string." ) self . clipboard . selection = string self . __enqueue ( self . _paste_using_m...
def create_q ( token ) : """Creates the Q ( ) object ."""
meta = getattr ( token , 'meta' , None ) query = getattr ( token , 'query' , '' ) wildcards = None if isinstance ( query , six . string_types ) : # Unicode - > Quoted string search = query else : # List - > No quoted string ( possible wildcards ) if len ( query ) == 1 : search = query [ 0 ] elif len...
def _filter ( self , query , ** kwargs ) : """Filter a query with user - supplied arguments ."""
query = self . _auto_filter ( query , ** kwargs ) return query
def drawPoint ( self , x , y , silent = True ) : """Draws a point on the current : py : class : ` Layer ` with the current : py : class : ` Brush ` . Coordinates are relative to the original layer size WITHOUT downsampling applied . : param x1 : Point X coordinate . : param y1 : Point Y coordinate . : rtype...
start = time . time ( ) # Downsample the coordinates x = int ( x / config . DOWNSAMPLING ) y = int ( y / config . DOWNSAMPLING ) # Apply the dab with or without source caching if self . brush . usesSourceCaching : applyMirroredDab_jit ( self . mirrorMode , self . image . getActiveLayer ( ) . data , int ( x - self ....
def _draw_fold_indicator ( self , top , mouse_over , collapsed , painter ) : """Draw the fold indicator / trigger ( arrow ) . : param top : Top position : param mouse _ over : Whether the mouse is over the indicator : param collapsed : Whether the trigger is collapsed or not . : param painter : QPainter"""
rect = QRect ( 0 , top , self . sizeHint ( ) . width ( ) , self . sizeHint ( ) . height ( ) ) if self . _native_icons : opt = QStyleOptionViewItem ( ) opt . rect = rect opt . state = ( QStyle . State_Active | QStyle . State_Item | QStyle . State_Children ) if not collapsed : opt . state |= QStyl...
def as_dot ( self ) -> str : """Return as a string the dot version of the graph ."""
return nx . drawing . nx_pydot . to_pydot ( self . _graph ) . to_string ( )
def _cont_norm_running_quantile_mp ( wl , fluxes , ivars , q , delta_lambda , n_proc = 2 , verbose = False ) : """The same as _ cont _ norm _ running _ quantile ( ) above , but using multi - processing . Bo Zhang ( NAOC )"""
nStar = fluxes . shape [ 0 ] # start mp . Pool mp_results = [ ] pool = mp . Pool ( processes = n_proc ) for i in xrange ( nStar ) : mp_results . append ( pool . apply_async ( _find_cont_running_quantile , ( wl , fluxes [ i , : ] . reshape ( ( 1 , - 1 ) ) , ivars [ i , : ] . reshape ( ( 1 , - 1 ) ) , q , delta_lambd...
def Logout ( self , dumpXml = None ) : """Logout method disconnects from UCS ."""
from UcsBase import UcsException if ( self . _cookie == None ) : return True if self . _refreshTimer : self . _refreshTimer . cancel ( ) response = self . AaaLogout ( dumpXml ) self . _cookie = None self . _lastUpdateTime = str ( time . asctime ( ) ) self . _domains = None self . _priv = None self . _sessionId ...
def SortBy ( * qs ) : """Convert a list of Q objects into list of sort instructions"""
sort = [ ] for q in qs : if q . _path . endswith ( '.desc' ) : sort . append ( ( q . _path [ : - 5 ] , DESCENDING ) ) else : sort . append ( ( q . _path , ASCENDING ) ) return sort
def plugin_for ( cls , model ) : '''Find and return a plugin for this model . Uses inheritance to find a model where the plugin is registered .'''
logger . debug ( "Getting a plugin for: %s" , model ) if not issubclass ( model , Model ) : return if model in cls . plugins : return cls . plugins [ model ] for b in model . __bases__ : p = cls . plugin_for ( b ) if p : return p
def compress_ranges_to_lists ( self ) : '''Converts the internal dimension ranges on lists into list of the restricted size . Thus all dimension rules are applied to all dimensions of the list wrapper and returned as a list ( of lists ) .'''
clist = [ ] for elem in self : if isinstance ( elem , FixedListSubset ) : clist . append ( elem . compress_ranges_to_lists ( ) ) else : clist . append ( elem ) return clist
def draw_light_2d_linear ( self , kwargs_list , n = 1 , new_compute = False , r_eff = 1. ) : """constructs the CDF and draws from it random realizations of projected radii R : param kwargs _ list : : return :"""
if not hasattr ( self , '_light_cdf' ) or new_compute is True : r_array = np . linspace ( self . _min_interpolate , self . _max_interpolate , self . _interp_grid_num ) cum_sum = np . zeros_like ( r_array ) sum = 0 for i , r in enumerate ( r_array ) : if i == 0 : cum_sum [ i ] = 0 ...
def insertBefore ( self , newchild , refchild ) : """Insert a new child node before an existing child . It must be the case that refchild is a child of this node ; if not , ValueError is raised . newchild is returned ."""
for i , childNode in enumerate ( self . childNodes ) : if childNode is refchild : self . childNodes . insert ( i , newchild ) newchild . parentNode = self self . _verifyChildren ( i ) return newchild raise ValueError ( refchild )
def connect ( self , keyfile = None ) : """Connect to the node via ssh using the paramiko library . : return : : py : class : ` paramiko . SSHClient ` - ssh connection or None on failure"""
ssh = paramiko . SSHClient ( ) ssh . set_missing_host_key_policy ( paramiko . AutoAddPolicy ( ) ) if keyfile and os . path . exists ( keyfile ) : ssh . load_host_keys ( keyfile ) # Try connecting using the ` preferred _ ip ` , if # present . Otherwise , try all of them and set ` preferred _ ip ` # using the first t...
def _process_diseases ( self , limit = None ) : """This method processes the KEGG disease IDs . Triples created : < disease _ id > is a class < disease _ id > rdfs : label < disease _ name > : param limit : : return :"""
LOG . info ( "Processing diseases" ) if self . test_mode : graph = self . testgraph else : graph = self . graph line_counter = 0 model = Model ( graph ) raw = '/' . join ( ( self . rawdir , self . files [ 'disease' ] [ 'file' ] ) ) with open ( raw , 'r' , encoding = "iso-8859-1" ) as csvfile : filereader = ...
def append_text ( self , txt ) : """adds a line of text to a file"""
with open ( self . fullname , "a" ) as myfile : myfile . write ( txt )
def generic_request ( self , method , uri , all_pages = False , data_key = None , no_data = False , do_not_process = False , force_urlencode_data = False , data = None , params = None , files = None , single_item = False ) : """Generic Canvas Request Method ."""
if not uri . startswith ( 'http' ) : uri = self . uri_for ( uri ) if force_urlencode_data is True : uri += '?' + urllib . urlencode ( data ) assert method in [ 'GET' , 'POST' , 'PUT' , 'DELETE' , 'HEAD' , 'OPTIONS' ] if method == 'GET' : response = self . session . get ( uri , params = params ) elif method ...
def delete_collection_csi_driver ( self , ** kwargs ) : """delete collection of CSIDriver This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . delete _ collection _ csi _ driver ( async _ req = True ) > > > resul...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . delete_collection_csi_driver_with_http_info ( ** kwargs ) else : ( data ) = self . delete_collection_csi_driver_with_http_info ( ** kwargs ) return data
def run_rep ( self , params , rep ) : """run a single repetition including directory creation , log files , etc ."""
try : name = params [ 'name' ] fullpath = os . path . join ( params [ 'path' ] , params [ 'name' ] ) logname = os . path . join ( fullpath , '%i.log' % rep ) # check if repetition exists and has been completed restore = 0 if os . path . exists ( logname ) : logfile = open ( logname , 'r'...
def destroy ( vm_name , call = None ) : '''Call ' destroy ' on the instance . Can be called with " - a destroy " or - d CLI Example : . . code - block : : bash salt - cloud - a destroy myinstance1 myinstance2 . . . salt - cloud - d myinstance1 myinstance2 . . .'''
if call and call != 'action' : raise SaltCloudSystemExit ( 'The destroy action must be called with -d or "-a destroy".' ) conn = get_conn ( ) try : node = conn . ex_get_node ( vm_name ) except Exception as exc : # pylint : disable = W0703 log . error ( 'Could not locate instance %s\n\n' 'The following excep...
def get_word_break_property ( value , is_bytes = False ) : """Get ` WORD BREAK ` property ."""
obj = unidata . ascii_word_break if is_bytes else unidata . unicode_word_break if value . startswith ( '^' ) : negated = value [ 1 : ] value = '^' + unidata . unicode_alias [ 'wordbreak' ] . get ( negated , negated ) else : value = unidata . unicode_alias [ 'wordbreak' ] . get ( value , value ) return obj [...
def dbStore ( self , typ , py_value ) : """Prepares to store this column for the a particular backend database . : param backend : < orb . Database > : param py _ value : < variant > : param context : < orb . Context > : return : < variant >"""
# convert base types to work in the database if isinstance ( py_value , ( list , tuple , set ) ) : py_value = tuple ( ( self . dbStore ( x ) for x in py_value ) ) elif isinstance ( py_value , orb . Collection ) : py_value = py_value . ids ( ) elif isinstance ( py_value , orb . Model ) : py_value = py_value ...
def move ( self , x , y ) : """Move window top - left corner to position"""
SetWindowPos ( self . _hwnd , None , x , y , 0 , 0 , SWP_NOSIZE )
def tune ( self , verbose = None ) : """Tuning initial slice width parameter"""
if not self . _tune : return False else : self . w_tune . append ( abs ( self . stochastic . last_value - self . stochastic . value ) ) self . w = 2 * ( sum ( self . w_tune ) / len ( self . w_tune ) ) return True
def from_ ( self , selectable ) : """Adds a table to the query . This function can only be called once and will raise an AttributeError if called a second time . : param selectable : Type : ` ` Table ` ` , ` ` Query ` ` , or ` ` str ` ` When a ` ` str ` ` is passed , a table with the name matching the ` ` s...
self . _from . append ( Table ( selectable ) if isinstance ( selectable , str ) else selectable ) if isinstance ( selectable , ( QueryBuilder , _UnionQuery ) ) and selectable . alias is None : if isinstance ( selectable , QueryBuilder ) : sub_query_count = selectable . _subquery_count else : sub...
def skip_count ( self ) : """Amount of skipped test cases in this list . : return : integer"""
return len ( [ i for i , result in enumerate ( self . data ) if result . skip ] )
def close ( self ) : """Shutdown and free all resources ."""
if self . _controller is not None : self . _controller . quit ( ) self . _controller = None if self . _process is not None : self . _process . close ( ) self . _process = None
def cov_from_scales ( self , scales ) : """Return a covariance matrix built from a dictionary of scales . ` scales ` is a dictionary keyed by stochastic instances , and the values refer are the variance of the jump distribution for each stochastic . If a stochastic is a sequence , the variance must have the...
# Get array of scales ord_sc = [ ] for stochastic in self . stochastics : ord_sc . append ( np . ravel ( scales [ stochastic ] ) ) ord_sc = np . concatenate ( ord_sc ) if np . squeeze ( ord_sc ) . shape [ 0 ] != self . dim : raise ValueError ( "Improper initial scales, dimension don't match" , ( np . squeeze ( ...
def concentric_hexagons ( radius , start = ( 0 , 0 ) ) : """A generator which produces coordinates of concentric rings of hexagons . Parameters radius : int Number of layers to produce ( 0 is just one hexagon ) start : ( x , y ) The coordinate of the central hexagon ."""
x , y = start yield ( x , y ) for r in range ( 1 , radius + 1 ) : # Move to the next layer y -= 1 # Walk around the hexagon of this radius for dx , dy in [ ( 1 , 1 ) , ( 0 , 1 ) , ( - 1 , 0 ) , ( - 1 , - 1 ) , ( 0 , - 1 ) , ( 1 , 0 ) ] : for _ in range ( r ) : yield ( x , y ) ...
def _reaction_representer ( dumper , data ) : """Generate a parsable reaction representation to the YAML parser . Check the number of compounds in the reaction , if it is larger than 10, then transform the reaction data into a list of directories with all attributes in the reaction ; otherwise , just return t...
if len ( data . compounds ) > _MAX_REACTION_LENGTH : def dict_make ( compounds ) : for compound , value in compounds : yield OrderedDict ( [ ( 'id' , text_type ( compound . name ) ) , ( 'compartment' , compound . compartment ) , ( 'value' , value ) ] ) left = list ( dict_make ( data . left )...
def get_message ( self , set_slave_ok , is_mongos , use_cmd = False ) : """Get a query message , possibly setting the slaveOk bit ."""
if set_slave_ok : # Set the slaveOk bit . flags = self . flags | 4 else : flags = self . flags ns = _UJOIN % ( self . db , self . coll ) spec = self . spec if use_cmd : ns = _UJOIN % ( self . db , "$cmd" ) spec = self . as_command ( ) [ 0 ] ntoreturn = - 1 # All DB commands return 1 document els...
def add_formdata ( self , content = None ) : # type : ( Optional [ Dict [ str , str ] ] ) - > None """Add data as a multipart form - data request to the request . We only deal with file - like objects or strings at this point . The requests is not yet streamed . : param dict headers : Any headers to add to th...
if content is None : content = { } content_type = self . headers . pop ( 'Content-Type' , None ) if self . headers else None if content_type and content_type . lower ( ) == 'application/x-www-form-urlencoded' : # Do NOT use " add _ content " that assumes input is JSON self . data = { f : d for f , d in content ...
def await_reservations ( self , sc , status = { } , timeout = 600 ) : """Block until all reservations are received ."""
timespent = 0 while not self . reservations . done ( ) : logging . info ( "waiting for {0} reservations" . format ( self . reservations . remaining ( ) ) ) # check status flags for any errors if 'error' in status : sc . cancelAllJobs ( ) sc . stop ( ) sys . exit ( 1 ) time . slee...
def headercontent ( self , method ) : """Get the content for the SOAP I { Header } node . @ param method : A service method . @ type method : I { service . Method } @ return : The XML content for the < body / > . @ rtype : [ L { Element } , . . . ]"""
content = [ ] wsse = self . options ( ) . wsse if wsse is not None : content . append ( wsse . xml ( ) ) headers = self . options ( ) . soapheaders if not isinstance ( headers , ( tuple , list , dict ) ) : headers = ( headers , ) elif not headers : return content pts = self . headpart_types ( method ) if is...
def set_chime ( self , sound , cycles = None ) : """: param sound : a str , one of [ " doorbell " , " fur _ elise " , " doorbell _ extended " , " alert " , " william _ tell " , " rondo _ alla _ turca " , " police _ siren " , " " evacuation " , " beep _ beep " , " beep " , " inactive " ] : param cycles : Undoc...
desired_state = { "activate_chime" : sound } if cycles is not None : desired_state . update ( { "chime_cycles" : cycles } ) response = self . api_interface . set_device_state ( self , { "desired_state" : desired_state } ) self . _update_state_from_response ( response )
def _set_factory_context ( factory_class , bundle_context ) : # type : ( type , Optional [ BundleContext ] ) - > Optional [ FactoryContext ] """Transforms the context data dictionary into its FactoryContext object form . : param factory _ class : A manipulated class : param bundle _ context : The class bundle c...
try : # Try to get the factory context ( built using decorators ) context = getattr ( factory_class , constants . IPOPO_FACTORY_CONTEXT ) except AttributeError : # The class has not been manipulated , or too badly return None if not context . completed : # Partial context ( class not manipulated ) return No...
def execute_on_entries ( self , entry_processor , predicate = None ) : """Applies the user defined EntryProcessor to all the entries in the map or entries in the map which satisfies the predicate if provided . Returns the results mapped by each key in the map . : param entry _ processor : ( object ) , A statefu...
if predicate : return self . _encode_invoke ( map_execute_with_predicate_codec , entry_processor = self . _to_data ( entry_processor ) , predicate = self . _to_data ( predicate ) ) return self . _encode_invoke ( map_execute_on_all_keys_codec , entry_processor = self . _to_data ( entry_processor ) )
def add_send_message ( self , connection , send_message ) : """Adds a send _ message function to the Dispatcher ' s dictionary of functions indexed by connection . Args : connection ( str ) : A locally unique identifier provided by the receiver of messages . send _ message ( fn ) : The method that should ...
self . _send_message [ connection ] = send_message LOGGER . debug ( "Added send_message function " "for connection %s" , connection )
def read_gaf ( fin_gaf , prt = sys . stdout , hdr_only = False , allow_missing_symbol = False , ** kws ) : """Read Gene Association File ( GAF ) . Return data ."""
return GafReader ( fin_gaf , hdr_only , prt = prt , allow_missing_symbol = allow_missing_symbol ) . get_id2gos ( ** kws )