signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _msg_create_line ( self , msg , data , key ) : """Create a new line to the Quickview ."""
ret = [ ] ret . append ( self . curse_add_line ( msg ) ) ret . append ( self . curse_add_line ( data . pre_char , decoration = 'BOLD' ) ) ret . append ( self . curse_add_line ( data . get ( ) , self . get_views ( key = key , option = 'decoration' ) ) ) ret . append ( self . curse_add_line ( data . post_char , decoratio...
def update_dict ( d , u = None , depth = - 1 , take_new = True , default_mapping_type = dict , prefer_update_type = False , copy = False ) : """Recursively merge ( union or update ) dict - like objects ( Mapping ) to the specified depth . > > > update _ dict ( { ' k1 ' : { ' k2 ' : 2 } } , { ' k1 ' : { ' k2 ' : {...
u = u or { } orig_mapping_type = type ( d ) if prefer_update_type and isinstance ( u , Mapping ) : dictish = type ( u ) elif isinstance ( d , Mapping ) : dictish = orig_mapping_type else : dictish = default_mapping_type if copy : d = dictish ( d ) for k , v in viewitems ( u ) : if isinstance ( d , M...
def get_method_docstring ( cls , method_name ) : """return method docstring if method docstring is empty we get docstring from parent : param method : : type method : : return : : rtype :"""
method = getattr ( cls , method_name , None ) if method is None : return docstrign = inspect . getdoc ( method ) if docstrign is None : for base in cls . __bases__ : docstrign = get_method_docstring ( base , method_name ) if docstrign : return docstrign else : return None...
def push_call_history_item ( self , state , call_type , state_for_scoped_data , input_data = None ) : """Adds a new call - history - item to the history item list A call history items stores information about the point in time where a method ( entry , execute , exit ) of certain state was called . : param sta...
last_history_item = self . get_last_history_item ( ) from rafcon . core . states . library_state import LibraryState # delayed imported on purpose if isinstance ( state_for_scoped_data , LibraryState ) : state_for_scoped_data = state_for_scoped_data . state_copy return_item = CallItem ( state , last_history_item , ...
def pool_attr_remove ( arg , opts , shell_opts ) : """Remove attributes from a prefix"""
res = Pool . list ( { 'name' : arg } ) if len ( res ) < 1 : print ( "No pool with name '%s' found." % arg , file = sys . stderr ) sys . exit ( 1 ) p = res [ 0 ] for key in opts . get ( 'extra-attribute' , [ ] ) : if key not in p . avps : print ( "Unable to remove extra-attribute: '%s' does not exist...
def vectors ( self , failed = False ) : """Get vectors in the network . failed = { False , True , " all " } To get the vectors to / from to a specific node , see Node . vectors ( ) ."""
if failed not in [ "all" , False , True ] : raise ValueError ( "{} is not a valid vector failed" . format ( failed ) ) if failed == "all" : return Vector . query . filter_by ( network_id = self . id ) . all ( ) else : return Vector . query . filter_by ( network_id = self . id , failed = failed ) . all ( )
def digit_sum ( numbers ) : """This function calculates the sum of individual digits in each number from a provided list . Args : numbers : A list of numbers Returns : An integer that is a sum of all individual digits in the list of numbers Examples : > > > digit _ sum ( [ 10 , 2 , 56 ] ) 14 > > > d...
return sum ( int ( digit ) for num in numbers for digit in str ( num ) if digit . isnumeric ( ) )
def reject ( self , * , requeue = True ) : """Reject the message . : keyword bool requeue : if true , the broker will attempt to requeue the message and deliver it to an alternate consumer ."""
self . sender . send_BasicReject ( self . delivery_tag , requeue )
def error ( self , msg ) : """Callback run when a recoverable parsing error occurs"""
self . _error = True self . _progress . printMsg ( 'XML parse error: %s' % msg , error = True )
def _take_action ( self ) : """Determines whether to perform the action or not . Checks whether or not an action should be taken . This is determined by the truthy value for the unless parameter . If unless is a callback method , it will be invoked with no parameters in order to determine whether or not the...
# Do the action if there isn ' t an unless override . if self . unless is None : return True # Invoke the callback if there is one . if hasattr ( self . unless , '__call__' ) : return not self . unless ( ) return not self . unless
def _parse_arg_list ( arglist ) : """Parses a list of arguments . Arguments are expected to be split by a comma , surrounded by any amount of whitespace . Arguments are then run through Python ' s eval ( ) method ."""
args = [ ] for arg in arglist . split ( ',' ) : arg = arg . strip ( ) if arg : # string is not empty args . append ( eval ( arg ) ) return args
def get_args ( self , client ) : """Builds final set of XML - RPC method arguments based on the method ' s arguments , any default arguments , and their defined respective ordering ."""
default_args = self . default_args ( client ) if self . method_args or self . optional_args : optional_args = getattr ( self , 'optional_args' , tuple ( ) ) args = [ ] for arg in ( self . method_args + optional_args ) : if hasattr ( self , arg ) : obj = getattr ( self , arg ) ...
def ls_demux ( sel , ls_di , lsls_do ) : """Demultiplexes an input signal structure to list of output structures . A structure is represented by a list of signals : [ signal _ 1 , signal _ 2 , . . . , signal _ n ] lsls _ do [ sel ] [ 0 ] = ls _ di [ 0] lsls _ do [ sel ] [ 1 ] = ls _ di [ 1] lsls _ do [ sel ...
N = len ( ls_di ) lsls_out = [ list ( x ) for x in zip ( * lsls_do ) ] return [ demux ( sel , ls_di [ i ] , lsls_out [ i ] ) for i in range ( N ) ]
def _summary ( self , name , tensor ) : """Create a scalar or histogram summary matching the rank of the tensor . Args : name : Name for the summary . tensor : Tensor to summarize . Returns : Summary tensor ."""
if tensor . shape . ndims == 0 : return tf . summary . scalar ( name , tensor ) else : return tf . summary . histogram ( name , tensor )
def put ( self , item : _T , timeout : Union [ float , datetime . timedelta ] = None ) -> "Future[None]" : """Put an item into the queue , perhaps waiting until there is room . Returns a Future , which raises ` tornado . util . TimeoutError ` after a timeout . ` ` timeout ` ` may be a number denoting a time (...
future = Future ( ) # type : Future [ None ] try : self . put_nowait ( item ) except QueueFull : self . _putters . append ( ( item , future ) ) _set_timeout ( future , timeout ) else : future . set_result ( None ) return future
def listWorkerTypeSummaries ( self , * args , ** kwargs ) : """List worker types with details Return a list of worker types , including some summary information about current capacity for each . While this list includes all defined worker types , there may be running EC2 instances for deleted worker types tha...
return self . _makeApiCall ( self . funcinfo [ "listWorkerTypeSummaries" ] , * args , ** kwargs )
def waitUntilMaybeAvailable ( self , owner , access ) : """Fire when the lock * might * be available . The caller will need to check with isAvailable ( ) when the deferred fires . This loose form is used to avoid deadlocks . If we were interested in a stronger form , this would be named ' waitUntilAvailable '...
debuglog ( "%s waitUntilAvailable(%s)" % ( self , owner ) ) assert isinstance ( access , LockAccess ) if self . isAvailable ( owner , access ) : return defer . succeed ( self ) d = defer . Deferred ( ) # Are we already in the wait queue ? w = [ i for i , w in enumerate ( self . waiting ) if w [ 0 ] is owner ] if w ...
def stage_redis ( self , variable , data ) : """Stage data in Redis . Args : variable ( str ) : The Redis variable name . data ( dict | list | str ) : The data to store in Redis ."""
if isinstance ( data , int ) : data = str ( data ) # handle binary if variable . endswith ( 'Binary' ) : try : data = base64 . b64decode ( data ) except binascii . Error : msg = 'The Binary staging data for variable {} is not properly base64 encoded.' msg = msg . format ( variable ) ...
def Routine ( coroutine , scheduler , asyncStart = True , container = None , manualStart = False , daemon = False ) : """This wraps a normal coroutine to become a VLCP routine . Usually you do not need to call this yourself ; ` container . start ` and ` container . subroutine ` calls this automatically ."""
def run ( ) : iterator = _await ( coroutine ) iterself = yield if manualStart : yield try : if asyncStart : scheduler . yield_ ( iterself ) yield if container is not None : container . currentroutine = iterself if daemon : s...
def detect_version ( basedir , compiler = None , ** compiler_attrs ) : """Compile , link & execute a test program , in empty directory ` basedir ` . The C compiler will be updated with any keywords given via setattr . Parameters basedir : path The location where the test program will be compiled and run c...
if compiler is None : compiler = get_default_compiler ( ) cfile = pjoin ( basedir , 'vers.cpp' ) shutil . copy ( pjoin ( os . path . dirname ( __file__ ) , 'vers.cpp' ) , cfile ) # check if we need to link against Realtime Extensions library if sys . platform . startswith ( 'linux' ) : cc = ccompiler . new_comp...
def register ( self , event_name ) : """Decorator , Registers the decorated function as a callback for the ` event _ name ` given . : param event _ name : The name of the event to register for . Example : > > > callbacks = Callbacks ( ) > > > @ callbacks . register ( " my _ event " ) . . . def hello (...
def registrar ( func ) : self . callbacks [ event_name ] . append ( func ) return func return registrar
def nb_cluster ( data , k , P_init = None , R_init = None , assignments = None , means = None , max_iters = 10 ) : """Performs negative binomial clustering on the given data . If some genes have mean > variance , then these genes are fitted to a Poisson distribution . Args : data ( array ) : genes x cells k (...
genes , cells = data . shape if P_init is None : P_init = np . random . random ( ( genes , k ) ) if R_init is None : R_init = np . random . randint ( 1 , data . max ( ) , ( genes , k ) ) R_init = R_init . astype ( float ) if assignments is None : _ , assignments = kmeans_pp ( data , k , means ) means = ...
def load_key ( pubkey ) : """Load public RSA key , with work - around for keys using incorrect header / footer format . Read more about RSA encryption with cryptography : https : / / cryptography . io / latest / hazmat / primitives / asymmetric / rsa /"""
try : return load_pem_public_key ( pubkey . encode ( ) , default_backend ( ) ) except ValueError : # workaround for https : / / github . com / travis - ci / travis - api / issues / 196 pubkey = pubkey . replace ( 'BEGIN RSA' , 'BEGIN' ) . replace ( 'END RSA' , 'END' ) return load_pem_public_key ( pubkey . e...
def from_hex ( cls , h , space , assignment_class = 'self' ) : """Produce a TopNumber , with a length to match the given assignment class , based on an input hex string . This can be used to create TopNumbers from a hash of a string ."""
from math import log # Use the ln ( N ) / ln ( base ) trick to find the right number of hext digits # to use hex_digits = int ( round ( log ( 62 ** TopNumber . DLEN . DATASET_CLASSES [ assignment_class ] ) / log ( 16 ) , 0 ) ) i = int ( h [ : hex_digits ] , 16 ) return TopNumber ( space , i , assignment_class = assignm...
async def _nodes_found ( self , responses ) : """Handle the result of an iteration in _ find ."""
toremove = [ ] found_values = [ ] for peerid , response in responses . items ( ) : response = RPCFindResponse ( response ) if not response . happened ( ) : toremove . append ( peerid ) elif response . has_value ( ) : found_values . append ( response . get_value ( ) ) else : peer ...
def get_subj_alt_name ( peer_cert ) : """Given an PyOpenSSL certificate , provides all the subject alternative names ."""
# Pass the cert to cryptography , which has much better APIs for this . if hasattr ( peer_cert , "to_cryptography" ) : cert = peer_cert . to_cryptography ( ) else : # This is technically using private APIs , but should work across all # relevant versions before PyOpenSSL got a proper API for this . cert = _Cert...
def update_default ( self , new_default , respect_none = False ) : """Update our current default with the new _ default . Args : new _ default : New default to set . respect _ none : Flag to determine if ` ` None ` ` is a valid value ."""
if new_default is not None : self . default = new_default elif new_default is None and respect_none : self . default = None
def verify ( self , signed ) : '''Recover the message ( digest ) from the signature using the public key : param str signed : The signature created with the private key : rtype : str : return : The message ( digest ) recovered from the signature , or an empty string if the decryption failed'''
# Allocate a buffer large enough for the signature . Freed by ctypes . buf = create_string_buffer ( libcrypto . RSA_size ( self . _rsa ) ) signed = salt . utils . stringutils . to_bytes ( signed ) size = libcrypto . RSA_public_decrypt ( len ( signed ) , signed , buf , self . _rsa , RSA_X931_PADDING ) if size < 0 : ...
def get_concrete_model ( model ) : """Get model defined in Meta . : param str or django . db . models . Model model : : return : model or None : rtype django . db . models . Model or None : : raise ValueError : model is not found or abstract"""
if not ( inspect . isclass ( model ) and issubclass ( model , models . Model ) ) : model = get_model_by_name ( model ) return model
def _update_intersection ( dict1 , dict2 , ** kwargs ) : '''dict1 = { 1 : ' a ' , 2 : ' b ' , 3 : ' c ' , 4 : ' d ' } dict2 = { 5 : ' u ' , 2 : ' v ' , 3 : ' w ' , 6 : ' x ' , 7 : ' y ' } _ update _ intersection ( dict1 , dict2) pobj ( dict1) pobj ( dict2)'''
if ( 'deepcopy' in kwargs ) : deepcopy = kwargs [ 'deepcopy' ] else : deepcopy = 1 if ( deepcopy == 1 ) : dict1 = copy . deepcopy ( dict1 ) else : pass for key in dict2 : if ( key in dict1 ) : dict1 [ key ] = dict2 [ key ] return ( dict1 )
def get_content_type ( self ) : """mime type of the attachment part"""
ctype = self . part . get_content_type ( ) # replace underspecified mime description by a better guess if ctype in [ 'octet/stream' , 'application/octet-stream' , 'application/octetstream' ] : ctype = guess_mimetype ( self . get_data ( ) ) return ctype
def setButtonText ( self , which , text ) : """Sets the display text for the inputed button to the given text . : param which | < XOverlayWizard . WizardButton > text | < str >"""
try : self . _buttons [ which ] . setText ( text ) except KeyError : pass
def uriref_matches_iriref ( v1 : URIRef , v2 : Union [ str , ShExJ . IRIREF ] ) -> bool : """Compare : py : class : ` rdflib . URIRef ` value with : py : class : ` ShExJ . IRIREF ` value"""
return str ( v1 ) == str ( v2 )
def unwrap ( obj , attr ) : """Will unwrap a ` wrapt ` attribute : param obj : base object : param attr : attribute on ` obj ` to unwrap"""
f = getattr ( obj , attr , None ) if f and isinstance ( f , wrapt . ObjectProxy ) and hasattr ( f , '__wrapped__' ) : setattr ( obj , attr , f . __wrapped__ )
def clause_texts ( self ) : """The texts of ` ` clauses ` ` multilayer elements . Non - consequent spans are concatenated with space character by default . Use : py : meth : ` ~ estnltk . text . Text . texts ` method to supply custom separators ."""
if not self . is_tagged ( CLAUSES ) : self . tag_clauses ( ) return self . texts ( CLAUSES )
def update_fact ( self , fact_id , fact , temporary_activity = False ) : """Update fact values . See add _ fact for rules . Update is performed via remove / insert , so the fact _ id after update should not be used anymore . Instead use the ID from the fact dict that is returned by this function"""
start_time = timegm ( ( fact . start_time or dt . datetime . now ( ) ) . timetuple ( ) ) end_time = fact . end_time or 0 if end_time : end_time = timegm ( end_time . timetuple ( ) ) new_id = self . conn . UpdateFact ( fact_id , fact . serialized_name ( ) , start_time , end_time , temporary_activity ) return new_id
def LinShuReductionFactor ( axiPot , R , sigmar , nonaxiPot = None , k = None , m = None , OmegaP = None ) : """NAME : LinShuReductionFactor PURPOSE : Calculate the Lin & Shu ( 1966 ) reduction factor : the reduced linear response of a kinematically - warm stellar disk to a perturbation INPUT : axiPot - T...
axiPot = flatten ( axiPot ) from galpy . potential import omegac , epifreq if nonaxiPot is None and ( OmegaP is None or k is None or m is None ) : raise IOError ( "Need to specify either nonaxiPot= or m=, k=, OmegaP= for LinShuReductionFactor" ) elif not nonaxiPot is None : OmegaP = nonaxiPot . OmegaP ( ) k...
def command_runner ( shell_command , force_rerun_flag , outfile_checker , cwd = None , silent = False ) : """Run a shell command with subprocess , with additional options to check if output file exists and printing stdout . Args : shell _ command ( str ) : Command as it would be formatted in the command - line ...
program_and_args = shlex . split ( shell_command ) # Check if program is installed if not program_exists ( program_and_args [ 0 ] ) : raise OSError ( '{}: program not installed' . format ( program_and_args [ 0 ] ) ) # Format outfile if working in cwd if cwd : # TODO : should this be done , or should user explicitly...
def syllabify_ipa ( self , word ) : """Parses IPA string : param word : word to be syllabified"""
word = word [ 1 : - 1 ] word = '' . join ( l for l in unicodedata . normalize ( 'NFD' , word ) if unicodedata . category ( l ) != 'Mn' ) return self . syllabify_ssp ( word )
async def server_reflexive_candidate ( protocol , stun_server ) : """Query STUN server to obtain a server - reflexive candidate ."""
# lookup address loop = asyncio . get_event_loop ( ) stun_server = ( await loop . run_in_executor ( None , socket . gethostbyname , stun_server [ 0 ] ) , stun_server [ 1 ] ) # perform STUN query request = stun . Message ( message_method = stun . Method . BINDING , message_class = stun . Class . REQUEST ) response , _ =...
def make_epsilons ( matrix , seed , correlation ) : """Given a matrix N * R returns a matrix of the same shape N * R obtained by applying the multivariate _ normal distribution to N points and R samples , by starting from the given seed and correlation ."""
if seed is not None : numpy . random . seed ( seed ) asset_count = len ( matrix ) samples = len ( matrix [ 0 ] ) if not correlation : # avoid building the covariance matrix return numpy . random . normal ( size = ( samples , asset_count ) ) . transpose ( ) means_vector = numpy . zeros ( asset_count ) covariance...
def _handle_status ( self , key , value ) : """Parse a status code from the attached GnuPG process . : raises : : exc : ` ~ exceptions . ValueError ` if the status message is unknown ."""
if key in ( "ENC_TO" , "USERID_HINT" , "GOODMDC" , "END_DECRYPTION" , "BEGIN_SIGNING" , "NO_SECKEY" , "ERROR" , "NODATA" , "CARDCTRL" , ) : # in the case of ERROR , this is because a more specific error # message will have come first pass elif key in ( "NEED_PASSPHRASE" , "BAD_PASSPHRASE" , "GOOD_PASSPHRASE" , "MIS...
def repo_list ( self , project_key , start = None , limit = 25 ) : """Get repositories list from project : param project _ key : : param start : OPTIONAL : The start of the : param limit : OPTIONAL : The limit of the number of repositories to return , this may be restricted by fixed system limits . Default ...
url = 'rest/api/1.0/projects/{projectKey}/repos' . format ( projectKey = project_key ) params = { } if limit : params [ 'limit' ] = limit if start : params [ 'start' ] = start response = self . get ( url , params = params ) if response . get ( 'isLastPage' ) : log . info ( 'This is a last page of the result...
def create ( self , name , plugin_name , hadoop_version , description = None , cluster_configs = None , node_groups = None , anti_affinity = None , net_id = None , default_image_id = None , use_autoconfig = None , shares = None , is_public = None , is_protected = None , domain_name = None ) : """Create a Cluster Te...
data = { 'name' : name , 'plugin_name' : plugin_name , 'hadoop_version' : hadoop_version , } return self . _do_create ( data , description , cluster_configs , node_groups , anti_affinity , net_id , default_image_id , use_autoconfig , shares , is_public , is_protected , domain_name )
def get_qc_tools ( data ) : """Retrieve a list of QC tools to use based on configuration and analysis type . Uses defaults if previously set ."""
if dd . get_algorithm_qc ( data ) : return dd . get_algorithm_qc ( data ) analysis = data [ "analysis" ] . lower ( ) to_run = [ ] if tz . get_in ( [ "config" , "algorithm" , "kraken" ] , data ) : to_run . append ( "kraken" ) if "fastqc" not in dd . get_tools_off ( data ) : to_run . append ( "fastqc" ) if an...
def query_saved_screenshot_info ( self , screen_id ) : """Returns available formats and size of the screenshot from saved state . in screen _ id of type int Saved guest screen to query info from . out width of type int Image width . out height of type int Image height . return bitmap _ formats of type...
if not isinstance ( screen_id , baseinteger ) : raise TypeError ( "screen_id can only be an instance of type baseinteger" ) ( bitmap_formats , width , height ) = self . _call ( "querySavedScreenshotInfo" , in_p = [ screen_id ] ) bitmap_formats = [ BitmapFormat ( a ) for a in bitmap_formats ] return ( bitmap_formats...
def submit_tag_batch ( self , batch ) : """Submit a tag batch"""
url = '%s/api/v5/batch/tags' % self . base_url self . _submit_batch ( url , batch )
def make_view ( robot ) : """为一个 BaseRoBot 生成 Django view 。 : param robot : 一个 BaseRoBot 实例 。 : return : 一个标准的 Django view"""
assert isinstance ( robot , BaseRoBot ) , "RoBot should be an BaseRoBot instance." @ csrf_exempt def werobot_view ( request ) : timestamp = request . GET . get ( "timestamp" , "" ) nonce = request . GET . get ( "nonce" , "" ) signature = request . GET . get ( "signature" , "" ) if not robot . check_sign...
def _annotate ( reads , mirbase_ref , precursors ) : """Using SAM / BAM coordinates , mismatches and realign to annotate isomiRs"""
for r in reads : for p in reads [ r ] . precursors : start = reads [ r ] . precursors [ p ] . start + 1 # convert to 1base end = start + len ( reads [ r ] . sequence ) for mature in mirbase_ref [ p ] : mi = mirbase_ref [ p ] [ mature ] is_iso = _coord ( reads ...
def handle_request ( self , request , app , model , pk ) : """Render and return tab"""
ModelClass = self . get_model_class ( ) object = ModelClass . objects . get ( id = pk ) tab_code = request . GET . get ( 'tab' ) model_alias = request . GET . get ( 'model_alias' ) model_alias = model_alias if model_alias else '{}.{}' . format ( app , model ) # TODO permission check item = tabs . get_tab ( model_alias ...
def add_breathing ( ch , breathing ) : """Add the given breathing to the given ( possibly accented ) character ."""
decomposed = unicodedata . normalize ( "NFD" , ch ) if len ( decomposed ) > 1 and decomposed [ 1 ] == LONG : return unicodedata . normalize ( "NFC" , decomposed [ 0 : 2 ] + breathing + decomposed [ 2 : ] ) else : return unicodedata . normalize ( "NFC" , decomposed [ 0 ] + breathing + decomposed [ 1 : ] )
def render_mail_template ( subject_template , body_template , context ) : """Renders both the subject and body templates in the given context . Returns a tuple ( subject , body ) of the result ."""
try : subject = strip_spaces ( render_to_string ( subject_template , context ) ) body = render_to_string ( body_template , context ) finally : pass return subject , body
def checkout ( self , * args , ** kwargs ) : """This function checks out source code ."""
self . _call_helper ( "Checking out" , self . real . checkout , * args , ** kwargs )
def _get ( self , plugin_name ) : """Retrieves the plugin with given name : param plugin _ name : Name of the plugin to retrieve : return samtranslator . plugins . BasePlugin : Returns the plugin object if found . None , otherwise"""
for p in self . _plugins : if p . name == plugin_name : return p return None
def end_input ( self , cmd ) : """End of wait _ input mode"""
self . input_mode = False self . input_loop . exit ( ) self . interpreter . widget_proxy . end_input ( cmd )
def _cut ( dna , index , restriction_enzyme ) : '''Cuts template once at the specified index . : param dna : DNA to cut : type dna : coral . DNA : param index : index at which to cut : type index : int : param restriction _ enzyme : Enzyme with which to cut : type restriction _ enzyme : coral . Restrict...
# TODO : handle case where cut site is outside of recognition sequence , # for both circular and linear cases where site is at index 0 # Find absolute indices at which to cut cut_site = restriction_enzyme . cut_site top_cut = index + cut_site [ 0 ] bottom_cut = index + cut_site [ 1 ] # Isolate left and ride sequences t...
def ready ( self ) : """Function used when agent is ` lazy ` . It is being processed only when ` ready ` condition is satisfied"""
logger = self . get_logger ( ) now = current_ts ( ) logger . trace ( "Current time: {0}" . format ( now ) ) logger . trace ( "Last Run: {0}" . format ( self . _last_run ) ) delta = ( now - self . _last_run ) logger . trace ( "Delta: {0}, Interval: {1}" . format ( delta , self . interval * 1000 ) ) return delta > self ....
def import_graph ( hl_graph , tf_graph , output = None , verbose = False ) : """Convert TF graph to directed graph tfgraph : A TF Graph object . output : Name of the output node ( string ) . verbose : Set to True for debug print output"""
# Get clean ( er ) list of nodes graph_def = tf_graph . as_graph_def ( add_shapes = True ) graph_def = tf . graph_util . remove_training_nodes ( graph_def ) # Dump list of TF nodes ( DEBUG only ) if verbose : dump_tf_graph ( tf_graph , graph_def ) # Loop through nodes and build the matching directed graph for tf_no...
def bless ( rest ) : "Bless the day !"
if rest : blesse = rest else : blesse = 'the day' karma . Karma . store . change ( blesse , 1 ) return "/me blesses %s!" % blesse
def writeAMF3 ( self , data ) : """Writes an element in L { AMF3 < pyamf . amf3 > } format ."""
self . writeType ( TYPE_AMF3 ) self . context . getAMF3Encoder ( self ) . writeElement ( data )
def printMcmcSamplesToFile ( self , profile , numSamples , outFileName ) : """Generate samples to a file . : ivar Profile profile : A Profile object that represents an election profile . : ivar int numSamples : The number of samples to be generated . : ivar str outFileName : The name of the file to be output ...
wmg = profile . getWmg ( True ) V = self . getInitialSample ( wmg ) # Print the number of candidates , phi , and the number of samples . outFile = open ( outFileName , 'w' ) outFile . write ( "m," + str ( profile . numCands ) + '\n' ) outFile . write ( "phi," + str ( self . phi ) + '\n' ) outFile . write ( "numSamples,...
def data_to_binary ( self ) : """: return : bytes"""
return bytes ( [ COMMAND_CODE , self . transmit_error_counter , self . receive_error_counter , self . bus_off_counter ] )
def highlight_keywords ( self , event , colored ) : """Highlight the keyword in the log statement by drawing an underline"""
if self . keyword : highlight = colored . underline ( self . keyword ) event . message = event . message . replace ( self . keyword , highlight ) return event
def simulate_feeddata ( self , feedid , data , mime = None , time = None ) : """Send feed data"""
# Separate public method since internal one does not require parameter checks feedid = Validation . guid_check_convert ( feedid ) mime = Validation . mime_check_convert ( mime , allow_none = True ) Validation . datetime_check_convert ( time , allow_none = True , to_iso8601 = False ) self . __simulate_feeddata ( feedid ...
def get_route ( self , route_id ) : """Gets specified route . Will be detail - level if owned by authenticated user ; otherwise summary - level . https : / / strava . github . io / api / v3 / routes / # retreive : param route _ id : The ID of route to fetch . : type route _ id : int : rtype : : class : ` ...
raw = self . protocol . get ( '/routes/{id}' , id = route_id ) return model . Route . deserialize ( raw , bind_client = self )
def index_to_coords ( index , shape ) : '''convert index to coordinates given the shape'''
coords = [ ] for i in xrange ( 1 , len ( shape ) ) : divisor = int ( np . product ( shape [ i : ] ) ) value = index // divisor coords . append ( value ) index -= value * divisor coords . append ( index ) return tuple ( coords )
def to_repr ( value , ctx ) : """Converts a value back to its representation form , e . g . x - > " x " """
as_string = to_string ( value , ctx ) if isinstance ( value , str ) or isinstance ( value , datetime . date ) or isinstance ( value , datetime . time ) : as_string = as_string . replace ( '"' , '""' ) # escape quotes by doubling as_string = '"%s"' % as_string return as_string
def get_secrets ( self , secure_data_path , version = None ) : """( Deprecated ) Return json secrets based on the secure data path This method is deprecated because an addition step of reading value with [ ' data ' ] key from the returned data is required to get secrets , which contradicts the method name . U...
warnings . warn ( "get_secrets is deprecated, use get_secrets_data instead" , DeprecationWarning ) return self . _get_secrets ( secure_data_path , version )
def set_session ( s ) : """Configures the default connection with a preexisting : class : ` cassandra . cluster . Session ` Note : the mapper presently requires a Session : attr : ` ~ . row _ factory ` set to ` ` dict _ factory ` ` . This may be relaxed in the future"""
try : conn = get_connection ( ) except CQLEngineException : # no default connection set ; initalize one register_connection ( 'default' , session = s , default = True ) conn = get_connection ( ) if conn . session : log . warning ( "configuring new default connection for cqlengine when one was already se...
def create_aside ( self , definition_id , usage_id , aside_type ) : """Create the aside ."""
return ( self . ASIDE_DEFINITION_ID ( definition_id , aside_type ) , self . ASIDE_USAGE_ID ( usage_id , aside_type ) , )
def build_pic_map ( self ) : """Searches in docx template all the xml pictures tag and store them in pic _ map dict"""
if self . pic_to_replace : # Main document part = self . docx . part self . pic_map . update ( self . _img_filename_to_part ( part ) ) # Header / Footer for relid , rel in six . iteritems ( self . docx . part . rels ) : if rel . reltype in ( REL_TYPE . HEADER , REL_TYPE . FOOTER ) : ...
def check_voltage ( grid , mode ) : """Checks for voltage stability issues at all nodes for MV or LV grid Parameters grid : GridDing0 Grid identifier . mode : str Kind of grid ( ' MV ' or ' LV ' ) . Returns : any : ` list ` of : any : ` GridDing0 ` List of critical nodes , sorted descending by volta...
crit_nodes = { } if mode == 'MV' : # load max . voltage difference for load and feedin case mv_max_v_level_lc_diff_normal = float ( cfg_ding0 . get ( 'mv_routing_tech_constraints' , 'mv_max_v_level_lc_diff_normal' ) ) mv_max_v_level_fc_diff_normal = float ( cfg_ding0 . get ( 'mv_routing_tech_constraints' , 'mv_...
def setData ( self , type : str , data : str ) -> None : """Set data of type format . : arg str type : Data format of the data , like ' text / plain ' ."""
type = normalize_type ( type ) if type in self . __data : del self . __data [ type ] self . __data [ type ] = data
def split_sql ( sql ) : """generate hunks of SQL that are between the bookends return : tuple of beginning bookend , closing bookend , and contents note : beginning & end of string are returned as None"""
bookends = ( "\n" , ";" , "--" , "/*" , "*/" ) last_bookend_found = None start = 0 while start <= len ( sql ) : results = get_next_occurence ( sql , start , bookends ) if results is None : yield ( last_bookend_found , None , sql [ start : ] ) start = len ( sql ) + 1 else : ( end , bo...
def BE16 ( value , min_value = None , max_value = None , fuzzable = True , name = None , full_range = False ) : '''16 - bit field , Big endian encoded'''
return UInt16 ( value , min_value = min_value , max_value = max_value , encoder = ENC_INT_BE , fuzzable = fuzzable , name = name , full_range = full_range )
def __push_import_modules ( self ) : """Add custom < import _ modules > to the import namespace under its own _ _ name _ _ ."""
for module in self . __import_modules : sys . modules [ module . __name__ ] = module
def read ( filename , file_format = None ) : """Reads an unstructured mesh with added data . : param filenames : The files to read from . : type filenames : str : returns mesh { 2,3 } d : The mesh data ."""
# https : / / stackoverflow . com / q / 4843173/353337 assert isinstance ( filename , str ) if not file_format : # deduce file format from extension file_format = _filetype_from_filename ( filename ) format_to_reader = { "ansys" : ansys_io , "ansys-ascii" : ansys_io , "ansys-binary" : ansys_io , "gmsh" : msh_io , "...
def _build_signature ( self ) : """Create the signature using the private key ."""
sig_contents = self . payload + "." + b64encode ( b"application/xml" ) . decode ( "ascii" ) + "." + b64encode ( b"base64url" ) . decode ( "ascii" ) + "." + b64encode ( b"RSA-SHA256" ) . decode ( "ascii" ) sig_hash = SHA256 . new ( sig_contents . encode ( "ascii" ) ) cipher = PKCS1_v1_5 . new ( self . private_key ) sig ...
async def root ( self ) : """Root level init : return :"""
if self . writing : await self . iobj . awrite ( binascii . unhexlify ( b'011673657269616c697a6174696f6e3a3a617263686976650000' ) ) else : hdr = bytearray ( 2 ) await self . iobj . areadinto ( hdr ) if hdr != bytearray ( b'\x01\x16' ) : raise ValueError ( 'Unsupported header' ) hdr = bytearr...
def cdf_abramowitz_stegun ( x ) : """The cumulative distribution function of the standard normal distribution . The standard implementation , following Abramowitz / Stegun , ( 26.2.17 ) ."""
if x >= 0 : # if x > 7.0: # return 1 - ONE _ OVER _ SQRT _ OF _ TWO _ PI * exp ( - 0.5 * x * x ) / sqrt ( 1.0 + x * x ) result = 1.0 / ( 1.0 + 0.2316419 * x ) ret = 1.0 - ONE_OVER_SQRT_OF_TWO_PI * exp ( - 0.5 * x * x ) * ( result * ( 0.31938153 + result * ( - 0.356563782 + result * ( 1.781477937 + result * ( - ...
def equipable_classes ( self ) : """Returns a list of classes that _ can _ use the item ."""
sitem = self . _schema_item return [ c for c in sitem . get ( "used_by_classes" , self . equipped . keys ( ) ) if c ]
def fetch ( self , url ) : """Get the feed content using ' requests '"""
try : r = requests . get ( url , timeout = self . timeout ) except requests . exceptions . Timeout : if not self . safe : raise else : return None # Raise 404/500 error if any if r and not self . safe : r . raise_for_status ( ) return r . text
def find_general_mappings ( es_major_version ) : """Find the general mappings applied to all data sources : param es _ major _ version : string with the major version for Elasticsearch : return : a dict with the mappings ( raw and enriched )"""
if es_major_version not in ES_SUPPORTED : print ( "Elasticsearch version not supported %s (supported %s)" % ( es_major_version , ES_SUPPORTED ) ) sys . exit ( 1 ) # By default all strings are not analyzed in ES < 6 if es_major_version == '5' : # Before version 6 , strings were strings not_analyze_strings = ...
def __load ( self ) : """Loads text and photos if they are not cached ."""
if self . _text is not None : return body = self . _session . get ( self . url ) . content root = html . fromstring ( body ) self . _text = "\n" . join ( ( p_tag . text_content ( ) for p_tag in root . findall ( './/p[@class="ArticleContent"]' ) if 'justify' in p_tag . get ( 'style' , '' ) ) ) # TODO fix this self ....
def remove_expired_multipartobjects ( ) : """Remove expired multipart objects ."""
delta = current_app . config [ 'FILES_REST_MULTIPART_EXPIRES' ] expired_dt = datetime . utcnow ( ) - delta file_ids = [ ] for mp in MultipartObject . query_expired ( expired_dt ) : file_ids . append ( str ( mp . file_id ) ) mp . delete ( ) for fid in file_ids : remove_file_data . delay ( fid )
def create_volume ( kwargs = None , call = None , wait_to_finish = False ) : '''Create a volume . zone The availability zone used to create the volume . Required . String . size The size of the volume , in GiBs . Defaults to ` ` 10 ` ` . Integer . snapshot The snapshot - id from which to create the volu...
if call != 'function' : log . error ( 'The create_volume function must be called with -f or --function.' ) return False if 'zone' not in kwargs : log . error ( 'An availability zone must be specified to create a volume.' ) return False if 'size' not in kwargs and 'snapshot' not in kwargs : # This number...
def scrollbar_toggled ( self , settings , key , user_data ) : """If the gconf var use _ scrollbar be changed , this method will be called and will show / hide scrollbars of all terminals open ."""
for term in self . guake . notebook_manager . iter_terminals ( ) : # There is an hbox in each tab of the main notebook and it # contains a Terminal and a Scrollbar . Since only have the # Terminal here , we ' re going to use this to get the # scrollbar and hide / show it . hbox = term . get_parent ( ) if hbox i...
def load_pretrained_word2vec ( infile ) : """Load the pre - trained word2vec from file ."""
if isinstance ( infile , str ) : infile = open ( infile ) word2vec_list = { } for idx , line in enumerate ( infile ) : if idx == 0 : vocab_size , dim = line . strip ( ) . split ( ) else : tks = line . strip ( ) . split ( ) word2vec_list [ tks [ 0 ] ] = map ( float , tks [ 1 : ] ) ret...
def setup_cache ( app : Flask , cache_config ) -> Optional [ Cache ] : """Setup the flask - cache on a flask app"""
if cache_config and cache_config . get ( 'CACHE_TYPE' ) != 'null' : return Cache ( app , config = cache_config ) return None
def draw_image ( self , video_name , image_name , out , start , end , x , y , verbose = False ) : """Draws an image over the video @ param video _ name : name of video input file @ param image _ name : name of image input file @ param out : name of video output file @ param start : when to start overlay @...
cfilter = ( r"[0] [1] overlay=x={x}: y={y}:" "enable='between(t, {start}, {end}')" ) . format ( x = x , y = y , start = start , end = end ) call ( [ 'ffmpeg' , '-i' , video_name , '-i' , image_name , '-c:v' , 'huffyuv' , '-y' , '-preset' , 'veryslow' , '-filter_complex' , cfilter , out ] )
def symbols_app ( parser , _ , args ) : # pragma : no cover """List ELF symbol table ."""
parser . add_argument ( 'file' , help = 'ELF file to list the symbols of' ) parser . add_argument ( 'symbol' , nargs = '?' , help = 'show only this symbol' ) parser . add_argument ( '--exact' , '-e' , action = 'store_const' , const = True , help = 'filter by exact symbol name' ) args = parser . parse_args ( args ) prin...
def saccadic_momentum_effect ( durations , forward_angle , summary_stat = nanmean ) : """Computes the mean fixation duration at forward angles ."""
durations_per_da = np . nan * np . ones ( ( len ( e_angle ) - 1 , ) ) for i , ( bo , b1 ) in enumerate ( zip ( e_angle [ : - 1 ] , e_angle [ 1 : ] ) ) : idx = ( bo <= forward_angle ) & ( forward_angle < b1 ) & ( ~ np . isnan ( durations ) ) durations_per_da [ i ] = summary_stat ( durations [ idx ] ) return dura...
def parse ( self , line : str , expand : bool = True ) -> Statement : """Tokenize the input and parse it into a Statement object , stripping comments , expanding aliases and shortcuts , and extracting output redirection directives . : param line : the command line being parsed : param expand : If True , the...
# handle the special case / hardcoded terminator of a blank line # we have to do this before we tokenize because tokenizing # destroys all unquoted whitespace in the input terminator = '' if line [ - 1 : ] == constants . LINE_FEED : terminator = constants . LINE_FEED command = '' args = '' arg_list = [ ] # lex the ...
def fromxml ( node ) : """Static method returning an MetaField instance ( any subclass of AbstractMetaField ) from the given XML description . Node can be a string or an etree . _ Element ."""
if not isinstance ( node , ElementTree . _Element ) : # pylint : disable = protected - access node = parsexmlstring ( node ) if node . tag . lower ( ) != 'meta' : raise Exception ( "Expected meta tag but got '" + node . tag + "' instead" ) key = node . attrib [ 'id' ] if node . text : value = node . text el...
def prettyval ( self , val ) : """returns the value in a readable format ."""
if len ( val ) == self . wordsize and val [ - 1 : ] in ( b'\x00' , b'\xff' ) : return "%x" % struct . unpack ( "<" + self . fmt , val ) if len ( val ) == self . wordsize and re . search ( b'[\x00-\x08\x0b\x0c\x0e-\x1f]' , val , re . DOTALL ) : return "%x" % struct . unpack ( "<" + self . fmt , val ) if len ( va...
def get_collection ( self , ** kwargs ) : """Establish a connection with the database . Returns MongoDb collection"""
from pymongo import MongoClient if self . host and self . port : client = MongoClient ( host = config . host , port = config . port ) else : client = MongoClient ( ) db = client [ self . dbname ] # Authenticate if needed if self . user and self . password : db . autenticate ( self . user , password = self ....
def powerDown ( self ) : """power down the Thread device"""
print '%s call powerDown' % self . port self . _sendline ( 'reset' ) self . isPowerDown = True
def PrependUOffsetTRelativeSlot ( self , o , x , d ) : """PrependUOffsetTRelativeSlot prepends an UOffsetT onto the object at vtable slot ` o ` . If value ` x ` equals default ` d ` , then the slot will be set to zero and no other data will be written ."""
if x != d : self . PrependUOffsetTRelative ( x ) self . Slot ( o )
def do_check ( pool , request , models , include_children_for , modelgb ) : "request is the output of translate _ check . models a dict of { ( model _ name , pkey _ tuple ) : model } . ICF is a { model _ name : fields _ list } for which we want to add nulls in request for missing children . see AMC for how it ' s u...
add_missing_children ( models , request , include_children_for , modelgb ) return { k : fkapply ( models , pool , process_check , None , k , v ) for k , v in request . items ( ) }
def get_model_by_field ( self , name ) : """Find the : class : ` TranslatedFieldsModel ` that contains the given field ."""
try : return self . _fields_to_model [ name ] except KeyError : raise FieldError ( "Translated field does not exist: '{0}'" . format ( name ) )