signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def close ( self ) : """Close injector & injected Provider instances , including generators . Providers are closed in the reverse order in which they were opened , and each provider is only closed once . Providers are closed if accessed by the injector , even if a dependency is not successfully provided . As ...
if self . closed : raise RuntimeError ( '{!r} already closed' . format ( self ) ) for finalizer in reversed ( self . finalizers ) : # Note : Unable to apply injector on close method . finalizer ( ) self . closed = True self . instances . clear ( ) self . values . clear ( )
def _add_discovery_config ( self ) : """Add the Discovery configuration to our list of configs . This should only be called with self . _ config _ lock . The code here assumes the lock is held ."""
lookup_key = ( discovery_service . DiscoveryService . API_CONFIG [ 'name' ] , discovery_service . DiscoveryService . API_CONFIG [ 'version' ] ) self . _configs [ lookup_key ] = discovery_service . DiscoveryService . API_CONFIG
def _process_key ( self , key ) : """Process the given export key from redis ."""
# Handle the driver case first . if self . mode != ray . WORKER_MODE : if key . startswith ( b"FunctionsToRun" ) : with profiling . profile ( "fetch_and_run_function" ) : self . fetch_and_execute_function_to_run ( key ) # Return because FunctionsToRun are the only things that # the drive...
def _secret_event_lifecycle_cb ( conn , secret , event , detail , opaque ) : '''Secret lifecycle events handler'''
_salt_send_event ( opaque , conn , { 'secret' : { 'uuid' : secret . UUIDString ( ) } , 'event' : _get_libvirt_enum_string ( 'VIR_SECRET_EVENT_' , event ) , 'detail' : 'unknown' # currently unused } )
def descriptor_factory ( self , type_name , shard = u'lobby' , ** kwargs ) : """Creates and returns a descriptor to pass it later for starting the agent . First parameter is a type _ name representing the descirptor . Second parameter is optional ( default lobby ) . Usage : > descriptor _ factory ( ' shard ...
desc = factories . build ( type_name , shard = unicode ( shard ) , ** kwargs ) return self . _database_connection . save_document ( desc )
def _set_backup ( self , v , load = False ) : """Setter method for backup , mapped from YANG variable / mpls _ state / lsp / backup ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ backup is considered as a private method . Backends looking to populate th...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = backup . backup , is_container = 'container' , presence = False , yang_name = "backup" , rest_name = "backup" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , ext...
def update_folder_name ( self , name , update_folder_data = True ) : """Change this folder name : param str name : new name to change to : param bool update _ folder _ data : whether or not to re - fetch the data : return : Updated or Not : rtype : bool"""
if self . root : return False if not name : return False url = self . build_url ( self . _endpoints . get ( 'get_folder' ) . format ( id = self . folder_id ) ) response = self . con . patch ( url , data = { self . _cc ( 'displayName' ) : name } ) if not response : return False self . name = name if not upda...
def save ( self , path ) : """Save loss in json format"""
json . dump ( dict ( loss = self . __class__ . __name__ , params = self . hparams ) , open ( os . path . join ( path , 'loss.json' ) , 'wb' ) )
def set_simple_fault_geometry_3D ( w , src ) : """Builds a 3D polygon from a node instance"""
assert "simpleFaultSource" in src . tag geometry_node = src . nodes [ get_taglist ( src ) . index ( "simpleFaultGeometry" ) ] fault_attrs = parse_simple_fault_geometry ( geometry_node ) build_polygon_from_fault_attrs ( w , fault_attrs )
def repr_new_instance ( self , class_data ) : """Create code like this : : person = Person ( name = ' Jack ' , person _ id = 1)"""
classname = self . formatted_classname ( class_data [ "classname" ] ) instancename = self . formatted_instancename ( class_data [ "classname" ] ) arguments = list ( ) for key , value in self . sorted_dict ( class_data . get ( "metadata" , dict ( ) ) ) : arguments . append ( "%s=%r" % ( key , value ) ) return "%s = ...
def anno_parser ( func ) : "Look at params ( annotated with ` Param ` ) in func and return an ` ArgumentParser `"
p = ArgumentParser ( description = func . __doc__ ) for k , v in inspect . signature ( func ) . parameters . items ( ) : param = func . __annotations__ . get ( k , Param ( ) ) kwargs = param . kwargs if v . default != inspect . Parameter . empty : kwargs [ 'default' ] = v . default p . add_argum...
def get_conditional_uni ( cls , left_parent , right_parent ) : """Identify pair univariate value from parents . Args : left _ parent ( Edge ) : left parent right _ parent ( Edge ) : right parent Returns : tuple [ np . ndarray , np . ndarray ] : left and right parents univariate ."""
left , right , _ = cls . _identify_eds_ing ( left_parent , right_parent ) left_u = left_parent . U [ 0 ] if left_parent . L == left else left_parent . U [ 1 ] right_u = right_parent . U [ 0 ] if right_parent . L == right else right_parent . U [ 1 ] return left_u , right_u
def decrypt ( private , ciphertext , output ) : """Decrypt ciphertext with private key . Requires PRIVATE key file and the CIPHERTEXT encrypted with the corresponding public key ."""
privatekeydata = json . load ( private ) assert 'pub' in privatekeydata pub = load_public_key ( privatekeydata [ 'pub' ] ) log ( "Loading private key" ) private_key_error = "Invalid private key" assert 'key_ops' in privatekeydata , private_key_error assert "decrypt" in privatekeydata [ 'key_ops' ] , private_key_error a...
def attach ( self , ** kwargs ) : """Attach to this container . : py : meth : ` logs ` is a wrapper around this method , which you can use instead if you want to fetch / stream container output without first retrieving the entire backlog . Args : stdout ( bool ) : Include stdout . stderr ( bool ) : Incl...
return self . client . api . attach ( self . id , ** kwargs )
def get_nodes ( self , request ) : """Return menu ' s node for tags"""
nodes = [ ] nodes . append ( NavigationNode ( _ ( 'Tags' ) , reverse ( 'zinnia:tag_list' ) , 'tags' ) ) for tag in tags_published ( ) : nodes . append ( NavigationNode ( tag . name , reverse ( 'zinnia:tag_detail' , args = [ tag . name ] ) , tag . pk , 'tags' ) ) return nodes
def getRangeValues ( self , vp , verbose = None ) : """Returns a list of all available values for the Visual Property specified by the ` vp ` parameter . This method is only for Visual Properties with a Discrete Range , such as NODE _ SHAPE or EDGE _ LINE _ TYPE . Additional details on common Visual Properties ...
response = api ( url = self . ___url + 'styles/visualproperties/' + str ( vp ) + '/values' , method = "GET" , verbose = verbose , parse_params = False ) return response
def get ( self , request , bot_id , id , format = None ) : """Get TelegramBot by id serializer : TelegramBotSerializer responseMessages : - code : 401 message : Not authenticated"""
return super ( TelegramBotDetail , self ) . get ( request , bot_id , id , format )
def _parse_canonical_dbpointer ( doc ) : """Decode a JSON ( deprecated ) DBPointer to bson . dbref . DBRef ."""
dbref = doc [ '$dbPointer' ] if len ( doc ) != 1 : raise TypeError ( 'Bad $dbPointer, extra field(s): %s' % ( doc , ) ) if isinstance ( dbref , DBRef ) : dbref_doc = dbref . as_doc ( ) # DBPointer must not contain $ db in its value . if dbref . database is not None : raise TypeError ( 'Bad $dbPo...
def ungettext ( self ) : """Dispatch to the appropriate ngettext method to handle text objects . Note that under python 3 , this uses ` ngettext ( ) ` , while under python 2, it uses ` ungettext ( ) ` . This should not be used with bytestrings ."""
# pylint : disable = no - member if six . PY2 : return self . _translations . ungettext else : return self . _translations . ngettext
def _run_server ( self ) : """启动 HTTP Server"""
try : if __conf__ . DEBUG : self . _webapp . listen ( self . _port ) else : server = HTTPServer ( self . _webapp ) server . bind ( self . _port ) server . start ( 0 ) IOLoop . current ( ) . start ( ) except KeyboardInterrupt : print ( "exit ..." )
def add ( self , key ) : """Store new key in a new link at the end of the linked list"""
if key not in self . _map : self . _map [ key ] = link = _Link ( ) root = self . _root last = root . prev link . prev , link . next , link . key = last , root , key last . next = root . prev = weakref . proxy ( link )
def makelink ( self , tarinfo , targetpath ) : """Make a ( symbolic ) link called targetpath . If it cannot be created ( platform limitation ) , we try to make a copy of the referenced file instead of a link ."""
try : # For systems that support symbolic and hard links . if tarinfo . issym ( ) : os . symlink ( tarinfo . linkname , targetpath ) else : # See extract ( ) . if os . path . exists ( tarinfo . _link_target ) : os . link ( tarinfo . _link_target , targetpath ) else : ...
def add_edge ( self , u , v , weight = None ) : """Add an edge between u and v . The nodes u and v will be automatically added if they are not already in the graph . Parameters u , v : nodes Nodes can be any hashable Python object . weight : int , float ( default = None ) The weight of the edge Exam...
super ( DAG , self ) . add_edge ( u , v , weight = weight )
def gettrace ( self , burn = 0 , thin = 1 , chain = - 1 , slicing = None ) : """Return the trace . : Stochastics : - burn ( int ) : The number of transient steps to skip . - thin ( int ) : Keep one in thin . - chain ( int ) : The index of the chain to fetch . If None , return all chains . - slicing : A sl...
if slicing is None : slicing = slice ( burn , None , thin ) if chain is not None : if chain < 0 : chain = range ( self . db . chains ) [ chain ] return self . _trace [ chain ] [ slicing ] else : return concatenate ( list ( self . _trace . values ( ) ) ) [ slicing ]
def get_height_rect ( width : int , string : str ) -> int : """Return the number of lines which would be printed from these parameters . ` width ` is the width of the print boundary . ` string ` is a Unicode string which may include color control characters . . . versionadded : : 9.2"""
string_ = string . encode ( "utf-8" ) # type : bytes return int ( lib . get_height_rect2 ( width , string_ , len ( string_ ) ) )
def end_datetime ( self ) -> Optional [ datetime . datetime ] : """Returns the end date of the set of intervals , or ` ` None ` ` if empty ."""
if not self . intervals : return None return max ( [ x . end for x in self . intervals ] )
def unbounded ( self ) : """Whether solution is unbounded"""
self . _check_valid ( ) if self . _ret_val != 0 : return self . _ret_val == swiglpk . GLP_ENODFS return swiglpk . glp_get_status ( self . _problem . _p ) == swiglpk . GLP_UNBND
def validate_create_package ( ctx , opts , owner , repo , package_type , skip_errors , ** kwargs ) : """Check new package parameters via the API ."""
click . echo ( "Checking %(package_type)s package upload parameters ... " % { "package_type" : click . style ( package_type , bold = True ) } , nl = False , ) context_msg = "Failed to validate upload parameters!" with handle_api_exceptions ( ctx , opts = opts , context_msg = context_msg , reraise_on_error = skip_errors...
def show_buff ( self , pos ) : """Return the display of the instruction : rtype : string"""
buff = self . get_name ( ) + " " buff += "%x:" % self . first_key for i in self . targets : buff += " %x" % i return buff
def tuple ( self , var , cast = None , default = NOTSET ) : """: rtype : tuple"""
return self . get_value ( var , cast = tuple if not cast else ( cast , ) , default = default )
def dump_children ( self , obj ) : """Dump the siblings of a PID ."""
data , errors = PIDSchema ( many = True ) . dump ( obj . children . ordered ( 'asc' ) . all ( ) ) return data
def _parse_expression ( s ) : """Parse boolean expression containing and / or operators"""
# Converters for opeartor clauses operators = { 'and' : And , 'or' : Or , None : lambda * args : args [ 0 ] } # Pairing of end group symbols with start group symbols group_pairs = { ')' : '(' , ']' : '[' } scanner = re . compile ( r''' (\s+) | # space (\(|\[) | # group_start ...
def populateFromDirectory ( self , vcfDirectory ) : """Populates this VariantSet by examing all the VCF files in the specified directory . This is mainly used for as a convenience for testing purposes ."""
pattern = os . path . join ( vcfDirectory , "*.vcf.gz" ) dataFiles = [ ] indexFiles = [ ] for vcfFile in glob . glob ( pattern ) : dataFiles . append ( vcfFile ) indexFiles . append ( vcfFile + ".tbi" ) self . populateFromFile ( dataFiles , indexFiles )
def commit_channel ( self , channel_id ) : """commit _ channel : commits channel to Kolibri Studio Args : channel _ id ( str ) : channel ' s id on Kolibri Studio Returns : channel id and link to uploadedchannel"""
payload = { "channel_id" : channel_id , "stage" : config . STAGE , } response = config . SESSION . post ( config . finish_channel_url ( ) , data = json . dumps ( payload ) ) if response . status_code != 200 : config . LOGGER . error ( "\n\nCould not activate channel: {}\n" . format ( response . _content . decode ( ...
def month_average_temperature ( self , older_year = None , newer_year = None , include_yearly = False , minimum_days = 23 ) : '''> > station = get _ closest _ station ( 38.8572 , - 77.0369) > > station _ data = StationDataGSOD ( station ) > > station _ data . month _ average _ temperature ( 1990 , 2000 , includ...
# Take years , make them inclusive ; add minimum valid days . year_month_averages = { } year_month_counts = { } for year , data in self . parsed_data . items ( ) : if not ( older_year <= year <= newer_year ) : continue # Ignore out - of - range years easily year_month_averages [ year ] = [ 0.0 ]...
def messages ( self , query , ** kwargs ) : """https : / / api . slack . com / methods / search . messages"""
self . url = 'https://slack.com/api/search.messages' return super ( Search , self ) . search_from_url ( query , ** kwargs )
def scm_find_files ( path , scm_files , scm_dirs ) : """setuptools compatible file finder that follows symlinks - path : the root directory from which to search - scm _ files : set of scm controlled files and symlinks ( including symlinks to directories ) - scm _ dirs : set of scm controlled directories (...
realpath = os . path . normcase ( os . path . realpath ( path ) ) seen = set ( ) res = [ ] for dirpath , dirnames , filenames in os . walk ( realpath , followlinks = True ) : # dirpath with symlinks resolved realdirpath = os . path . normcase ( os . path . realpath ( dirpath ) ) def _link_not_in_scm ( n ) : ...
def send ( self , event_data ) : """Sends an event data and blocks until acknowledgement is received or operation times out . : param event _ data : The event to be sent . : type event _ data : ~ azure . eventhub . common . EventData : raises : ~ azure . eventhub . common . EventHubError if the message fail...
if self . error : raise self . error if not self . running : raise ValueError ( "Unable to send until client has been started." ) if event_data . partition_key and self . partition : raise ValueError ( "EventData partition key cannot be used with a partition sender." ) event_data . message . on_send_complet...
def download_shared_files ( job , input_args ) : """Downloads and stores shared inputs files in the FileStore input _ args : dict Dictionary of input arguments ( from main ( ) )"""
shared_files = [ 'unc.bed' , 'hg19.transcripts.fa' , 'composite_exons.bed' , 'normalize.pl' , 'rsem_ref.zip' , 'ebwt.zip' , 'chromosomes.zip' ] shared_ids = { } for f in shared_files : shared_ids [ f ] = job . addChildJobFn ( download_from_url , input_args [ f ] ) . rv ( ) if input_args [ 'config' ] or input_args [...
def connection ( self ) : # pragma : no cover """Establish LDAP connection ."""
# self . server allows us to fetch server info # ( including LDAP schema list ) if we wish to # add this feature later self . server = ldap3 . Server ( self . host , port = self . port , get_info = ldap3 . ALL ) self . conn = ldap3 . Connection ( self . server , user = self . user_dn , password = self . user_pw , auto_...
def get_fields_in_model ( instance ) : """Returns the list of fields in the given model instance . Checks whether to use the official _ meta API or use the raw data . This method excludes many to many fields . : param instance : The model instance to get the fields for : type instance : Model : return : The...
assert isinstance ( instance , Model ) # Check if the Django 1.8 _ meta API is available use_api = hasattr ( instance . _meta , 'get_fields' ) and callable ( instance . _meta . get_fields ) if use_api : return [ f for f in instance . _meta . get_fields ( ) if track_field ( f ) ] return instance . _meta . fields
def get_selected_elements_of_core_class ( self , core_element_type ) : """Returns all selected elements having the specified ` core _ element _ type ` as state element class : return : Subset of the selection , only containing elements having ` core _ element _ type ` as state element class : rtype : set"""
if core_element_type is Outcome : return self . outcomes elif core_element_type is InputDataPort : return self . input_data_ports elif core_element_type is OutputDataPort : return self . output_data_ports elif core_element_type is ScopedVariable : return self . scoped_variables elif core_element_type is...
def load_metadata_for_topics ( self , * topics ) : """Discover topic metadata and brokers Afkak internally calls this method whenever metadata is required . : param str topics : Topic names to look up . The resulting metadata includes the list of topic partitions , brokers owning those partitions , and whic...
topics = tuple ( _coerce_topic ( t ) for t in topics ) log . debug ( "%r: load_metadata_for_topics(%s)" , self , ', ' . join ( repr ( t ) for t in topics ) ) fetch_all_metadata = not topics # create the request requestId = self . _next_id ( ) request = KafkaCodec . encode_metadata_request ( self . _clientIdBytes , requ...
def search_bm25 ( cls , term , weights = None , with_score = False , score_alias = 'score' , explicit_ordering = False ) : """Full - text search for selected ` term ` using BM25 algorithm ."""
return cls . _search ( term , weights , with_score , score_alias , cls . bm25 , explicit_ordering )
def clear ( self ) : """Clear the segment . : return : None"""
for _ , frame in self . _segments . items ( ) : frame . configure ( background = self . _bg_color )
def summary ( self ) : """Return a string summary of transaction"""
return "\n" . join ( [ "Transaction:" , " When: " + self . date . strftime ( "%a %d %b %Y" ) , " Description: " + self . desc . replace ( '\n' , ' ' ) , " For amount: {}" . format ( self . amount ) , " From: {}" . format ( ", " . join ( map ( lambda x : x . account , self . src ) ) if self . src else...
def get_schema ( brain_or_object ) : """Get the schema of the content : param brain _ or _ object : A single catalog brain or content object : type brain _ or _ object : ATContentType / DexterityContentType / CatalogBrain : returns : Schema object"""
obj = get_object ( brain_or_object ) if is_portal ( obj ) : fail ( "get_schema can't return schema of portal root" ) if is_dexterity_content ( obj ) : pt = get_tool ( "portal_types" ) fti = pt . getTypeInfo ( obj . portal_type ) return fti . lookupSchema ( ) if is_at_content ( obj ) : return obj . S...
def get_dates ( feed : "Feed" , * , as_date_obj : bool = False ) -> List [ str ] : """Return a list of dates for which the given " Feed " is valid , which could be the empty list if the " Feed " has no calendar information . Parameters feed : " Feed " as _ date _ obj : boolean If ` ` True ` ` , then retur...
dates = [ ] if feed . calendar is not None and not feed . calendar . empty : if "start_date" in feed . calendar . columns : dates . append ( feed . calendar [ "start_date" ] . min ( ) ) if "end_date" in feed . calendar . columns : dates . append ( feed . calendar [ "end_date" ] . max ( ) ) if fe...
def byte_list_to_u32le_list ( data , pad = 0x00 ) : """! @ brief Convert a list of bytes to a list of 32 - bit integers ( little endian ) If the length of the data list is not a multiple of 4 , then the pad value is used for the additional required bytes ."""
res = [ ] for i in range ( len ( data ) // 4 ) : res . append ( data [ i * 4 + 0 ] | data [ i * 4 + 1 ] << 8 | data [ i * 4 + 2 ] << 16 | data [ i * 4 + 3 ] << 24 ) remainder = ( len ( data ) % 4 ) if remainder != 0 : padCount = 4 - remainder res += byte_list_to_u32le_list ( list ( data [ - remainder : ] ) ...
def get_deployment_group ( self , project , deployment_group_id , action_filter = None , expand = None ) : """GetDeploymentGroup . [ Preview API ] Get a deployment group by its ID . : param str project : Project ID or project name : param int deployment _ group _ id : ID of the deployment group . : param st...
route_values = { } if project is not None : route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' ) if deployment_group_id is not None : route_values [ 'deploymentGroupId' ] = self . _serialize . url ( 'deployment_group_id' , deployment_group_id , 'int' ) query_parameters = { } if a...
def send_script_async ( self , conn_id , data , progress_callback , callback ) : """Asynchronously send a a script to this IOTile device Args : conn _ id ( int ) : A unique identifer that will refer to this connection data ( bytes ) : the script to send to the device progress _ callback ( callable ) : A fun...
found_handle = None # Find the handle by connection id for handle , conn in self . _connections . items ( ) : if conn [ 'connection_id' ] == conn_id : found_handle = handle if found_handle is None : callback ( conn_id , self . id , False , 'Invalid connection_id' ) return services = self . _connecti...
def main ( ) : """Run ftfy as a command - line utility ."""
import argparse parser = argparse . ArgumentParser ( description = "ftfy (fixes text for you), version %s" % __version__ ) parser . add_argument ( 'filename' , default = '-' , nargs = '?' , help = 'The file whose Unicode is to be fixed. Defaults ' 'to -, meaning standard input.' ) parser . add_argument ( '-o' , '--outp...
def get_name_DID_info ( self , name , lastblock = None ) : """Given a name , find its DID ( decentralized identifier ) information . Returns { ' address ' : . . . , ' index ' : . . . } Returns None if there is no such name"""
if lastblock is None : lastblock = self . lastblock cur = self . db . cursor ( ) did_info = namedb_get_name_DID_info ( cur , name , lastblock ) if did_info is None : return None return did_info
def main ( ) : """Run check . anycast - healthchecker is a multi - threaded software and for each service check it holds a thread . If a thread dies then the service is not monitored anymore and the route for the IP associated with service it wont be withdrawn in case service goes down in the meantime ."""
arguments = docopt ( __doc__ ) config_file = '/etc/anycast-healthchecker.conf' config_dir = '/etc/anycast-healthchecker.d' config = configparser . ConfigParser ( ) config_files = [ config_file ] config_files . extend ( glob . glob ( os . path . join ( config_dir , '*.conf' ) ) ) config . read ( config_files ) try : ...
def reconnected ( self , conn ) : '''Subscribe connection and manipulate its RDY state'''
conn . sub ( self . _topic , self . _channel ) conn . rdy ( 1 )
def load ( self , loc ) : '''Load a pickled model .'''
try : w_td_c = pickle . load ( open ( loc , 'rb' ) ) except IOError : msg = ( "Missing trontagger.pickle file." ) raise MissingCorpusError ( msg ) self . model . weights , self . tagdict , self . classes = w_td_c self . model . classes = self . classes return None
def authorize ( self , authentication_request , # type : oic . oic . message . AuthorizationRequest user_id , # type : str extra_id_token_claims = None # type : Optional [ Union [ Mapping [ str , Union [ str , List [ str ] ] ] , Callable [ [ str , str ] , Mapping [ str , Union [ str , List [ str ] ] ] ] ] ) : # type : ...
custom_sub = self . userinfo [ user_id ] . get ( 'sub' ) if custom_sub : self . authz_state . subject_identifiers [ user_id ] = { 'public' : custom_sub } sub = custom_sub else : sub = self . _create_subject_identifier ( user_id , authentication_request [ 'client_id' ] , authentication_request [ 'redirect_ur...
def water ( target , temperature = 'pore.temperature' , salinity = 'pore.salinity' ) : r"""Calculates density of pure water or seawater at atmospheric pressure using Eq . ( 8 ) given by Sharqawy et . al [ 1 ] . Values at temperature higher than the normal boiling temperature are calculated at the saturation p...
T = target [ temperature ] if salinity in target . keys ( ) : S = target [ salinity ] else : S = 0 a1 = 9.9992293295E+02 a2 = 2.0341179217E-02 a3 = - 6.1624591598E-03 a4 = 2.2614664708E-05 a5 = - 4.6570659168E-08 b1 = 8.0200240891E-01 b2 = - 2.0005183488E-03 b3 = 1.6771024982E-05 b4 = - 3.0600536746E-08 b5 = - ...
def set_cover_tilt_position ( self , position , channel = None ) : """Seek a specific value by specifying a float ( ) from 0.0 to 1.0."""
try : position = float ( position ) except Exception as err : LOG . debug ( "HelperActorBlindTilt.set_level_2: Exception %s" % ( err , ) ) return False level = self . getWriteData ( "LEVEL" , channel ) self . writeNodeData ( "LEVEL_2" , position , channel ) # set level after level _ 2 to have level _ 2 upda...
def start_in_keepedalive_processes ( obj , nb_process ) : """Start nb _ process and keep them alive . Send job to them multiple times , then close thems ."""
processes = [ ] readers_pipes = [ ] writers_pipes = [ ] for i in range ( nb_process ) : # Start process with Pipes for communicate local_read_pipe , local_write_pipe = Pipe ( duplex = False ) process_read_pipe , process_write_pipe = Pipe ( duplex = False ) readers_pipes . append ( local_read_pipe ) writ...
def write_model_map ( self , model_name , name = None ) : """Save the counts model map to a FITS file . Parameters model _ name : str String that will be append to the name of the output file . name : str Name of the component . Returns"""
maps = [ c . write_model_map ( model_name , name ) for c in self . components ] outfile = os . path . join ( self . workdir , 'mcube_%s.fits' % ( model_name ) ) mmap = Map . from_geom ( self . geom ) for m in maps : mmap . coadd ( m ) mmap . write ( outfile , overwrite = True , conv = 'fgst-ccube' ) return [ mmap ]...
def add_interaction ( self , u , v , t = None , e = None ) : """Add an interaction between u and v at time t vanishing ( optional ) at time e . The nodes u and v will be automatically added if they are not already in the graph . Parameters u , v : nodes Nodes can be , for example , strings or numbers . ...
if t is None : raise nx . NetworkXError ( "The t argument must be specified." ) if u not in self . _node : self . _adj [ u ] = self . adjlist_inner_dict_factory ( ) self . _node [ u ] = { } if v not in self . _node : self . _adj [ v ] = self . adjlist_inner_dict_factory ( ) self . _node [ v ] = { } ...
def match_range ( self , el , condition ) : """Match range . Behavior is modeled after what we see in browsers . Browsers seem to evaluate if the value is out of range , and if not , it is in range . So a missing value will not evaluate out of range ; therefore , value is in range . Personally , I feel like...
out_of_range = False itype = self . get_attribute_by_name ( el , 'type' ) . lower ( ) mn = self . get_attribute_by_name ( el , 'min' , None ) if mn is not None : mn = Inputs . parse_value ( itype , mn ) mx = self . get_attribute_by_name ( el , 'max' , None ) if mx is not None : mx = Inputs . parse_value ( itype...
def chk_genes ( self , study , pop , assoc = None ) : """Check gene sets ."""
if len ( pop ) < len ( study ) : exit ( "\nERROR: The study file contains more elements than the population file. " "Please check that the study file is a subset of the population file.\n" ) # check the fraction of genomic ids that overlap between study and population overlap = self . get_overlap ( study , pop ) if...
def load_example ( name ) : """Load an example problem by name . Parameters name : string ( e . g . ' airfoil ' ) Name of the example to load Notes Each example is stored in a dictionary with the following keys : - ' A ' : sparse matrix - ' B ' : near - nullspace candidates - ' vertices ' : dense ar...
if name not in example_names : raise ValueError ( 'no example with name (%s)' % name ) else : return loadmat ( os . path . join ( example_dir , name + '.mat' ) , struct_as_record = True )
def _get_all_forums ( self ) : """Returns all forums ."""
if not hasattr ( self , '_all_forums' ) : self . _all_forums = list ( Forum . objects . all ( ) ) return self . _all_forums
def addDataProducts ( self , dps ) : """Adds new data products to listview . dps is a list of DP objects . Returns True if new ( non - quiet ) DPs are added , or if existing non - quiet dps are updated . ( this usually tells the main window to wake up )"""
busy = Purr . BusyIndicator ( ) wakeup = False # build up list of items to be inserted itemlist = [ ] for dp in dps : item = self . dpitems . get ( dp . sourcepath ) # If item already exists , it needs to be moved to its new position # If takeTopLevelItem ( ) returns None , then item was already removed ( t...
def main ( md = None , filename = None , cols = None , theme = None , c_theme = None , bg = None , c_no_guess = None , display_links = None , from_txt = None , do_html = None , no_colors = None , ** kw ) : """md is markdown string . alternatively we use filename and read"""
args = locals ( ) if not md : if not filename : print 'Using sample markdown:' make_sample ( ) md = args [ 'md' ] = md_sample print md print print 'Styling Result' else : with open ( filename ) as f : md = f . read ( ) global term_columns # sty...
def ensureiterable ( value , iterable = list , exclude = None ) : """Convert a value into an iterable if it is not . : param object value : object to convert : param type iterable : iterable type to apply ( default : list ) : param type / tuple exclude : types to not convert : Example : > > > ensureiterab...
result = value if not isiterable ( value , exclude = exclude ) : result = [ value ] result = iterable ( result ) else : result = iterable ( value ) return result
def load ( * fps , missing = Missing . silent ) : """Read a ` . Configuration ` instance from file - like objects . : param fps : file - like objects ( supporting ` ` . read ( ) ` ` ) : param missing : policy to be used when a configured key is missing , either as a ` . Missing ` instance or a default value ...
return Configuration ( * ( yaml . safe_load ( fp . read ( ) ) for fp in fps ) , missing = missing )
def countRemovedDataProducts ( self ) : """Returns number of DPs marked for removal"""
return len ( [ item for item , dp in self . wdplv . getItemDPList ( ) if dp . policy == "remove" ] )
def mat2euler ( rmat , axes = "sxyz" ) : """Converts given rotation matrix to euler angles in radian . Args : rmat : 3x3 rotation matrix axes : One of 24 axis sequences as string or encoded tuple Returns : converted euler angles in radian vec3 float"""
try : firstaxis , parity , repetition , frame = _AXES2TUPLE [ axes . lower ( ) ] except ( AttributeError , KeyError ) : firstaxis , parity , repetition , frame = axes i = firstaxis j = _NEXT_AXIS [ i + parity ] k = _NEXT_AXIS [ i - parity + 1 ] M = np . array ( rmat , dtype = np . float32 , copy = False ) [ : 3...
def export_csv ( self , path , idx = None , header = None , formatted = False , sort_idx = True , fmt = '%.18e' ) : """Export to a csv file Parameters path : str path of the csv file to save idx : None or array - like , optional the indices of the variables to export . Export all by default header : Non...
if not idx : idx = self . _idx if not header : header = self . get_header ( idx , formatted = formatted ) assert len ( idx ) == len ( header ) , "Idx length does not match header length" body = self . get_values ( idx ) with open ( path , 'w' ) as fd : fd . write ( ',' . join ( header ) + '\n' ) np . sa...
def add_region_location ( self , region , locations = None , use_live = True ) : # type : ( str , Optional [ List [ str ] ] , bool ) - > bool """Add all countries in a region . If a 3 digit UNStats M49 region code is not provided , value is parsed as a region name . If any country is already added , it is ignored...
return self . add_country_locations ( Country . get_countries_in_region ( region , exception = HDXError , use_live = use_live ) , locations = locations )
def _dropout_sparse_coo_matrix ( sparse_matrix , rate , min_dropout_rate , max_dropout_rate ) : """Drop values from a sparse matrix encoded as a SciPy coo matrix . Args : sparse _ matrix : a SciPy coo sparse matrix . rate : if rate > 0 then non - zero elements of the input matrix will be droped uniformly at...
if min_dropout_rate is None : min_dropout_rate = FLAGS . min_dropout_rate if max_dropout_rate is None : max_dropout_rate = FLAGS . max_dropout_rate if min_dropout_rate > max_dropout_rate : raise ValueError ( "min_dropout_rate (%f) should be less or equal to " "max_dropout_rate (%f)" % ( min_dropout_rate , m...
def isnat ( val ) : """Checks if the value is a NaT . Should only be called on datetimelike objects ."""
if ( isinstance ( val , ( np . datetime64 , np . timedelta64 ) ) or ( isinstance ( val , np . ndarray ) and val . dtype . kind == 'M' ) ) : if numpy_version >= '1.13' : return np . isnat ( val ) else : return val . view ( 'i8' ) == nat_as_integer elif pd and val is pd . NaT : return True eli...
def _cleanup_channel ( self , channel_id ) : """Remove the the channel from the list of available channels . : param int channel _ id : Channel id : return :"""
with self . lock : if channel_id not in self . _channels : return del self . _channels [ channel_id ]
def _reroot ( self ) : '''Run the re - rooting algorithm in the Rerooter class .'''
rerooter = Rerooter ( ) self . tree = rerooter . reroot_by_tree ( self . reference_tree , self . tree )
def move_user ( self , user_id , group_id ) : """移动用户分组 详情请参考 http : / / mp . weixin . qq . com / wiki / 0/56d992c605a97245eb7e617854b169fc . html : param user _ id : 用户 ID , 可以是单个或者列表 , 为列表时为批量移动用户分组 : param group _ id : 分组 ID : return : 返回的 JSON 数据包 使用示例 : : from wechatpy import WeChatClient clien...
data = { 'to_groupid' : group_id } if isinstance ( user_id , ( tuple , list ) ) : endpoint = 'groups/members/batchupdate' data [ 'openid_list' ] = user_id else : endpoint = 'groups/members/update' data [ 'openid' ] = user_id return self . _post ( endpoint , data = data )
def sphericalAngSep ( ra0 , dec0 , ra1 , dec1 , radians = False ) : """Compute the spherical angular separation between two points on the sky . / / Taken from http : / / www . movable - type . co . uk / scripts / gis - faq - 5.1 . html NB : For small distances you can probably use sqrt ( dDec * * 2 + cos ^ ...
if radians == False : ra0 = np . radians ( ra0 ) dec0 = np . radians ( dec0 ) ra1 = np . radians ( ra1 ) dec1 = np . radians ( dec1 ) deltaRa = ra1 - ra0 deltaDec = dec1 - dec0 val = haversine ( deltaDec ) val += np . cos ( dec0 ) * np . cos ( dec1 ) * haversine ( deltaRa ) val = min ( 1 , np . sqrt ( v...
def get_handler ( progname , address = None , proto = None , facility = None , fmt = None , datefmt = None , ** _ ) : """Helper function to create a Syslog handler . See ` ulogger . syslog . SyslogHandlerBuilder ` for arguments and supported keyword arguments . Returns : ( obj ) : Instance of ` logging . Sy...
builder = SyslogHandlerBuilder ( progname , address = address , proto = proto , facility = facility , fmt = fmt , datefmt = datefmt ) return builder . get_handler ( )
def dispatch ( self ) : """Dispatch http request to registerd commands . Example : : slack = Slack ( app ) app . add _ url _ rule ( ' / ' , view _ func = slack . dispatch )"""
from flask import request method = request . method data = request . args if method == 'POST' : data = request . form token = data . get ( 'token' ) team_id = data . get ( 'team_id' ) command = data . get ( 'command' ) or data . get ( 'trigger_word' ) if isinstance ( command , string_types ) : command = command...
def topk ( self , column_name , k = 10 , reverse = False ) : """Get top k rows according to the given column . Result is according to and sorted by ` column _ name ` in the given order ( default is descending ) . When ` k ` is small , ` topk ` is more efficient than ` sort ` . Parameters column _ name : str...
if type ( column_name ) is not str : raise TypeError ( "column_name must be a string" ) sf = self [ self [ column_name ] . is_topk ( k , reverse ) ] return sf . sort ( column_name , ascending = reverse )
def inFootprint ( self , pixels , nside = None ) : """Open each valid filename for the set of pixels and determine the set of subpixels with valid data ."""
if np . isscalar ( pixels ) : pixels = np . array ( [ pixels ] ) if nside is None : nside = self . nside_likelihood inside = np . zeros ( len ( pixels ) , dtype = 'bool' ) if not self . nside_catalog : catalog_pix = [ 0 ] else : catalog_pix = superpixel ( pixels , nside , self . nside_catalog ) cata...
def xsrf_token ( self ) -> bytes : """The XSRF - prevention token for the current user / session . To prevent cross - site request forgery , we set an ' _ xsrf ' cookie and include the same ' _ xsrf ' value as an argument with all POST requests . If the two do not match , we reject the form submission as a ...
if not hasattr ( self , "_xsrf_token" ) : version , token , timestamp = self . _get_raw_xsrf_token ( ) output_version = self . settings . get ( "xsrf_cookie_version" , 2 ) cookie_kwargs = self . settings . get ( "xsrf_cookie_kwargs" , { } ) if output_version == 1 : self . _xsrf_token = binascii ...
def set ( self , status_item , status ) : """sets the status item to the passed in paramaters args : status _ item : the name if the item to set status : boolean value to set the item"""
lg = logging . getLogger ( "%s.%s" % ( self . ln , inspect . stack ( ) [ 0 ] [ 3 ] ) ) lg . setLevel ( self . log_level ) sparql = ''' DELETE {{ kdr:{0} kds:{1} ?o }} INSERT {{ kdr:{0} kds:{1} "{2}"^^xsd:boolean }} WHERE {{ ...
def GetAmi ( ec2 , ami_spec ) : """Get the boto ami object given a AmiSpecification object ."""
images = ec2 . get_all_images ( owners = [ ami_spec . owner_id ] ) requested_image = None for image in images : if image . name == ami_spec . ami_name : requested_image = image break return requested_image
def query_balance ( self , asset : str , b58_address : str ) -> int : """This interface is used to query the account ' s ONT or ONG balance . : param asset : a string which is used to indicate which asset we want to check the balance . : param b58 _ address : a base58 encode account address . : return : accou...
raw_address = Address . b58decode ( b58_address ) . to_bytes ( ) contract_address = self . get_asset_address ( asset ) invoke_code = build_native_invoke_code ( contract_address , b'\x00' , "balanceOf" , raw_address ) tx = Transaction ( 0 , 0xd1 , int ( time ( ) ) , 0 , 0 , None , invoke_code , bytearray ( ) , list ( ) ...
def cmd ( send , msg , _ ) : """Gets a slogan . Syntax : { command } [ text ]"""
if not msg : msg = textutils . gen_word ( ) send ( textutils . gen_slogan ( msg ) )
def find ( max_depth = 3 ) : """Returns the path of a Pipfile in parent directories ."""
i = 0 for c , d , f in walk_up ( os . getcwd ( ) ) : i += 1 if i < max_depth : if 'Pipfile' : p = os . path . join ( c , 'Pipfile' ) if os . path . isfile ( p ) : return p raise RuntimeError ( 'No Pipfile found!' )
def get ( self , r ) : """Returns precomputed value of the given expression"""
if r is None : return None if r . lower ( ) == '(sp)' and self . stack : return self . stack [ - 1 ] if r [ : 1 ] == '(' : return self . mem [ r [ 1 : - 1 ] ] r = r . lower ( ) if is_number ( r ) : return str ( valnum ( r ) ) if not is_register ( r ) : return None return self . regs [ r ]
def tachogram ( data , sample_rate , signal = False , in_seconds = False , out_seconds = False ) : """Function for generation of ECG Tachogram . Parameters data : list ECG signal or R peak list . When the input is a raw signal the input flag signal should be True . sample _ rate : int Sampling frequency...
if signal is False : # data is a list of R peaks position . data_copy = data time_axis = numpy . array ( data ) # . cumsum ( ) if out_seconds is True and in_seconds is False : time_axis = time_axis / sample_rate else : # data is a ECG signal . # Detection of R peaks . data_copy = detect_r_pe...
def example ( self ) -> str : """Same as str ( self ) , except the color codes are actually used ."""
if self . rgb_mode : colorcode = '\033[38;2;{};{};{}m' . format ( * self . rgb ) else : colorcode = '\033[38;5;{}m' . format ( self . code ) return '{code}{s}\033[0m' . format ( code = colorcode , s = self )
def _ensure_session ( self , session = None ) : """If provided session is None , lend a temporary session ."""
if session : return session try : # Don ' t make implicit sessions causally consistent . Applications # should always opt - in . return self . __start_session ( True , causal_consistency = False ) except ( ConfigurationError , InvalidOperation ) : # Sessions not supported , or multiple users authenticated . ...
def _execute_after_prepare ( self , host , connection , pool , response ) : """Handle the response to our attempt to prepare a statement . If it succeeded , run the original query again against the same host ."""
if pool : pool . return_connection ( connection ) if self . _final_exception : return if isinstance ( response , ResultMessage ) : if response . kind == RESULT_KIND_PREPARED : if self . prepared_statement : # result metadata is the only thing that could have # changed from an alter ...
def _get_full_model_smt_script ( self , constraints = ( ) , variables = ( ) ) : """Returns a SMT script that declare all the symbols and constraint and checks their satisfiability ( check - sat ) : param extra - constraints : list of extra constraints that we want to evaluate only in the scope of this call ...
smt_script = '(set-logic ALL)\n' smt_script += '(set-option :produce-models true)\n' smt_script += self . _smtlib_exprs ( variables ) smt_script += self . _smtlib_exprs ( constraints ) smt_script += '(check-sat)\n' smt_script += '(get-model)\n' return smt_script
def describe_table ( cls , db : DATABASE_SUPPORTER_FWD_REF , table : str ) -> List [ List [ Any ] ] : """Returns details on a specific table ."""
raise RuntimeError ( _MSG_NO_FLAVOUR )
def stash ( self , storage , url ) : """Stores the uploaded file in a temporary storage location ."""
result = { } if self . is_valid ( ) : upload = self . cleaned_data [ 'upload' ] name = storage . save ( upload . name , upload ) result [ 'filename' ] = os . path . basename ( name ) try : result [ 'url' ] = storage . url ( name ) except NotImplementedError : result [ 'url' ] = None ...
def get_translations ( self ) : """Returns the correct gettext translations that should be used for this request . This will never fail and return a dummy translation object if used outside of the request or if a translation cannot be found ."""
ctx = stack . top if ctx is None : return NullTranslations ( ) locale = get_locale ( ) cache = self . get_translations_cache ( ctx ) translations = cache . get ( str ( locale ) ) if translations is None : translations_dir = self . get_translations_path ( ctx ) translations = Translations . load ( translatio...
def _combine_sets ( self , sets , final_set ) : """Given a list of set , combine them to create the final set that will be used to make the final redis call . If we have a least a sorted set , use zinterstore insted of sunionstore"""
if self . _has_sortedsets : self . cls . get_connection ( ) . zinterstore ( final_set , list ( sets ) ) else : final_set = super ( ExtendedCollectionManager , self ) . _combine_sets ( sets , final_set ) return final_set