signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def wait_droplets ( self , droplets , status = None , locked = None , wait_interval = None , wait_time = None ) : r"""Poll the server periodically until all droplets in ` ` droplets ` ` have reached some final state , yielding each ` Droplet ` ' s final value when it ' s done . If ` ` status ` ` is non - ` None...
if ( status is None ) == ( locked is None ) : # # # TODO : Is TypeError the right type of error ? raise TypeError ( 'Exactly one of "status" and "locked" must be' ' specified' ) droplets = map ( self . _droplet , droplets ) if status is not None : return self . _wait ( droplets , "status" , status , wait_interv...
def estimate ( self , maxiter = 250 , convergence = 1e-7 ) : """run EM algorithm until convergence , or until maxiter reached"""
self . loglik = np . zeros ( maxiter ) iter = 0 while iter < maxiter : self . loglik [ iter ] = self . E_step ( ) if np . isnan ( self . loglik [ iter ] ) : print ( "undefined log-likelihood" ) break self . M_step ( ) if self . loglik [ iter ] - self . loglik [ iter - 1 ] < 0 and iter > ...
def delta ( self , mapping , prefix ) : """return a delta containing values that have changed ."""
previous = self . getrange ( prefix , strip = True ) if not previous : pk = set ( ) else : pk = set ( previous . keys ( ) ) ck = set ( mapping . keys ( ) ) delta = DeltaSet ( ) # added for k in ck . difference ( pk ) : delta [ k ] = Delta ( None , mapping [ k ] ) # removed for k in pk . difference ( ck ) : ...
def content_length ( self ) -> Optional [ int ] : """The value of Content - Length HTTP header ."""
content_length = self . _headers . get ( hdrs . CONTENT_LENGTH ) # type : ignore if content_length is not None : return int ( content_length ) else : return None
def varchar ( self , field = None ) : """Returns a chunk of text , of maximum length ' max _ length '"""
assert field is not None , "The field parameter must be passed to the 'varchar' method." max_length = field . max_length def source ( ) : length = random . choice ( range ( 1 , max_length + 1 ) ) return "" . join ( random . choice ( general_chars ) for i in xrange ( length ) ) return self . get_allowed_value ( ...
def start_new_log ( self ) : '''open a new dataflash log , reset state'''
filename = self . new_log_filepath ( ) self . block_cnt = 0 self . logfile = open ( filename , 'w+b' ) print ( "DFLogger: logging started (%s)" % ( filename ) ) self . prev_cnt = 0 self . download = 0 self . prev_download = 0 self . last_idle_status_printed_time = time . time ( ) self . last_status_time = time . time (...
def SetBalanceFor ( self , assetId , fixed8_val ) : """Set the balance for an asset id . Args : assetId ( UInt256 ) : fixed8 _ val ( Fixed8 ) : balance value ."""
found = False for key , val in self . Balances . items ( ) : if key == assetId : self . Balances [ key ] = fixed8_val found = True if not found : self . Balances [ assetId ] = fixed8_val
def metadata_response ( self , request , full_url , headers ) : """Mock response for localhost metadata http : / / docs . aws . amazon . com / AWSEC2 / latest / UserGuide / AESDG - chapter - instancedata . html"""
parsed_url = urlparse ( full_url ) tomorrow = datetime . datetime . utcnow ( ) + datetime . timedelta ( days = 1 ) credentials = dict ( AccessKeyId = "test-key" , SecretAccessKey = "test-secret-key" , Token = "test-session-token" , Expiration = tomorrow . strftime ( "%Y-%m-%dT%H:%M:%SZ" ) ) path = parsed_url . path met...
def peaks ( data , method = 'max' , axis = 'time' , limits = None ) : """Return the values of an index where the data is at max or min Parameters method : str , optional ' max ' or ' min ' axis : str , optional the axis where you want to detect the peaks limits : tuple of two values , optional the low...
idx_axis = data . index_of ( axis ) output = data . _copy ( ) output . axis . pop ( axis ) for trl in range ( data . number_of ( 'trial' ) ) : values = data . axis [ axis ] [ trl ] dat = data ( trial = trl ) if limits is not None : limits = ( values < limits [ 0 ] ) | ( values > limits [ 1 ] ) ...
def noEmptyNests ( node ) : '''recursively make sure that no dictionaries inside node contain empty children lists'''
if type ( node ) == list : for i in node : noEmptyNests ( i ) if type ( node ) == dict : for i in node . values ( ) : noEmptyNests ( i ) if node [ "children" ] == [ ] : node . pop ( "children" ) return node
def drawHotspots ( self , painter ) : """Draws all the hotspots for the renderer . : param painter | < QPaint >"""
# draw hotspots for hotspot in ( self . _hotspots + self . _dropzones ) : hstyle = hotspot . style ( ) if hstyle == XNode . HotspotStyle . Invisible : continue hotspot . render ( painter , self )
def verification_resource_secure ( self , verification_id , jwt , name ) : """Get Verification Resource . Uses GET to / verifications / < verification _ id > interface Use this method rather than verification _ resource when adding a second factor to your application . See ` this < https : / / cloud . knuvers...
params = { "jwt" : jwt , "name" : name } response = self . _get ( url . verifications_id . format ( id = verification_id ) , params = params ) self . _check_response ( response , 200 ) return self . _create_response ( response )
def get_symbol_map ( self ) : """If you need the symbol map , use this method . The symbol map is an array of string pairs mapping common tokens to X Keysym strings , such as " alt " to " Alt _ L " : return : array of strings ."""
# todo : make sure we return a list of strings ! sm = _libxdo . xdo_get_symbol_map ( ) # Return value is like : # [ ' alt ' , ' Alt _ L ' , . . . , None , None , None , . . . ] # We want to return only values up to the first None . # todo : any better solution than this ? i = 0 ret = [ ] while True : c = sm [ i ] ...
def _file_lists ( load , form ) : '''Return a dict containing the file lists for files , dirs , emptydirs and symlinks'''
if 'env' in load : # " env " is not supported ; Use " saltenv " . load . pop ( 'env' ) if 'saltenv' not in load or load [ 'saltenv' ] not in envs ( ) : return [ ] list_cachedir = os . path . join ( __opts__ [ 'cachedir' ] , 'file_lists/svnfs' ) if not os . path . isdir ( list_cachedir ) : try : os ....
def has_separate_working_tree ( self ) : """: return : True if our git _ dir is not at the root of our working _ tree _ dir , but a . git file with a platform agnositic symbolic link . Our git _ dir will be wherever the . git file points to : note : bare repositories will always return False here"""
if self . bare : return False return osp . isfile ( osp . join ( self . working_tree_dir , '.git' ) )
def do_save ( self , line ) : """save [ config _ file ] Save session variables to file save ( without parameters ) : Save session to default file ~ / . dataone _ cli . conf save . < file > : Save session to specified file ."""
config_file = self . _split_args ( line , 0 , 1 ) [ 0 ] self . _command_processor . get_session ( ) . save ( config_file ) if config_file is None : config_file = ( self . _command_processor . get_session ( ) . get_default_pickle_file_path ( ) ) self . _print_info_if_verbose ( "Saved session to file: {}" . format ( ...
def _FromSpecs ( self , specs ) : """Populates _ params using specification Arguments : specs - - either : ( a ) list as [ ( name , { . . . } ) , . . . ] ( see Parameter . FromSpec ( ) for further information ) ( b ) dictionary as { " name " : value , . . . }"""
if isinstance ( specs , dict ) : specs_ = [ ] for name , value in specs . items ( ) : specs_ . append ( ( name , { "value" : value } ) ) else : specs_ = specs for spec in specs_ : self . params . append ( Parameter ( spec ) )
def _find_mirror ( self , axis ) : """Looks for mirror symmetry of specified type about axis . Possible types are " h " or " vd " . Horizontal ( h ) mirrors are perpendicular to the axis while vertical ( v ) or diagonal ( d ) mirrors are parallel . v mirrors has atoms lying on the mirror plane while d mirrors...
mirror_type = "" # First test whether the axis itself is the normal to a mirror plane . if self . is_valid_op ( SymmOp . reflection ( axis ) ) : self . symmops . append ( SymmOp . reflection ( axis ) ) mirror_type = "h" else : # Iterate through all pairs of atoms to find mirror for s1 , s2 in itertools . co...
def get_config ( self ) : """Return configurations of BoltzmannQPolicy # Returns Dict of config"""
config = super ( BoltzmannQPolicy , self ) . get_config ( ) config [ 'tau' ] = self . tau config [ 'clip' ] = self . clip return config
def set_labels ( self , labels , axis = 'rows' ) : '''Set the row / col labels . Note that this method doesn ' t check that enough labels were set for all the assigned positions .'''
if axis . lower ( ) in ( 'rows' , 'row' , 'r' , 0 ) : assigned_pos = set ( v [ 0 ] for v in self . _positions . itervalues ( ) ) not_assigned = set ( labels ) - assigned_pos if len ( not_assigned ) > 0 : msg = 'New labels must contain all assigned positions' raise ValueError ( msg ) self...
async def scan_for_apple_tvs ( loop , timeout = 5 , abort_on_found = False , device_ip = None , only_usable = True , protocol = None ) : """Scan for Apple TVs using zeroconf ( bonjour ) and returns them ."""
semaphore = asyncio . Semaphore ( value = 0 , loop = loop ) listener = _ServiceListener ( loop , abort_on_found , device_ip , protocol , semaphore ) zeroconf = Zeroconf ( ) try : ServiceBrowser ( zeroconf , HOMESHARING_SERVICE , listener ) ServiceBrowser ( zeroconf , DEVICE_SERVICE , listener ) ServiceBrows...
def read_daemon ( self ) : """Read thread ."""
while True : data = self . _socket . recv ( 9999 ) self . feed_parser ( data )
def t_heredoc_END_HEREDOC ( t ) : r'( ? < = \ n ) [ A - Za - z _ ] [ \ w _ ] *'
if t . value == t . lexer . heredoc_label : del t . lexer . heredoc_label t . lexer . pop_state ( ) else : t . type = 'ENCAPSED_AND_WHITESPACE' return t
def handle_readable ( client ) : """Return True : The client is re - registered to the selector object . Return False : The server disconnects the client ."""
data = client . recv ( 1028 ) if data == b'' : return False client . sendall ( b'SERVER: ' + data ) print ( threading . active_count ( ) ) return True
def _builder_connect_signals ( self , _dict ) : """Called by controllers which want to autoconnect their handlers with signals declared in internal Gtk . Builder . This method accumulates handlers , and books signal autoconnection later on the idle of the next occurring gtk loop . After the autoconnection i...
assert not self . builder_connected , "Gtk.Builder not already connected" if _dict and not self . builder_pending_callbacks : # this is the first call , book the builder connection for # later gtk loop GLib . idle_add ( self . __builder_connect_pending_signals ) for n , v in _dict . items ( ) : if n not in self...
def _json_path_search ( self , json_dict , expr ) : """Scan JSON dictionary with using json - path passed sting of the format of $ . element . . element1 [ index ] etc . * Args : * \n _ json _ dict _ - JSON dictionary ; \n _ expr _ - string of fuzzy search for items within the directory ; \n * Returns : * \...
path = parse ( expr ) results = path . find ( json_dict ) if len ( results ) is 0 : raise JsonValidatorError ( "Nothing found in the dictionary {0} using the given path {1}" . format ( str ( json_dict ) , str ( expr ) ) ) return results
def start ( self ) : """Start the channel"""
# observers for this channel only need to wait for one value self . _observer_params . update ( dict ( once = True ) ) super ( CurrentResourceValue , self ) . start ( ) self . _api . ensure_notifications_thread ( ) self . _api . _mds_rpc_post ( device_id = self . device_id , method = 'GET' , uri = self . resource_path ...
def _handle_read_chunk ( self ) : """Some data can be read"""
new_data = b'' buffer_length = len ( self . read_buffer ) try : while buffer_length < self . MAX_BUFFER_SIZE : try : piece = self . recv ( 4096 ) except OSError as e : if e . errno == errno . EAGAIN : # End of the available data break elif e . errn...
def set_data ( self , data , invsigma = None ) : """Set the data to be modeled . Returns * self * ."""
self . data = np . array ( data , dtype = np . float , ndmin = 1 ) if invsigma is None : self . invsigma = np . ones ( self . data . shape ) else : i = np . array ( invsigma , dtype = np . float ) self . invsigma = np . broadcast_arrays ( self . data , i ) [ 1 ] # allow scalar invsigma if self . invsigma . ...
def verify_rsa_signature ( signature , signature_scheme , public_key , data ) : """< Purpose > Determine whether the corresponding private key of ' public _ key ' produced ' signature ' . verify _ signature ( ) will use the public key , signature scheme , and ' data ' to complete the verification . > > > pu...
# Does ' public _ key ' have the correct format ? # This check will ensure ' public _ key ' conforms to # ' securesystemslib . formats . PEMRSA _ SCHEMA ' . Raise # ' securesystemslib . exceptions . FormatError ' if the check fails . securesystemslib . formats . PEMRSA_SCHEMA . check_match ( public_key ) # Does ' signa...
def close ( self ) : """Unmap the MMIO object ' s mapped physical memory ."""
if self . mapping is None : return self . mapping . close ( ) self . mapping = None self . _fd = None
def _process_media_status ( self , data ) : """Processes a STATUS message ."""
self . status . update ( data ) self . logger . debug ( "Media:Received status %s" , data ) # Update session active threading event if self . status . media_session_id is None : self . session_active_event . clear ( ) else : self . session_active_event . set ( ) self . _fire_status_changed ( )
def on_finish ( self ) : """Called regardless of success or failure"""
r = self . response r . request_time = time . time ( ) - self . start_time if self . callback : self . callback ( r )
def by_median_household_income ( self , lower = - 1 , upper = 2 ** 31 , zipcode_type = ZipcodeType . Standard , sort_by = SimpleZipcode . median_household_income . name , ascending = False , returns = DEFAULT_LIMIT ) : """Search zipcode information by median household income ."""
return self . query ( median_household_income_lower = lower , median_household_income_upper = upper , sort_by = sort_by , zipcode_type = zipcode_type , ascending = ascending , returns = returns , )
def normalize_locale ( loc ) : '''Format a locale specifier according to the format returned by ` locale - a ` .'''
comps = split_locale ( loc ) comps [ 'territory' ] = comps [ 'territory' ] . upper ( ) comps [ 'codeset' ] = comps [ 'codeset' ] . lower ( ) . replace ( '-' , '' ) comps [ 'charmap' ] = '' return join_locale ( comps )
def speech ( self ) -> str : """Report summary designed to be read by a text - to - speech program"""
if not self . data : self . update ( ) return speech . taf ( self . data , self . units )
def alias ( * aliases ) : """Decorator to add aliases for Cmdln . do _ * command handlers . Example : class MyShell ( cmdln . Cmdln ) : @ cmdln . alias ( " ! " , " sh " ) def do _ shell ( self , argv ) : # . . . implement ' shell ' command"""
def decorate ( f ) : if not hasattr ( f , "aliases" ) : f . aliases = [ ] f . aliases += aliases return f return decorate
def _enforce_space ( self , item ) : """Enforce a space in certain situations . There are cases where we will want a space where normally we wouldn ' t put one . This just enforces the addition of a space ."""
if isinstance ( self . _lines [ - 1 ] , ( self . _Space , self . _LineBreak , self . _Indent ) ) : return if not self . _prev_item : return item_text = unicode ( item ) prev_text = unicode ( self . _prev_item ) # Prefer a space around a ' . ' in an import statement , and between the # ' import ' and ' ( ' . if ...
def json ( src , dest = False , shift = 4 ) : """Beautify JSON Args : src : JSON string or path - to - file with text to beautify ( mandatory ) dest : path - to - file to save beautified json string ; ( optional ) if file doesn ' t exist it is created automatically ; if this arg is skept function returns ...
if not dest : return _json ( _text ( src ) ) # returns string else : if type ( dest ) is int : # dest is skept , custom pattern provided at dist place return _json ( _text ( src ) , dest ) else : with open ( dest , 'w' ) as f2 : return f2 . write ( _json ( _text ( src ) , shi...
def set_chassis ( self , chassis ) : """Sets the chassis . : param : chassis string : 1720 , 1721 , 1750 , 1751 or 1760"""
yield from self . _hypervisor . send ( 'c1700 set_chassis "{name}" {chassis}' . format ( name = self . _name , chassis = chassis ) ) log . info ( 'Router "{name}" [{id}]: chassis set to {chassis}' . format ( name = self . _name , id = self . _id , chassis = chassis ) ) self . _chassis = chassis self . _setup_chassis ( ...
def load_plugins ( plugin_dir : str , module_prefix : str ) -> int : """Find all non - hidden modules or packages in a given directory , and import them with the given module prefix . : param plugin _ dir : plugin directory to search : param module _ prefix : module prefix used while importing : return : nu...
count = 0 for name in os . listdir ( plugin_dir ) : path = os . path . join ( plugin_dir , name ) if os . path . isfile ( path ) and ( name . startswith ( '_' ) or not name . endswith ( '.py' ) ) : continue if os . path . isdir ( path ) and ( name . startswith ( '_' ) or not os . path . exists ( os ...
def _getFirstPathExpression ( name ) : """Returns the first metric path in an expression ."""
tokens = grammar . parseString ( name ) pathExpression = None while pathExpression is None : if tokens . pathExpression : pathExpression = tokens . pathExpression elif tokens . expression : tokens = tokens . expression elif tokens . call : tokens = tokens . call . args [ 0 ] else...
def parse_state_variable ( self , node ) : """Parses < StateVariable > @ param node : Node containing the < StateVariable > element @ type node : xml . etree . Element @ raise ParseError : Raised when the state variable is not being defined in the context of a component type ."""
if 'name' in node . lattrib : name = node . lattrib [ 'name' ] else : self . raise_error ( '<StateVariable> must specify a name' ) if 'dimension' in node . lattrib : dimension = node . lattrib [ 'dimension' ] else : self . raise_error ( "State variable '{0}' must specify a dimension" , name ) if 'exposu...
def find_packages ( ) : """Find all of mdtraj ' s python packages . Adapted from IPython ' s setupbase . py . Copyright IPython contributors , licensed under the BSD license ."""
packages = [ 'mdtraj.scripts' ] for dir , subdirs , files in os . walk ( 'MDTraj' ) : package = dir . replace ( os . path . sep , '.' ) if '__init__.py' not in files : # not a package continue packages . append ( package . replace ( 'MDTraj' , 'mdtraj' ) ) return packages
def create_basic_app ( cls , bundles = None , _config_overrides = None ) : """Creates a " fake " app for use while developing"""
bundles = bundles or [ ] name = bundles [ - 1 ] . module_name if bundles else 'basic_app' app = FlaskUnchained ( name , template_folder = os . path . join ( os . path . dirname ( __file__ ) , 'templates' ) ) for bundle in bundles : bundle . before_init_app ( app ) unchained . init_app ( app , DEV , bundles , _confi...
def update_identity ( self , identity , identity_id ) : """UpdateIdentity . : param : class : ` < Identity > < azure . devops . v5_0 . identity . models . Identity > ` identity : : param str identity _ id :"""
route_values = { } if identity_id is not None : route_values [ 'identityId' ] = self . _serialize . url ( 'identity_id' , identity_id , 'str' ) content = self . _serialize . body ( identity , 'Identity' ) self . _send ( http_method = 'PUT' , location_id = '28010c54-d0c0-4c89-a5b0-1c9e188b9fb7' , version = '5.0' , r...
def python_like_exts ( ) : """Return a list of all python - like extensions"""
exts = [ ] for lang in languages . PYTHON_LIKE_LANGUAGES : exts . extend ( list ( languages . ALL_LANGUAGES [ lang ] ) ) return [ '.' + ext for ext in exts ]
def get_repo_info ( loader , sha , prov_g ) : """Generate swagger information from the repo being used ."""
user_repo = loader . getFullName ( ) repo_title = loader . getRepoTitle ( ) contact_name = loader . getContactName ( ) contact_url = loader . getContactUrl ( ) commit_list = loader . getCommitList ( ) licence_url = loader . getLicenceURL ( ) # Add the API URI as a used entity by the activity if prov_g : prov_g . ad...
def refreshWidgets ( self ) : """This function manually refreshed all widgets attached to this simulation . You want to call this function if any particle data has been manually changed ."""
if hasattr ( self , '_widgets' ) : for w in self . _widgets : w . refresh ( isauto = 0 ) else : raise RuntimeError ( "No widgets found" )
def solve_limited ( self , assumptions = [ ] ) : """Solve internal formula using given budgets for conflicts and propagations ."""
if self . minisat : if self . use_timer : start_time = time . clock ( ) # saving default SIGINT handler def_sigint_handler = signal . signal ( signal . SIGINT , signal . SIG_DFL ) self . status = pysolvers . minisatgh_solve_lim ( self . minisat , assumptions ) # recovering default SIGINT han...
async def run_action ( self , action_name , ** params ) : """Run an action on this unit . : param str action _ name : Name of action to run : param * * params : Action parameters : returns : A : class : ` juju . action . Action ` instance . Note that this only enqueues the action . You will need to call `...
action_facade = client . ActionFacade . from_connection ( self . connection ) log . debug ( 'Starting action `%s` on %s' , action_name , self . name ) res = await action_facade . Enqueue ( [ client . Action ( name = action_name , parameters = params , receiver = self . tag , ) ] ) action = res . results [ 0 ] . action ...
def incremental ( self , start_time , ** kwargs ) : """Retrieve bulk data from the chat incremental API . : param fields : list of fields to retrieve . ` Chat API Docs < https : / / developer . zendesk . com / rest _ api / docs / chat / incremental _ export # usage - notes - resource - expansion > ` _ _ . : p...
return self . _query_zendesk ( self . endpoint . incremental , self . object_type , start_time = start_time , ** kwargs )
def is_abstract ( self , pass_is_abstract = True ) : """Check if the method is abstract . A method is considered abstract if any of the following is true : * The only statement is ' raise NotImplementedError ' * The only statement is ' pass ' and pass _ is _ abstract is True * The method is annotated with a...
if self . decorators : for node in self . decorators . nodes : try : inferred = next ( node . infer ( ) ) except exceptions . InferenceError : continue if inferred and inferred . qname ( ) in ( "abc.abstractproperty" , "abc.abstractmethod" , ) : return Tru...
def prepare ( self , query , custom_payload = None , keyspace = None ) : """Prepares a query string , returning a : class : ` ~ cassandra . query . PreparedStatement ` instance which can be used as follows : : > > > session = cluster . connect ( " mykeyspace " ) > > > query = " INSERT INTO users ( id , name ,...
message = PrepareMessage ( query = query , keyspace = keyspace ) future = ResponseFuture ( self , message , query = None , timeout = self . default_timeout ) try : future . send_request ( ) query_id , bind_metadata , pk_indexes , result_metadata , result_metadata_id = future . result ( ) except Exception : ...
def use_comparative_assessment_part_view ( self ) : """Pass through to provider AssessmentPartLookupSession . use _ comparative _ assessment _ part _ view"""
self . _object_views [ 'assessment_part' ] = COMPARATIVE # self . _ get _ provider _ session ( ' assessment _ part _ lookup _ session ' ) # To make sure the session is tracked for session in self . _get_provider_sessions ( ) : try : session . use_comparative_assessment_part_view ( ) except AttributeErro...
def increment_lineno ( node , n = 1 ) : """Increment the line numbers of all nodes by ` n ` if they have line number attributes . This is useful to " move code " to a different location in a file ."""
for node in zip ( ( node , ) , walk ( node ) ) : if 'lineno' in node . _attributes : node . lineno = getattr ( node , 'lineno' , 0 ) + n
def read_samples ( self , sr = None , offset = 0 , duration = None ) : """Read the samples of the utterance . Args : sr ( int ) : If None uses the sampling rate given by the track , otherwise resamples to the given sampling rate . offset ( float ) : Offset in seconds to read samples from . duration ( floa...
read_duration = self . duration if offset > 0 and read_duration is not None : read_duration -= offset if duration is not None : if read_duration is None : read_duration = duration else : read_duration = min ( duration , read_duration ) return self . track . read_samples ( sr = sr , offset = ...
def left_of ( self , other ) : """Test if this range ` other ` is strictly left of ` other ` . > > > intrange ( 1 , 5 ) . left _ of ( intrange ( 5 , 10 ) ) True > > > intrange ( 1 , 10 ) . left _ of ( intrange ( 5 , 10 ) ) False The bitwise right shift operator ` ` < < ` ` is overloaded for this operation...
if not self . is_valid_range ( other ) : msg = ( "Left of is not supported for '{}', provide a proper range " "class" ) . format ( other . __class__ . __name__ ) raise TypeError ( msg ) return self < other and not self . overlap ( other )
def plot_baf_lrr ( file_names , options ) : """Plot BAF and LRR for a list of files . : param file _ names : contains the name of the input file for each sample . : param options : the options . : type file _ names : dict : type options : argparse . Namespace Plots the BAF ( B Allele Frequency ) and LRR (...
# importing important stuff import matplotlib as mpl if options . format != "X11" and mpl . get_backend ( ) != "agg" : mpl . use ( "Agg" ) import matplotlib . pyplot as plt if options . format != "X11" : plt . ioff ( ) # For each of the sample / files for sample , file_name in file_names . iteritems ( ) : d...
def str_count ( arr , pat , flags = 0 ) : """Count occurrences of pattern in each string of the Series / Index . This function is used to count the number of times a particular regex pattern is repeated in each of the string elements of the : class : ` ~ pandas . Series ` . Parameters pat : str Valid re...
regex = re . compile ( pat , flags = flags ) f = lambda x : len ( regex . findall ( x ) ) return _na_map ( f , arr , dtype = int )
def run_event_hooks ( event , task ) : """Executes registered task event plugins for the provided event and task . ` event ` Name of the event to trigger for the plugin : ( ' task _ start ' , ' task _ run ' , ' task _ end ' ) ` task ` ` ` Task ` ` instance ."""
# get chain of classes registered for this event call_chain = _event_hooks . get ( event ) if call_chain : # lookup the associated class method for this event event_methods = { 'task_start' : 'on_taskstart' , 'task_run' : 'on_taskrun' , 'task_end' : 'on_taskend' } method = event_methods . get ( event ) if m...
def _apply_base_theme ( app ) : """Apply base theme to the application . Args : app ( QApplication ) : QApplication instance ."""
if QT_VERSION < ( 5 , ) : app . setStyle ( 'plastique' ) else : app . setStyle ( 'Fusion' ) with open ( _STYLESHEET ) as stylesheet : app . setStyleSheet ( stylesheet . read ( ) )
def remove_option ( self , mask ) : """Unset arbitrary query flags using a bitmask . To unset the tailable flag : cursor . remove _ option ( 2)"""
if not isinstance ( mask , int ) : raise TypeError ( "mask must be an int" ) self . __check_okay_to_chain ( ) if mask & _QUERY_OPTIONS [ "exhaust" ] : self . __exhaust = False self . __query_flags &= ~ mask return self
def _palette_cmd ( self , event ) : """Respond to user click on a palette item ."""
label = event . widget label . master . focus_set ( ) label . master . configure ( relief = "sunken" ) r , g , b = self . winfo_rgb ( label . cget ( "background" ) ) r = round2 ( r * 255 / 65535 ) g = round2 ( g * 255 / 65535 ) b = round2 ( b * 255 / 65535 ) args = ( r , g , b ) if self . alpha_channel : a = self ....
def getJsonPath ( name , moduleFile ) : """获取JSON配置文件的路径 : 1 . 优先从当前工作目录查找JSON文件 2 . 若无法找到则前往模块所在目录查找"""
currentFolder = os . getcwd ( ) currentJsonPath = os . path . join ( currentFolder , name ) if os . path . isfile ( currentJsonPath ) : return currentJsonPath else : moduleFolder = os . path . abspath ( os . path . dirname ( moduleFile ) ) moduleJsonPath = os . path . join ( moduleFolder , '.' , name ) ...
def cover ( self , match_set ) : """Return a new classifier rule that can be added to the match set , with a condition that matches the situation of the match set and an action selected to avoid duplication of the actions already contained therein . The match _ set argument is a MatchSet instance representi...
assert isinstance ( match_set , MatchSet ) assert match_set . model . algorithm is self # Create a new condition that matches the situation . condition = bitstrings . BitCondition . cover ( match_set . situation , self . wildcard_probability ) # Pick a random action that ( preferably ) isn ' t already suggested by # so...
def from_dict ( cls , d ) : """Construct a MSONable AdfTask object from the JSON dict . Parameters d : dict A dict of saved attributes . Returns task : AdfTask An AdfTask object recovered from the JSON dict ` ` d ` ` ."""
def _from_dict ( _d ) : return AdfKey . from_dict ( _d ) if _d is not None else None operation = d . get ( "operation" ) title = d . get ( "title" ) basis_set = _from_dict ( d . get ( "basis_set" ) ) xc = _from_dict ( d . get ( "xc" ) ) units = _from_dict ( d . get ( "units" ) ) scf = _from_dict ( d . get ( "scf" )...
def get_as_nullable_parameters ( self , key ) : """Converts map element into an Parameters or returns null if conversion is not possible . : param key : a key of element to get . : return : Parameters value of the element or null if conversion is not supported ."""
value = self . get_as_nullable_map ( key ) return Parameters ( value ) if value != None else None
def release_apply ( ui , repo , clname , ** opts ) : """apply a CL to the release branch Creates a new CL copying a previously committed change from the main branch to the release branch . The current client must either be clean or already be in the release branch . The release branch must be created by s...
c = repo [ None ] if not releaseBranch : raise hg_util . Abort ( "no active release branches" ) if c . branch ( ) != releaseBranch : if c . modified ( ) or c . added ( ) or c . removed ( ) : raise hg_util . Abort ( "uncommitted local changes - cannot switch branches" ) err = hg_clean ( repo , releas...
def list_lattices ( device_name : str = None , num_qubits : int = None , connection : ForestConnection = None ) : """Query the Forest 2.0 server for its knowledge of lattices . Optionally filters by underlying device name and lattice qubit count . : return : A dictionary keyed on lattice names and valued in dic...
if connection is None : connection = ForestConnection ( ) session = connection . session url = connection . forest_cloud_endpoint + "/lattices" try : response = get_json ( session , url , params = { "device_name" : device_name , "num_qubits" : num_qubits } ) return response [ "lattices" ] except Exception a...
def soma_surface_area ( nrn , neurite_type = NeuriteType . soma ) : '''Get the surface area of a neuron ' s soma . Note : The surface area is calculated by assuming the soma is spherical .'''
assert neurite_type == NeuriteType . soma , 'Neurite type must be soma' return 4 * math . pi * nrn . soma . radius ** 2
def _prepare_body ( self ) : """private function to prepare content for paramType = body"""
content_type = self . __consume if not content_type : content_type = self . __op . consumes [ 0 ] if self . __op . consumes else 'application/json' if self . __op . consumes and content_type not in self . __op . consumes : raise errs . SchemaError ( 'content type {0} does not present in {1}' . format ( content_...
def make_synthetic ( self , srd = 0 , v_repl_seismic = 2000 , v_repl_log = 2000 , f = 50 , dt = 0.001 ) : """Early hack . Use with extreme caution . Hands - free . There ' ll be a more granualr version in synthetic . py . Assumes DT is in μs / m and RHOB is kg / m3. There is no handling yet for TVD . The da...
kb = getattr ( self . location , 'kb' , None ) or 0 data0 = self . data [ 'DT' ] . start log_start_time = ( ( srd - kb ) / v_repl_seismic ) + ( data0 / v_repl_log ) # Basic log values . dt_log = self . data [ 'DT' ] . despike ( ) # assume μs / m rho_log = self . data [ 'RHOB' ] . despike ( ) # assume kg / m3 if not np ...
def transform_entries ( self , entries , terminal_compositions ) : """Method to transform all entries to the composition coordinate in the terminal compositions . If the entry does not fall within the space defined by the terminal compositions , they are excluded . For example , Li3PO4 is mapped into a Li2O :...
new_entries = [ ] if self . normalize_terminals : fractional_comp = [ c . fractional_composition for c in terminal_compositions ] else : fractional_comp = terminal_compositions # Map terminal compositions to unique dummy species . sp_mapping = collections . OrderedDict ( ) for i , comp in enumerate ( fractional...
def upset_union ( self , featuresets ) : """Yield all featuresets that subsume any of the given ones ."""
concepts = ( f . concept for f in featuresets ) indexes = ( c . index for c in self . lattice . upset_union ( concepts ) ) return map ( self . _featuresets . __getitem__ , indexes )
def decode ( self , value ) : """Decode value ."""
if self . encoding : value = value . decode ( self . encoding ) return self . deserialize ( value )
def create_network ( self ) : """Create a new network ."""
return DiscreteGenerational ( generations = self . generations , generation_size = self . generation_size , initial_source = True , )
def del_ostype ( self , ostype , sync = True ) : """delete OS type from this company : param ostype : the OS type to be deleted from this company : param sync : If sync = True ( default ) synchronize with Ariane server . If sync = False , add the OS type object on list to be removed on next save ( ) . : ret...
LOGGER . debug ( "Company.del_ostype" ) if not sync : self . ost_2_rm . append ( ostype ) else : if ostype . id is None : ostype . sync ( ) if self . id is not None and ostype . id is not None : params = { 'id' : self . id , 'ostypeID' : ostype . id } args = { 'http_operation' : 'GET...
def putrequest ( self , method , url , * args , ** kwargs ) : """httplib gives you more than one way to do it . This is a way to start building up a request . Usually followed by a bunch of putheader ( ) calls ."""
self . _vcr_request = Request ( method = method , uri = self . _uri ( url ) , body = "" , headers = { } ) log . debug ( 'Got {}' . format ( self . _vcr_request ) )
def _all_dicts ( bases , seen = None ) : """Yield each class in ` ` bases ` ` and each of their base classes ."""
if seen is None : seen = set ( ) for cls in bases : if cls in seen : continue seen . add ( cls ) yield cls . __dict__ for b in _all_dicts ( cls . __bases__ , seen ) : yield b
def resolve_polytomy ( self , default_dist = 0.0 , default_support = 0.0 , recursive = True ) : """Resolve all polytomies under current node by creating an arbitrary dicotomic structure among the affected nodes . This function randomly modifies current tree topology and should only be used for compatibility r...
def _resolve ( node ) : if len ( node . children ) > 2 : children = list ( node . children ) node . children = [ ] next_node = root = node for i in range ( len ( children ) - 2 ) : next_node = next_node . add_child ( ) next_node . dist = default_dist ...
def urlopen ( url , headers = { } , data = None , retries = RETRIES , timeout = TIMEOUT ) : '''打开一个http连接 , 并返回Request . headers 是一个dict . 默认提供了一些项目 , 比如User - Agent , Referer等 , 就 不需要重复加入了 . 这个函数只能用于http请求 , 不可以用于下载大文件 . 如果服务器支持gzip压缩的话 , 就会使用gzip对数据进行压缩 , 然后在本地自动 解压 . req . data 里面放着的是最终的http数据内容 , 通常...
headers_merged = default_headers . copy ( ) for key in headers . keys ( ) : headers_merged [ key ] = headers [ key ] opener = urllib . request . build_opener ( ForbiddenHandler ) opener . addheaders = [ ( k , v ) for k , v in headers_merged . items ( ) ] for i in range ( retries ) : try : req = opener ....
def get ( self , request , bot_id , id , format = None ) : """Get KikBot by id serializer : KikBotSerializer responseMessages : - code : 401 message : Not authenticated"""
return super ( KikBotDetail , self ) . get ( request , bot_id , id , format )
def batch ( data , batch_size , batch_size_fn = None ) : """Yield elements from data in chunks of batch _ size ."""
if batch_size_fn is None : def batch_size_fn ( new , count , sofar ) : return count minibatch , size_so_far = [ ] , 0 for ex in data : minibatch . append ( ex ) size_so_far = batch_size_fn ( ex , len ( minibatch ) , size_so_far ) if size_so_far == batch_size : yield minibatch min...
def tileBounds ( self , zoom , tileCol , tileRow ) : "Returns the bounds of a tile in LV03 ( EPSG : 21781)"
assert zoom in range ( 0 , len ( self . RESOLUTIONS ) ) # 0,0 at top left : y axis down and x axis right tileSize = self . tileSize ( zoom ) minX = self . MINX + tileCol * tileSize maxX = self . MINX + ( tileCol + 1 ) * tileSize if self . originCorner == 'bottom-left' : minY = self . MINY + tileRow * tileSize m...
def layers ( self ) : """returns a list of layer classes ( including subclasses ) in this packet"""
# noqa : E501 layers = [ ] lyr = self while lyr : layers . append ( lyr . __class__ ) lyr = lyr . payload . getlayer ( 0 , _subclass = True ) return layers
def append_process_params ( xmldoc , process , params ) : """xmldoc is an XML document tree , process is the row in the process table for which these are the parameters , and params is a list of ( name , type , value ) tuples one for each parameter . See also process _ params _ from _ dict ( ) , register _ to...
try : paramtable = lsctables . ProcessParamsTable . get_table ( xmldoc ) except ValueError : paramtable = lsctables . New ( lsctables . ProcessParamsTable ) xmldoc . childNodes [ 0 ] . appendChild ( paramtable ) for name , typ , value in params : row = paramtable . RowType ( ) row . program = proces...
def parse_file_args ( file_obj , file_type , resolver = None , ** kwargs ) : """Given a file _ obj and a file _ type try to turn them into a file - like object and a lowercase string of file type . Parameters file _ obj : str : if string represents a file path , returns file _ obj : an ' rb ' opened file ob...
metadata = { } opened = False if ( 'metadata' in kwargs and isinstance ( kwargs [ 'metadata' ] , dict ) ) : metadata . update ( kwargs [ 'metadata' ] ) if util . is_file ( file_obj ) and file_type is None : raise ValueError ( 'file_type must be set when passing file objects!' ) if util . is_string ( file_obj ) ...
def config ( self ) : """Return a string with the configuration"""
return ", " . join ( '%s:%s' % ( key , value ) for key , value in self . conf . items ( ) )
def authorize_client_credentials ( self , client_id , client_secret = None , scope = "private_agent" ) : """Authorize to platform with client credentials This should be used if you posses client _ id / client _ secret pair generated by platform ."""
self . auth_data = { "grant_type" : "client_credentials" , "scope" : [ scope ] , "client_id" : client_id , "client_secret" : client_secret } self . _do_authorize ( )
def orderered_methods ( self ) : """An ordered list of methods : return : A list of ordered methods is this module : rtype : list"""
oms = [ ] self . methods . reverse ( ) if self . main : oms = [ self . main ] for m in self . methods : if m == self . main : continue oms . append ( m ) return oms
def get_users_of_account_group ( self , account_id , group_id , ** kwargs ) : # noqa : E501 """Get users of a group . # noqa : E501 An endpoint for listing users of the group with details . * * Example usage : * * ` curl https : / / api . us - east - 1 . mbedcloud . com / v3 / accounts / { accountID } / policy - ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . get_users_of_account_group_with_http_info ( account_id , group_id , ** kwargs ) # noqa : E501 else : ( data ) = self . get_users_of_account_group_with_http_info ( account_id , group_id , ** kwargs ) # noqa : E5...
def _get_connection ( self ) : """Returns our cached LDAPObject , which may or may not be bound ."""
if self . _connection is None : uri = self . settings . SERVER_URI if callable ( uri ) : uri = uri ( ) self . _connection = self . backend . ldap . initialize ( uri ) for opt , value in self . settings . CONNECTION_OPTIONS . items ( ) : self . _connection . set_option ( opt , value ) ...
def _load_nonlink_level ( handler , level , pathtable , pathname ) : """Loads level and builds appropriate type , without handling softlinks"""
if isinstance ( level , tables . Group ) : if _sns and ( level . _v_title . startswith ( 'SimpleNamespace:' ) or DEEPDISH_IO_ROOT_IS_SNS in level . _v_attrs ) : val = SimpleNamespace ( ) dct = val . __dict__ elif level . _v_title . startswith ( 'list:' ) : dct = { } val = [ ] ...
def prepare_destruction ( self , recursive = True ) : """Prepares the model for destruction Recursively un - registers all observers and removes references to child models . Extends the destroy method of the base class by child elements of a container state ."""
# logger . verbose ( " Prepare destruction container state . . . " ) if recursive : for scoped_variable in self . scoped_variables : scoped_variable . prepare_destruction ( ) for connection in self . transitions [ : ] + self . data_flows [ : ] : connection . prepare_destruction ( ) for state...
def get_time ( self , instance ) : """Return the current mission time for the specified instance . : rtype : ~ datetime . datetime"""
url = '/instances/{}' . format ( instance ) response = self . get_proto ( url ) message = yamcsManagement_pb2 . YamcsInstance ( ) message . ParseFromString ( response . content ) if message . HasField ( 'missionTime' ) : return parse_isostring ( message . missionTime ) return None
def load_policy_config ( filters = None , prepend = True , pillar_key = 'acl' , pillarenv = None , saltenv = None , merge_pillar = True , only_lower_merge = False , revision_id = None , revision_no = None , revision_date = True , revision_date_format = '%Y/%m/%d' , test = False , commit = True , debug = False , ** kwar...
if not filters : filters = [ ] platform = _get_capirca_platform ( ) policy_config = __salt__ [ 'capirca.get_policy_config' ] ( platform , filters = filters , prepend = prepend , pillar_key = pillar_key , pillarenv = pillarenv , saltenv = saltenv , merge_pillar = merge_pillar , only_lower_merge = only_lower_merge , ...
def nice_pkg_name ( name ) : """todo : Docstring for nice _ pkg _ name : param name : arg description : type name : type description : return : : rtype :"""
logger . debug ( "%s" , name ) root , ext = os . path . splitext ( name ) logger . debug ( "root :'%s', ext: '%s'" , root , ext ) if ext in ugly_ext : logger . debug ( "remove ext %s to get %s" , ext , root ) return root logger . debug ( "no change %s" , name ) return name
def client_info ( self , client ) : """Get client info . Uses GET to / clients / < client > interface . : Args : * * client * : ( str ) Client ' s ID : Returns : ( dict ) Client dictionary"""
client = self . _client_id ( client ) response = self . _get ( url . clients_id . format ( id = client ) ) self . _check_response ( response , 200 ) return self . _create_response ( response )
def illumf ( method , target , ilusrc , et , fixref , abcorr , obsrvr , spoint ) : """Compute the illumination angles - - - phase , incidence , and emission - - - at a specified point on a target body . Return logical flags indicating whether the surface point is visible from the observer ' s position and whe...
method = stypes . stringToCharP ( method ) target = stypes . stringToCharP ( target ) ilusrc = stypes . stringToCharP ( ilusrc ) et = ctypes . c_double ( et ) fixref = stypes . stringToCharP ( fixref ) abcorr = stypes . stringToCharP ( abcorr ) obsrvr = stypes . stringToCharP ( obsrvr ) spoint = stypes . toDoubleVector...