signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def push_json_file ( json_file , url , dry_run = False , batch_size = 100 , anonymize_fields = [ ] , remove_fields = [ ] , rename_fields = [ ] ) : """read the json file provided and POST in batches no bigger than the batch _ size specified to the specified url ."""
batch = [ ] json_data = json . loads ( json_file . read ( ) ) if isinstance ( json_data , list ) : for item in json_data : # anonymize fields for field_name in anonymize_fields : if field_name in item : item [ field_name ] = md5sum ( item [ field_name ] ) # remove fields ...
def _print_split_model ( self , path , apps_models ) : """Print each model in apps _ models into its own file ."""
for app , models in apps_models : for model in models : model_name = model ( ) . title if self . _has_extension ( path ) : model_path = re . sub ( r'^(.*)[.](\w+)$' , r'\1.%s.%s.\2' % ( app , model_name ) , path ) else : model_path = '%s.%s.%s.puml' % ( path , app , m...
def fromJSON ( cls , jdata ) : """Generates a new column from the given json data . This should be already loaded into a Python dictionary , not a JSON string . : param jdata | < dict > : return < orb . Column > | | None"""
cls_type = jdata . get ( 'type' ) col_cls = cls . byName ( cls_type ) if not col_cls : raise orb . errors . ColumnTypeNotFound ( cls_type ) else : col = col_cls ( ) col . loadJSON ( jdata ) return col
def _format_capability_report ( self , data ) : """This is a private utility method . This method formats a capability report if the user wishes to send it to the console . If log _ output = True , no output is generated : param data : Capability report : returns : None"""
if self . log_output : return else : pin_modes = { 0 : 'Digital_Input' , 1 : 'Digital_Output' , 2 : 'Analog' , 3 : 'PWM' , 4 : 'Servo' , 5 : 'Shift' , 6 : 'I2C' , 7 : 'One Wire' , 8 : 'Stepper' , 9 : 'Encoder' } x = 0 pin = 0 print ( '\nCapability Report' ) print ( '-----------------\n' ) wh...
def _flush ( self ) : """We skip any locking code due to the fact that this is now a single process per collector"""
# Send a None down the queue to indicate a flush try : self . queue . put ( None , block = False ) except Queue . Full : self . _throttle_error ( 'Queue full, check handlers for delays' )
def listSubjectsResponse ( self , query , status = None , start = None , count = None , vendorSpecific = None ) : """CNIdentity . listSubjects ( session , query , status , start , count ) → SubjectList https : / / releases . dataone . org / online / api - documentation - v2.0.1 / apis / CN _ APIs . html # CNIde...
url_query = { 'status' : status , 'start' : start , 'count' : count , 'query' : query } return self . GET ( 'accounts' , query = url_query , headers = vendorSpecific )
def parse_cutadapt_logs ( self , f ) : """Go through log file looking for cutadapt output"""
fh = f [ 'f' ] regexes = { '1.7' : { 'bp_processed' : "Total basepairs processed:\s*([\d,]+) bp" , 'bp_written' : "Total written \(filtered\):\s*([\d,]+) bp" , 'quality_trimmed' : "Quality-trimmed:\s*([\d,]+) bp" , 'r_processed' : "Total reads processed:\s*([\d,]+)" , 'r_with_adapters' : "Reads with adapters:\s*([\d,]+...
def renew_token ( self , token = None , increment = None , wrap_ttl = None ) : """POST / auth / token / renew POST / auth / token / renew - self : param token : : type token : : param increment : : type increment : : param wrap _ ttl : : type wrap _ ttl : : return : : rtype :"""
params = { 'increment' : increment , } if token is not None : params [ 'token' ] = token return self . _adapter . post ( '/v1/auth/token/renew' , json = params , wrap_ttl = wrap_ttl ) . json ( ) else : return self . _adapter . post ( '/v1/auth/token/renew-self' , json = params , wrap_ttl = wrap_ttl ) . json...
def run_exitfuncs ( ) : """Function that behaves exactly like Python ' s atexit , but runs atexit functions in the order in which they were registered , not reversed ."""
exc_info = None for func , targs , kargs in _exithandlers : try : func ( * targs , ** kargs ) except SystemExit : exc_info = sys . exc_info ( ) except : exc_info = sys . exc_info ( ) if exc_info is not None : six . reraise ( exc_info [ 0 ] , exc_info [ 1 ] , exc_info [ 2 ] )
def POST_AUTH ( self ) : # pylint : disable = arguments - differ """Parse course registration or course creation and display the course list page"""
username = self . user_manager . session_username ( ) user_info = self . database . users . find_one ( { "username" : username } ) user_input = web . input ( ) success = None # Handle registration to a course if "register_courseid" in user_input and user_input [ "register_courseid" ] != "" : try : course = ...
def compute_neighbors ( self , n_neighbors : int = 30 , knn : bool = True , n_pcs : Optional [ int ] = None , use_rep : Optional [ str ] = None , method : str = 'umap' , random_state : Optional [ Union [ RandomState , int ] ] = 0 , write_knn_indices : bool = False , metric : str = 'euclidean' , metric_kwds : Mapping [ ...
if n_neighbors > self . _adata . shape [ 0 ] : # very small datasets n_neighbors = 1 + int ( 0.5 * self . _adata . shape [ 0 ] ) logg . warn ( 'n_obs too small: adjusting to `n_neighbors = {}`' . format ( n_neighbors ) ) if method == 'umap' and not knn : raise ValueError ( '`method = \'umap\' only with `knn...
def ite_burrowed ( self ) : """Returns an equivalent AST that " burrows " the ITE expressions as deep as possible into the ast , for simpler printing ."""
if self . _burrowed is None : self . _burrowed = self . _burrow_ite ( ) # pylint : disable = attribute - defined - outside - init self . _burrowed . _burrowed = self . _burrowed # pylint : disable = attribute - defined - outside - init return self . _burrowed
def unpatch ( self ) : """un - applies this patch ."""
if not self . _patched : return for func in self . _read_compilers + self . _write_compilers : func . execute_sql = self . _original [ func ] self . cache_backend . unpatch ( ) self . _patched = False
def _outer_distance_mod_n ( ref , est , modulus = 12 ) : """Compute the absolute outer distance modulo n . Using this distance , d ( 11 , 0 ) = 1 ( modulo 12) Parameters ref : np . ndarray , shape = ( n , ) Array of reference values . est : np . ndarray , shape = ( m , ) Array of estimated values . mo...
ref_mod_n = np . mod ( ref , modulus ) est_mod_n = np . mod ( est , modulus ) abs_diff = np . abs ( np . subtract . outer ( ref_mod_n , est_mod_n ) ) return np . minimum ( abs_diff , modulus - abs_diff )
def assign_fields ( meta , assignments ) : """Takes a list of C { key = value } strings and assigns them to the given metafile . If you want to set nested keys ( e . g . " info . source " ) , you have to use a dot as a separator . For exotic keys * containing * a dot , double that dot ( " dotted . . key " ) ....
for assignment in assignments : assignment = fmt . to_unicode ( assignment ) try : if '=' in assignment : field , val = assignment . split ( '=' , 1 ) else : field , val = assignment , None if val and val [ 0 ] in "+-" and val [ 1 : ] . isdigit ( ) : v...
def is_monotonic ( df , items = None , increasing = None , strict = False ) : """Asserts that the DataFrame is monotonic . Parameters df : Series or DataFrame items : dict mapping columns to conditions ( increasing , strict ) increasing : None or bool None is either increasing or decreasing . strict :...
if items is None : items = { k : ( increasing , strict ) for k in df } for col , ( increasing , strict ) in items . items ( ) : s = pd . Index ( df [ col ] ) if increasing : good = getattr ( s , 'is_monotonic_increasing' ) elif increasing is None : good = getattr ( s , 'is_monotonic' ) |...
def SequenceOf ( klass ) : """Function to return a class that can encode and decode a list of some other type ."""
if _debug : SequenceOf . _debug ( "SequenceOf %r" , klass ) global _sequence_of_map global _sequence_of_classes , _array_of_classes # if this has already been built , return the cached one if klass in _sequence_of_map : if _debug : SequenceOf . _debug ( " - found in cache" ) return _sequence_of_m...
def impulse_deltav_hernquist_curvedstream ( v , x , b , w , x0 , v0 , GM , rs ) : """NAME : impulse _ deltav _ plummer _ hernquist PURPOSE : calculate the delta velocity to due an encounter with a Hernquist sphere in the impulse approximation ; allows for arbitrary velocity vectors , and arbitrary position al...
if len ( v . shape ) == 1 : v = numpy . reshape ( v , ( 1 , 3 ) ) if len ( x . shape ) == 1 : x = numpy . reshape ( x , ( 1 , 3 ) ) b0 = numpy . cross ( w , v0 ) b0 *= b / numpy . sqrt ( numpy . sum ( b0 ** 2 ) ) b_ = b0 + x - x0 w = w - v wmag = numpy . sqrt ( numpy . sum ( w ** 2 , axis = 1 ) ) bdotw = numpy ...
def _update_notification ( self , message = None ) : """Update the message area with blank or a message ."""
if message is None : message = '' message_label = self . _parts [ 'notification label' ] message_label . config ( text = message ) self . _base . update ( )
def get_lan_ip ( interface = "default" ) : if sys . version_info < ( 3 , 0 , 0 ) : if type ( interface ) == str : interface = unicode ( interface ) else : if type ( interface ) == bytes : interface = interface . decode ( "utf-8" ) # Get ID of interface that handles WA...
if platform . system ( ) == "Linux" : if ip is not None : return ip . routes [ "8.8.8.8" ] [ "prefsrc" ] return None
def namedb_get_namespace_reveal ( cur , namespace_id , current_block , include_history = True ) : """Get a namespace reveal , and optionally its history , given its namespace ID . Only return a namespace record if : * it is not ready * it is not expired"""
select_query = "SELECT * FROM namespaces WHERE namespace_id = ? AND op = ? AND reveal_block <= ? AND ? < reveal_block + ?;" args = ( namespace_id , NAMESPACE_REVEAL , current_block , current_block , NAMESPACE_REVEAL_EXPIRE ) namespace_reveal_rows = namedb_query_execute ( cur , select_query , args ) namespace_reveal_row...
def report ( self , item_id , report_format = "json" ) : """Retrieves the specified report for the analyzed item , referenced by item _ id . Available formats include : json , html . : type item _ id : str : param item _ id : File ID number : type report _ format : str : param report _ format : Return for...
report_format = report_format . lower ( ) response = self . _request ( "/report/{job_id}/summary" . format ( job_id = item_id ) ) if response . status_code == 429 : raise sandboxapi . SandboxError ( 'API rate limit exceeded while fetching report' ) # if response is JSON , return it as an object if report_format == ...
def _get_pitcher ( self , pitcher ) : """get pitcher object : param pitcher : Beautifulsoup object ( pitcher element ) : return : pitcher ( dict )"""
values = OrderedDict ( ) player = self . players . rosters . get ( pitcher . get ( 'id' ) ) values [ 'pos' ] = pitcher . get ( 'pos' , MlbamConst . UNKNOWN_SHORT ) values [ 'id' ] = pitcher . get ( 'id' , MlbamConst . UNKNOWN_SHORT ) values [ 'first' ] = player . first values [ 'last' ] = player . last values [ 'box_na...
def update ( self , tickDict ) : '''consume ticks'''
if not self . __trakers : self . __setUpTrakers ( ) for security , tick in tickDict . items ( ) : if security in self . __trakers : self . __trakers [ security ] . tickUpdate ( tick )
def get ( self , key , defaultvalue = None ) : """Support dict - like get ( return a default value if not found )"""
( t , k ) = self . _getsubitem ( key , False ) if t is None : return defaultvalue else : return t . __dict__ . get ( k , defaultvalue )
def update_default_channels ( sender , instance , created , ** kwargs ) : """Post save hook to ensure that there is only one default"""
if instance . default : Channel . objects . filter ( default = True ) . exclude ( channel_id = instance . channel_id ) . update ( default = False )
def disable_scanners ( self , scanners ) : """Enable the provided scanners by group and / or IDs ."""
scanner_ids = [ ] for scanner in scanners : if scanner in self . scanner_groups : self . disable_scanners_by_group ( scanner ) elif scanner . isdigit ( ) : scanner_ids . append ( scanner ) else : raise ZAPError ( 'Invalid scanner "{0}" provided. Must be a valid group or numeric ID.' ...
def send_reply_to ( address , reply = EMPTY ) : """Reply to a message previously received : param address : a nw0 address ( eg from ` nw0 . advertise ` ) : param reply : any simple Python object , including text & tuples"""
_logger . debug ( "Sending reply %s to %s" , reply , address ) return sockets . _sockets . send_reply_to ( address , reply )
def integrate ( self , dt ) : """Integrate gyro measurements to orientation using a uniform sample rate . Parameters dt : float Sample distance in seconds Returns orientation : ( 4 , N ) ndarray Gyroscope orientation in quaternion form ( s , q1 , q2 , q3)"""
if not dt == self . __last_dt : self . __last_q = fastintegrate . integrate_gyro_quaternion_uniform ( self . data , dt ) self . __last_dt = dt return self . __last_q
def ge ( self , other ) : """Greater than or overlaps . Returns True if no part of this Interval extends lower than other . : raises ValueError : if either self or other is a null Interval : param other : Interval or point : return : True or False : rtype : bool"""
self . _raise_if_null ( other ) return self . begin >= getattr ( other , 'begin' , other )
def local_histogram ( image , bins = 19 , rang = "image" , cutoffp = ( 0.0 , 100.0 ) , size = None , footprint = None , output = None , mode = "ignore" , origin = 0 , mask = slice ( None ) ) : r"""Computes multi - dimensional histograms over a region around each voxel . Supply an image and ( optionally ) a mask a...
return _extract_feature ( _extract_local_histogram , image , mask , bins = bins , rang = rang , cutoffp = cutoffp , size = size , footprint = footprint , output = output , mode = mode , origin = origin )
def open ( self , filename ) : # type : ( str ) - > None '''Open up an existing ISO for inspection and modification . Parameters : filename - The filename containing the ISO to open up . Returns : Nothing .'''
if self . _initialized : raise pycdlibexception . PyCdlibInvalidInput ( 'This object already has an ISO; either close it or create a new object' ) fp = open ( filename , 'r+b' ) self . _managing_fp = True try : self . _open_fp ( fp ) except Exception : fp . close ( ) raise
def source_headers ( self ) : """" Returns the headers for the resource source . Specifically , does not include any header that is the EMPTY _ SOURCE _ HEADER value of _ NONE _"""
t = self . schema_term if t : return [ self . _name_for_col_term ( c , i ) for i , c in enumerate ( t . children , 1 ) if c . term_is ( "Table.Column" ) and c . get_value ( 'name' ) != EMPTY_SOURCE_HEADER ] else : return None
def from_payload ( self , payload ) : """Init frame from binary data ."""
self . node_id = payload [ 0 ] self . name = bytes_to_string ( payload [ 1 : 65 ] )
def getRnaQuantificationSet ( self , id_ ) : """Returns the RnaQuantification set with the specified name , or raises a RnaQuantificationSetNotFoundException otherwise ."""
if id_ not in self . _rnaQuantificationSetIdMap : raise exceptions . RnaQuantificationSetNotFoundException ( id_ ) return self . _rnaQuantificationSetIdMap [ id_ ]
def _init_action_list ( self , action_filename ) : """Parses the file and populates the data ."""
self . actions = list ( ) self . hiid_to_action_index = dict ( ) f = codecs . open ( action_filename , 'r' , encoding = 'latin-1' ) first_line = True for line in f : line = line . rstrip ( ) if first_line : # Ignore the first line first_line = False else : self . actions . append ( GenewaysA...
def retry ( transport : 'UDPTransport' , messagedata : bytes , message_id : UDPMessageID , recipient : Address , stop_event : Event , timeout_backoff : Iterable [ int ] , ) -> bool : """Send messagedata until it ' s acknowledged . Exit when : - The message is delivered . - Event _ stop is set . - The iterat...
async_result = transport . maybe_sendraw_with_result ( recipient , messagedata , message_id , ) event_quit = event_first_of ( async_result , stop_event , ) for timeout in timeout_backoff : if event_quit . wait ( timeout = timeout ) is True : break log . debug ( 'retrying message' , node = pex ( transpor...
def do_display ( self , arg ) : """display [ expression ] Display the value of the expression if it changed , each time execution stops in the current frame . Without expression , list all display expressions for the current frame ."""
if not arg : self . message ( 'Currently displaying:' ) for item in self . displaying . get ( self . curframe , { } ) . items ( ) : self . message ( '%s: %s' % bdb . safe_repr ( item ) ) else : val = self . _getval_except ( arg ) self . displaying . setdefault ( self . curframe , { } ) [ arg ] =...
def _param_toc_updated_cb ( self ) : """Called when the param TOC has been fully updated"""
logger . info ( 'Param TOC finished updating' ) self . connected_ts = datetime . datetime . now ( ) self . connected . call ( self . link_uri ) # Trigger the update for all the parameters self . param . request_update_of_all_params ( )
def execute_sql ( self , sql , commit = False ) : """Log and then execute a SQL query"""
logger . info ( "Running sqlite query: \"%s\"" , sql ) self . connection . execute ( sql ) if commit : self . connection . commit ( )
def SetModel ( self , loader ) : """Set our overall model ( a loader object ) and populate sub - controls"""
self . loader = loader self . adapter , tree , rows = self . RootNode ( ) self . listControl . integrateRecords ( rows . values ( ) ) self . activated_node = tree self . squareMap . SetModel ( tree , self . adapter ) self . RecordHistory ( )
def setting ( self , opt , val ) : """change an arbitrary synth setting , type - smart"""
opt = opt . encode ( ) if isinstance ( val , basestring ) : fluid_settings_setstr ( self . settings , opt , val ) elif isinstance ( val , int ) : fluid_settings_setint ( self . settings , opt , val ) elif isinstance ( val , float ) : fluid_settings_setnum ( self . settings , opt , val )
def _handle_tag_definesceneandframelabeldata ( self ) : """Handle the DefineSceneAndFrameLabelData tag ."""
obj = _make_object ( "DefineSceneAndFrameLabelData" ) obj . SceneCount = self . _get_struct_encodedu32 ( ) for i in range ( 1 , obj . SceneCount + 1 ) : setattr ( obj , 'Offset{}' . format ( i ) , self . _get_struct_encodedu32 ( ) ) setattr ( obj , 'Name{}' . format ( i ) , self . _get_struct_string ( ) ) obj ....
def _update_from_database ( self ) : """Updates map to latest state in database . Should be called prior to major object events to assure that an assessment being taken on multiple devices are reasonably synchronized ."""
collection = JSONClientValidated ( 'assessment' , collection = 'AssessmentSection' , runtime = self . _runtime ) self . _my_map = collection . find_one ( { '_id' : self . _my_map [ '_id' ] } )
def print_err ( * args , end = '\n' ) : """Similar to print , but prints to stderr ."""
print ( * args , end = end , file = sys . stderr ) sys . stderr . flush ( )
def list_consumer_group_offsets ( self , group_id , group_coordinator_id = None , partitions = None ) : """Fetch Consumer Group Offsets . Note : This does not verify that the group _ id or partitions actually exist in the cluster . As soon as any error is encountered , it is immediately raised . : param g...
group_offsets_listing = { } if group_coordinator_id is None : group_coordinator_id = self . _find_group_coordinator_id ( group_id ) version = self . _matching_api_version ( OffsetFetchRequest ) if version <= 3 : if partitions is None : if version <= 1 : raise ValueError ( """OffsetFetchReque...
def unregisterDataItem ( self , path ) : """Unregisters a data item that has been previously registered with the server ' s data store . Inputs : path - path to share folder Example : path = r " / fileShares / folder _ share " print data . unregisterDataItem ( path )"""
url = self . _url + "/unregisterItem" params = { "f" : "json" , "itempath" : path , "force" : "true" } return self . _post ( url , param_dict = params , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port )
def start_heartbeat ( self ) : """Reset hearbeat timer"""
self . stop_heartbeat ( ) self . _heartbeat_timer = periodic . Callback ( self . _heartbeat , self . _heartbeat_interval , self . server . io_loop ) self . _heartbeat_timer . start ( )
def from_buffer ( string , config_path = None ) : '''Detects MIME type of the buffered content : param string : buffered content whose type needs to be detected : return :'''
status , response = callServer ( 'put' , ServerEndpoint , '/detect/stream' , string , { 'Accept' : 'text/plain' } , False , config_path = config_path ) return response
def get_attribute_stats ( cls , soup , key , data_type = str , unknown = None ) : """Get attribute for Beautifulsoup object : param soup : Beautifulsoup object : param key : attribute key : param data _ type : Data type ( int , float , etc . . . ) : param unknown : attribute key not exists value ( default :...
value = cls . get_attribute ( soup , key , unknown ) if value and value != unknown : return data_type ( value ) return unknown
def launch_thread ( self , name , fn , * args , ** kwargs ) : """Adds a named thread to the " thread pool " dictionary of Thread objects . A daemon thread that executes the passed - in function ` fn ` with the given args and keyword args is started and tracked in the ` thread _ pool ` attribute with the given...
logger . debug ( "Launching thread '%s': %s(%s, %s)" , name , fn , args , kwargs ) self . thread_pool [ name ] = threading . Thread ( target = fn , args = args , kwargs = kwargs ) self . thread_pool [ name ] . daemon = True self . thread_pool [ name ] . start ( )
def parse ( self , tokens , debug = None ) : """This is the main entry point from outside . Passing in a debug dictionary changes the default debug setting ."""
self . tokens = tokens if debug : self . debug = debug sets = [ [ ( 1 , 0 ) , ( 2 , 0 ) ] ] self . links = { } if self . ruleschanged : self . computeNull ( ) self . newrules = { } self . new2old = { } self . makeNewRules ( ) self . ruleschanged = False self . edges , self . cores = { } , { ...
def _psplit ( self ) : """Split ` self ` at both north and south poles . : return : A list of split StridedIntervals"""
nsplit_list = self . _nsplit ( ) psplit_list = [ ] for si in nsplit_list : psplit_list . extend ( si . _ssplit ( ) ) return psplit_list
def simhash ( self , content ) : """Select policies for simhash on the different types of content ."""
if content is None : self . hash = - 1 return if isinstance ( content , str ) : features = self . tokenizer_func ( content , self . keyword_weight_pari ) self . hash = self . build_from_features ( features ) elif isinstance ( content , collections . Iterable ) : self . hash = self . build_from_featu...
def add_key_val ( keyname , keyval , keytype , filename , extnum ) : """Add / replace FITS key Add / replace the key keyname with value keyval of type keytype in filename . Parameters : keyname : str FITS Keyword name . keyval : str FITS keyword value . keytype : str FITS keyword type : int , float ...
funtype = { 'int' : int , 'float' : float , 'str' : str , 'bool' : bool } if keytype not in funtype : raise ValueError ( 'Undefined keyword type: ' , keytype ) with fits . open ( filename , "update" ) as hdulist : hdulist [ extnum ] . header [ keyname ] = funtype [ keytype ] ( keyval ) print ( '>>> Insertin...
def post_operations ( self , mode = None ) : """Return post - operations only for the mode asked"""
version_mode = self . _get_version_mode ( mode = mode ) return version_mode . post_operations
def get_hdrgo2usrgos ( self , hdrgos ) : """Return a subset of hdrgo2usrgos ."""
get_usrgos = self . hdrgo2usrgos . get hdrgos_actual = self . get_hdrgos ( ) . intersection ( hdrgos ) return { h : get_usrgos ( h ) for h in hdrgos_actual }
def list ( self , filters = None ) : """List model instances . Currently this gets * everything * and iterates through all possible pages in the API . This may be unsuitable for production environments with huge databases , so finer grained page support should likely be added at some point . Args : filt...
# Add in the page and page _ size parameters to the filter , such # that our request gets * all * objects in the list . However , # don ' t do this if the user has explicitly included these # parameters in the filter . if not filters : filters = { } if "page" not in filters : filters [ "page" ] = 1 if "page_siz...
def load_overrides ( introspection_module ) : """Loads overrides for an introspection module . Either returns the same module again in case there are no overrides or a proxy module including overrides . Doesn ' t cache the result ."""
namespace = introspection_module . __name__ . rsplit ( "." , 1 ) [ - 1 ] module_keys = [ prefix + "." + namespace for prefix in const . PREFIX ] # We use sys . modules so overrides can import from gi . repository # but restore everything at the end so this doesn ' t have any side effects for module_key in module_keys :...
def cli ( ctx , hpo_term , check_terms , output , p_value_limit , verbose , username , password , to_json ) : "Give hpo terms either on the form ' HP : 0001623 ' , or ' 0001623'"
loglevel = LEVELS . get ( min ( verbose , 3 ) ) configure_stream ( level = loglevel ) if not hpo_term : logger . info ( "Please specify at least one hpo term with '-t/--hpo_term'." ) ctx . abort ( ) if not ( username and password ) : logger . info ( "Please specify username with -u and password with -p." ) ...
def embedded_tweet ( self ) : """Get the retweeted Tweet OR the quoted Tweet and return it as a Tweet object Returns : Tweet ( or None , if the Tweet is neither a quote tweet or a Retweet ) : a Tweet representing the quote Tweet or the Retweet ( see tweet _ embeds . get _ embedded _ tweet , this is that val...
embedded_tweet = tweet_embeds . get_embedded_tweet ( self ) if embedded_tweet is not None : try : return Tweet ( embedded_tweet ) except NotATweetError as nate : raise ( NotATweetError ( "The embedded tweet payload {} appears malformed." + " Failed with '{}'" . format ( embedded_tweet , nate ) )...
def _merge_with_defaults ( params ) : """Performs a 2 - level deep merge of params with _ default _ params with corrent merging of params for each mark . This is a bit complicated since params [ ' marks ' ] is a list and we need to make sure each mark gets the default params ."""
marks_params = [ tz . merge ( default , param ) for default , param in zip ( itertools . repeat ( _default_params [ 'marks' ] ) , params [ 'marks' ] ) ] if 'marks' in params else [ _default_params [ 'marks' ] ] merged_without_marks = tz . merge_with ( tz . merge , tz . dissoc ( _default_params , 'marks' ) , tz . dissoc...
def _request_helper ( self , url , request_body ) : """A helper method to assist in making a request and provide a parsed response ."""
response = None # pylint : disable = try - except - raise try : response = self . session . post ( url , data = request_body , ** self . request_defaults ) # We expect utf - 8 from the server response . encoding = 'UTF-8' # update / set any cookies if self . _cookiejar is not None : for cook...
def learn ( self , sentence_list , token_master_list , hidden_neuron_count = 1000 , training_count = 1 , batch_size = 100 , learning_rate = 1e-03 , seq_len = 5 ) : '''Init . Args : sentence _ list : The ` list ` of sentences . token _ master _ list : Unique ` list ` of tokens . hidden _ neuron _ count : The...
observed_arr = self . __setup_dataset ( sentence_list , token_master_list , seq_len ) visible_num = observed_arr . shape [ - 1 ] # ` Builder ` in ` Builder Pattern ` for LSTM - RTRBM . rnnrbm_builder = LSTMRTRBMSimpleBuilder ( ) # Learning rate . rnnrbm_builder . learning_rate = learning_rate # Set units in visible lay...
def save_task ( task , broker ) : """Saves the task package to Django or the cache"""
# SAVE LIMIT < 0 : Don ' t save success if not task . get ( 'save' , Conf . SAVE_LIMIT >= 0 ) and task [ 'success' ] : return # enqueues next in a chain if task . get ( 'chain' , None ) : django_q . tasks . async_chain ( task [ 'chain' ] , group = task [ 'group' ] , cached = task [ 'cached' ] , sync = task [ 's...
def is_email ( self , address , diagnose = False ) : """Check that an address address conforms to RFCs 5321 , 5322 and others . More specifically , see the follow RFCs : * http : / / tools . ietf . org / html / rfc5321 * http : / / tools . ietf . org / html / rfc5322 * http : / / tools . ietf . org / html /...
threshold = BaseDiagnosis . CATEGORIES [ 'VALID' ] return_status = [ ValidDiagnosis ( ) ] parse_data = { } # Parse the address into components , character by character raw_length = len ( address ) context = Context . LOCALPART # Where we are context_stack = [ context ] # Where we ' ve been context_prior = Context . LOC...
def _prep_genome ( out_dir , data ) : """Create prepped reference directory for pisces . Requires a custom GenomeSize . xml file present ."""
genome_name = utils . splitext_plus ( os . path . basename ( dd . get_ref_file ( data ) ) ) [ 0 ] out_dir = utils . safe_makedir ( os . path . join ( out_dir , genome_name ) ) ref_file = dd . get_ref_file ( data ) utils . symlink_plus ( ref_file , os . path . join ( out_dir , os . path . basename ( ref_file ) ) ) with ...
def breadth_first ( problem , graph_search = False , viewer = None ) : '''Breadth first search . If graph _ search = True , will avoid exploring repeated states . Requires : SearchProblem . actions , SearchProblem . result , and SearchProblem . is _ goal .'''
return _search ( problem , FifoList ( ) , graph_search = graph_search , viewer = viewer )
def init_from_fcnxs ( ctx , fcnxs_symbol , fcnxs_args_from , fcnxs_auxs_from ) : """use zero initialization for better convergence , because it tends to oputut 0, and the label 0 stands for background , which may occupy most size of one image ."""
fcnxs_args = fcnxs_args_from . copy ( ) fcnxs_auxs = fcnxs_auxs_from . copy ( ) for k , v in fcnxs_args . items ( ) : if ( v . context != ctx ) : fcnxs_args [ k ] = mx . nd . zeros ( v . shape , ctx ) v . copyto ( fcnxs_args [ k ] ) for k , v in fcnxs_auxs . items ( ) : if ( v . context != ctx )...
def align ( self , sequence ) : """Aligns the primer to the given query sequence , returning a tuple of : hamming _ distance , start , end Where hamming distance is the distance between the primer and aligned sequence , and start and end give the start and end index of the primer relative to the input seque...
seq_aln , primer_aln , score , start , end = pairwise2 . align . globalms ( str ( sequence ) . upper ( ) , str ( self . primer ) . upper ( ) , self . match , self . difference , self . gap_open , self . gap_extend , one_alignment_only = True , penalize_end_gaps = self . penalize_end_gaps ) [ 0 ] # Get an ungapped mappi...
def reset ( self ) : """Empties all internal storage containers"""
super ( MorseComplex , self ) . reset ( ) self . base_partitions = { } self . merge_sequence = { } self . persistences = [ ] self . max_indices = [ ] # State properties self . persistence = 0.
def get_node_bundle ( manager , handle_id = None , node = None ) : """: param manager : Neo4jDBSessionManager : param handle _ id : Unique id : type handle _ id : str | unicode : param node : Node object : type node : neo4j . v1 . types . Node : return : dict"""
if not node : node = get_node ( manager , handle_id = handle_id , legacy = False ) d = { 'data' : node . properties } labels = list ( node . labels ) labels . remove ( 'Node' ) # All nodes have this label for indexing for label in labels : if label in META_TYPES : d [ 'meta_type' ] = label label...
def _lemmatise_suffixe ( self , f , * args , ** kwargs ) : """Lemmatise un mot f si il finit par un suffixe : param f : Mot à lemmatiser : yield : Match formated like in _ lemmatise ( )"""
for suffixe in self . _suffixes : if f . endswith ( suffixe ) and suffixe != f : yield from self . _lemmatise ( f [ : - len ( suffixe ) ] , * args , ** kwargs )
def _parse_section_links ( self , id_tag ) : """given a section id , parse the links in the unordered list"""
soup = BeautifulSoup ( self . html , "html.parser" ) info = soup . find ( "span" , { "id" : id_tag } ) all_links = list ( ) if info is None : return all_links for node in soup . find ( id = id_tag ) . parent . next_siblings : if not isinstance ( node , Tag ) : continue elif node . get ( "role" , "" ...
def rm_rf ( path , dry_run = False ) : """Remove a file or directory tree . Won ' t throw an exception , even if the removal fails ."""
log . info ( "removing %s" % path ) if dry_run : return try : if os . path . isdir ( path ) and not os . path . islink ( path ) : shutil . rmtree ( path ) else : os . remove ( path ) except OSError : pass
def _len_lcs ( x , y ) : """Returns the length of the Longest Common Subsequence between sequences x and y . Source : http : / / www . algorithmist . com / index . php / Longest _ Common _ Subsequence : param x : sequence of words : param y : sequence of words : returns integer : Length of LCS between x a...
table = _lcs ( x , y ) n , m = _get_index_of_lcs ( x , y ) return table [ n , m ]
def expand ( self , delta_width , delta_height ) : '''Makes the cloud surface bigger . Maintains all word positions .'''
temp_surface = pygame . Surface ( ( self . width + delta_width , self . height + delta_height ) ) ( self . width , self . height ) = ( self . width + delta_width , self . height + delta_height ) temp_surface . blit ( self . cloud , ( 0 , 0 ) ) self . cloud = temp_surface
def delete_sp_template_for_vlan ( self , vlan_id ) : """Deletes SP Template for a vlan _ id if it exists ."""
with self . session . begin ( subtransactions = True ) : try : self . session . query ( ucsm_model . ServiceProfileTemplate ) . filter_by ( vlan_id = vlan_id ) . delete ( ) except orm . exc . NoResultFound : return
def cartogram ( df , projection = None , scale = None , limits = ( 0.2 , 1 ) , scale_func = None , trace = True , trace_kwargs = None , hue = None , categorical = False , scheme = None , k = 5 , cmap = 'viridis' , vmin = None , vmax = None , legend = False , legend_values = None , legend_labels = None , legend_kwargs =...
# Initialize the figure . fig = _init_figure ( ax , figsize ) # Load the projection . if projection : projection = projection . load ( df , { 'central_longitude' : lambda df : np . mean ( np . array ( [ p . x for p in df . geometry . centroid ] ) ) , 'central_latitude' : lambda df : np . mean ( np . array ( [ p . y...
def check_path_satisfiability ( code_analyzer , path , start_address ) : """Check satisfiability of a basic block path ."""
start_instr_found = False sat = False # Traverse basic blocks , translate its instructions to SMT # expressions and add them as assertions . for bb_curr , bb_next in zip ( path [ : - 1 ] , path [ 1 : ] ) : logger . info ( "BB @ {:#x}" . format ( bb_curr . address ) ) # For each instruction . . . for instr i...
def ip_address ( address ) : """Take an IP string / int and return an object of the correct type . Args : address : A string or integer , the IP address . Either IPv4 or IPv6 addresses may be supplied ; integers less than 2 * * 32 will be considered to be IPv4 by default . Returns : An IPv4Address or IP...
try : return IPv4Address ( address ) except ( AddressValueError , NetmaskValueError ) : pass try : return IPv6Address ( address ) except ( AddressValueError , NetmaskValueError ) : pass raise ValueError ( '%r does not appear to be an IPv4 or IPv6 address' % address )
def fill ( self , field , value ) : """Fill a specified form field in the current document . : param field : an instance of : class : ` zombie . dom . DOMNode ` : param value : any string value : return : self to allow function chaining ."""
self . client . nowait ( 'browser.fill' , ( field , value ) ) return self
def get_inventory ( self , resources ) : """Returns a JSON object with the requested resources and their properties , that are managed by the HMC . This method performs the ' Get Inventory ' HMC operation . Parameters : resources ( : term : ` iterable ` of : term : ` string ` ) : Resource classes and / or...
uri = '/api/services/inventory' body = { 'resources' : resources } result = self . session . post ( uri , body = body ) return result
def run_with_werkzeug ( self , ** options ) : """Run with werkzeug simple wsgi container ."""
threaded = self . threads is not None and ( self . threads > 0 ) self . app . run ( host = self . host , port = self . port , debug = self . debug , threaded = threaded , ** options )
def plot_probe ( mea , ax = None , xlim = None , ylim = None , color_currents = False , top = None , bottom = None , cmap = 'viridis' , type = 'shank' , alpha_elec = 0.7 , alpha_prb = 0.3 ) : '''Parameters mea axis xlim ylim Returns'''
if ax is None : fig = plt . figure ( ) ax = fig . add_subplot ( 111 ) n_elec = mea . positions . shape [ 0 ] elec_size = mea . size if mea . type == 'mea' : mea_pos = np . array ( [ np . dot ( mea . positions , mea . main_axes [ 0 ] ) , np . dot ( mea . positions , mea . main_axes [ 1 ] ) ] ) . T min_x ...
def record_diff ( lhs , rhs ) : "Diff an individual row ."
delta = { } for k in set ( lhs ) . union ( rhs ) : from_ = lhs [ k ] to_ = rhs [ k ] if from_ != to_ : delta [ k ] = { 'from' : from_ , 'to' : to_ } return delta
def _load_config ( config_filepath : str ) -> Dict [ str , Any ] : """Loads YAML config file to dictionary : returns : dict from YAML config file"""
try : config : Dict [ str , Any ] = yaml . load ( stream = open ( config_filepath , "r" ) ) except Exception as e : raise Exception ( f"Invalid DAG Factory config file; err: {e}" ) return config
def main ( _ ) : """Create or load configuration and launch the trainer ."""
utility . set_up_logging ( ) if not FLAGS . config : raise KeyError ( 'You must specify a configuration.' ) logdir = FLAGS . logdir and os . path . expanduser ( os . path . join ( FLAGS . logdir , '{}-{}' . format ( FLAGS . timestamp , FLAGS . config ) ) ) try : config = utility . load_config ( logdir ) except ...
def sadd ( self , key , * members ) : """Add the specified members to the set stored at key . Specified members that are already a member of this set are ignored . If key does not exist , a new set is created before adding the specified members . An error is returned when the value stored at key is not a set ...
return self . _execute ( [ b'SADD' , key ] + list ( members ) , len ( members ) )
def _node_le ( self , node_self , node_other ) : '''_ node _ le Low - level api : Return True if all descendants of one node exist in the other node . Otherwise False . This is a recursive method . Parameters node _ self : ` Element ` A node to be compared . node _ other : ` Element ` Another node to ...
for x in [ 'tag' , 'text' , 'tail' ] : if node_self . __getattribute__ ( x ) != node_other . __getattribute__ ( x ) : return False for a in node_self . attrib : if a not in node_other . attrib or node_self . attrib [ a ] != node_other . attrib [ a ] : return False for child in node_self . getchi...
def _report_container_spec_metrics ( self , pod_list , instance_tags ) : """Reports pod requests & limits by looking at pod specs ."""
for pod in pod_list [ 'items' ] : pod_name = pod . get ( 'metadata' , { } ) . get ( 'name' ) pod_phase = pod . get ( 'status' , { } ) . get ( 'phase' ) if self . _should_ignore_pod ( pod_name , pod_phase ) : continue for ctr in pod [ 'spec' ] [ 'containers' ] : if not ctr . get ( 'resour...
def memory_read16 ( self , addr , num_halfwords , zone = None ) : """Reads memory from the target system in units of 16 - bits . Args : self ( JLink ) : the ` ` JLink ` ` instance addr ( int ) : start address to read from num _ halfwords ( int ) : number of half words to read zone ( str ) : memory zone to...
return self . memory_read ( addr , num_halfwords , zone = zone , nbits = 16 )
def __add_kickoff_task ( cls , job_config , mapreduce_spec ) : """Add kickoff task to taskqueue . Args : job _ config : map _ job . JobConfig . mapreduce _ spec : model . MapreduceSpec ,"""
params = { "mapreduce_id" : job_config . job_id } # Task is not named so that it can be added within a transaction . kickoff_task = taskqueue . Task ( # TODO ( user ) : Perhaps make this url a computed field of job _ config . url = job_config . _base_path + "/kickoffjob_callback/" + job_config . job_id , headers = util...
def set_maxsize ( self , maxsize , ** kwargs ) : """Set maxsize . This involves creating a new cache and transferring the items ."""
new_cache = self . _get_cache_impl ( self . impl_name , maxsize , ** kwargs ) self . _populate_new_cache ( new_cache ) self . cache = new_cache
def get_bio ( self , section , language = None ) : """Returns a section of the bio . section can be " content " , " summary " or " published " ( for published date )"""
if language : params = self . _get_params ( ) params [ "lang" ] = language else : params = None return self . _extract_cdata_from_request ( self . ws_prefix + ".getInfo" , section , params )
def get ( self , name , section = None , fallback = False ) : """Returns a previously registered preference : param section : The section name under which the preference is registered : type section : str . : param name : The name of the preference . You can use dotted notation ' section . name ' if you want ...
# try dotted notation try : _section , name = name . split ( preferences_settings . SECTION_KEY_SEPARATOR ) return self [ _section ] [ name ] except ValueError : pass # use standard params try : return self [ section ] [ name ] except KeyError : if fallback : return self . _fallback ( sectio...
def mapIdentity ( self , primarySubject , secondarySubject , vendorSpecific = None ) : """See Also : mapIdentityResponse ( ) Args : primarySubject : secondarySubject : vendorSpecific : Returns :"""
response = self . mapIdentityResponse ( primarySubject , secondarySubject , vendorSpecific ) return self . _read_boolean_response ( response )
def remove_atoms ( self , indices ) : """Remove the atoms positioned at * indices * . The molecule containing the atom is removed as well . If you have a system of 10 water molecules ( and 30 atoms ) , if you remove the atoms at indices 0 , 1 and 29 you will remove the first and last water molecules . * *...
mol_indices = self . atom_to_molecule_indices ( indices ) self . copy_from ( self . sub ( molecule_index = mol_indices ) )
def p_common_scalar_magic_file ( p ) : 'common _ scalar : FILE'
value = getattr ( p . lexer , 'filename' , None ) p [ 0 ] = ast . MagicConstant ( p [ 1 ] . upper ( ) , value , lineno = p . lineno ( 1 ) )
def trim_common_suffixes ( strs , min_len = 0 ) : """trim common suffixes > > > trim _ common _ suffixes ( ' A ' , 1) (0 , ' A ' )"""
if len ( strs ) < 2 : return 0 , strs rev_strs = [ s [ : : - 1 ] for s in strs ] trimmed , rev_strs = trim_common_prefixes ( rev_strs , min_len ) if trimmed : strs = [ s [ : : - 1 ] for s in rev_strs ] return trimmed , strs