signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_followers ( id_ = None , screen_name = None , limit = 1e10 ) : """Either id _ or screen _ name must not be None ."""
# FIXME : DRY from _ tweets _ for _ user if not ( id_ or screen_name ) : raise Exception ( "either id_ or screen_name must not be None" ) if id_ : key = 'user_id' val = id_ else : key = 'screen_name' val = screen_name cursor = - 1 followers = [ ] while len ( followers ) < limit : try : r...
def install ( self , updates ) : '''Install the updates passed in the updates collection . Load the updates collection using the ` ` search ` ` or ` ` available ` ` functions . If the updates need to be downloaded , use the ` ` download ` ` function . Args : updates ( Updates ) : An instance of the Updates ...
# Check for empty list if updates . count ( ) == 0 : ret = { 'Success' : False , 'Updates' : 'Nothing to install' } return ret installer = self . _session . CreateUpdateInstaller ( ) self . _session . ClientApplicationID = 'Salt: Install Update' with salt . utils . winapi . Com ( ) : install_list = win32com...
def fix_surrogates ( text ) : """Replace 16 - bit surrogate codepoints with the characters they represent ( when properly paired ) , or with \ufffd otherwise . > > > high _ surrogate = chr ( 0xd83d ) > > > low _ surrogate = chr ( 0xdca9) > > > print ( fix _ surrogates ( high _ surrogate + low _ surrogate ) ...
if SURROGATE_RE . search ( text ) : text = SURROGATE_PAIR_RE . sub ( convert_surrogate_pair , text ) text = SURROGATE_RE . sub ( '\ufffd' , text ) return text
def count ( self ) : """Counts the number of results that could be accessed with the current parameters . : return : number of objects matches to the query : rtype : int"""
# Save the existing rows and start parameters to see how many results were actually expected _rows = self . _solr_params . get ( 'rows' , None ) _start = self . _solr_params . get ( 'start' , 0 ) if not self . _solr_cache : # Get the count for everything self . set_params ( rows = 0 ) self . _exec_query ( ) num...
def http_get ( url , fout = None ) : """Download a file from http . Save it in a file named by fout"""
print ( 'requests.get({URL}, stream=True)' . format ( URL = url ) ) rsp = requests . get ( url , stream = True ) if rsp . status_code == 200 and fout is not None : with open ( fout , 'wb' ) as prt : for chunk in rsp : # . iter _ content ( chunk _ size = 128 ) : prt . write ( chunk ) prin...
def append_text ( self , content ) : """Append text nodes into L { Content . data } Here is where the I { true } type is used to translate the value into the proper python type . @ param content : The current content being unmarshalled . @ type content : L { Content }"""
Core . append_text ( self , content ) known = self . resolver . top ( ) . resolved content . text = self . translated ( content . text , known )
def get_old_value ( self , args , kwargs , default = None ) : # type : ( List [ Any ] , Dict [ str , Any ] , Any ) - > Any """Returns the old value of the named argument without replacing it . Returns ` ` default ` ` if the argument is not present ."""
if self . arg_pos is not None and len ( args ) > self . arg_pos : return args [ self . arg_pos ] else : return kwargs . get ( self . name , default )
def _CreateDictReader ( self , line_reader ) : """Iterates over the log lines and provide a reader for the values . Args : line _ reader ( iter ) : yields each line in the log file . Yields : dict [ str , str ] : column values keyed by column header ."""
for line in line_reader : if isinstance ( line , py2to3 . BYTES_TYPE ) : try : line = codecs . decode ( line , self . _encoding ) except UnicodeDecodeError as exception : raise errors . UnableToParseFile ( 'Unable decode line with error: {0!s}' . format ( exception ) ) st...
def _copy_cell_text ( self ) : """Copies the description of the selected message to the clipboard"""
txt = self . currentItem ( ) . text ( ) QtWidgets . QApplication . clipboard ( ) . setText ( txt )
def write ( self , session , directory , name , replaceParamFile = None , ** kwargs ) : """Wrapper for GsshaPyFileObjectBase write method"""
if self . raster is not None or self . rasterText is not None : super ( RasterMapFile , self ) . write ( session , directory , name , replaceParamFile , ** kwargs )
def write_array_metadata ( dataset , array ) : """Write metadata for ` ` array ` ` into the ` h5py . Dataset `"""
for attr in ( 'unit' , ) + array . _metadata_slots : # format attribute try : value = _format_metadata_attribute ( getattr ( array , '_%s' % attr , None ) ) except IgnoredAttribute : continue # store attribute try : dataset . attrs [ attr ] = value except ( TypeError , ValueE...
def match ( elem , seq_expr ) : """Return True if elem ( an element of elem _ list ) matches seq _ expr , an element in self . sequence"""
if type ( seq_expr ) is str : # wild - card if seq_expr == '.' : # match any element return True elif seq_expr == '\d' : return elem . is_numerical ( ) elif seq_expr == '\D' : return not elem . is_numerical ( ) else : # invalid wild - card specified raise LookupError ( '{...
def process_json_rec ( self , data , name , idx , sub_idx ) : """Processes json rec - json object : param data : : param name : : param idx : : param sub _ idx : : return :"""
ret = [ ] if isinstance ( data , list ) : for kidx , rec in enumerate ( data ) : sub = self . process_json_rec ( rec , name , idx , list ( sub_idx + [ kidx ] ) ) ret . append ( sub ) return ret if isinstance ( data , dict ) : for key in data : rec = data [ key ] sub = self . ...
def local_moe_tpu ( inputs , hidden_size , output_size , num_experts , loss_coef = 1e-3 , overhead = 1.0 ) : """Local mixture of experts that works well on TPU . See https : / / arxiv . org / abs / 1701.06538 There are num _ experts expert networks , each containing a relu - activated hidden layer of size hid...
batch , length , input_size = common_layers . shape_list ( inputs ) [ : ] # Each sequence sends expert _ capacity positions to each expert . if isinstance ( length , int ) : expert_capacity = min ( length , int ( ( length * 2 * overhead ) / num_experts ) ) else : expert_capacity = tf . minimum ( length , tf . t...
def _graphql_request_count_per_sliding_window ( self , query_hash : str ) -> int : """Return how many GraphQL requests can be done within the sliding window ."""
if self . is_logged_in : max_reqs = { '1cb6ec562846122743b61e492c85999f' : 20 , '33ba35852cb50da46f5b5e889df7d159' : 20 } else : max_reqs = { '1cb6ec562846122743b61e492c85999f' : 200 , '33ba35852cb50da46f5b5e889df7d159' : 200 } return max_reqs . get ( query_hash ) or min ( max_reqs . values ( ) )
async def acquire ( self , blocking = None , blocking_timeout = None ) : """Use Redis to hold a shared , distributed lock named ` ` name ` ` . Returns True once the lock is acquired . If ` ` blocking ` ` is False , always return immediately . If the lock was acquired , return True , otherwise return False . ...
sleep = self . sleep token = b ( uuid . uuid1 ( ) . hex ) if blocking is None : blocking = self . blocking if blocking_timeout is None : blocking_timeout = self . blocking_timeout stop_trying_at = None if blocking_timeout is not None : stop_trying_at = mod_time . time ( ) + blocking_timeout while True : ...
def set_published ( self , value = None ) : """stub"""
if value is None : raise NullArgument ( ) if self . get_published_metadata ( ) . is_read_only ( ) : raise NoAccess ( ) if not self . my_osid_object_form . _is_valid_boolean ( value ) : raise InvalidArgument ( ) self . my_osid_object_form . _my_map [ 'published' ] = value
def _update_triplestore ( self , es_result , action_list , ** kwargs ) : """updates the triplestore with success of saves and failues of indexing Args : es _ result : the elasticsearch result list action _ list : list of elasticsearch action items that were indexed"""
idx_time = XsdDatetime ( datetime . datetime . utcnow ( ) ) uri_keys = { } bnode_keys = { } for item in action_list : try : uri_keys [ item [ '_id' ] ] = item [ '_source' ] [ "uri" ] except KeyError : bnode_keys [ item [ '_id' ] ] = item [ '_id' ] error_dict = { } error_bnodes = { } if es_result...
def get_total_size ( self , entries ) : """Returns the total size of a collection of entries . : param entries : ` ` list ` ` of entries to calculate the total size of ."""
size = 0 for entry in entries : if entry [ 'response' ] [ 'bodySize' ] > 0 : size += entry [ 'response' ] [ 'bodySize' ] return size
def save_form ( self , request , form , change ) : """Given a ModelForm return an unsaved instance . ` ` change ` ` is True if the object is being changed , and False if it ' s being added ."""
r = form . save ( commit = False ) parent_id = request . REQUEST . get ( 'parent_id' , None ) if parent_id : parent = Folder . objects . get ( id = parent_id ) r . parent = parent return r
def from_data ( cls , blob ) : """Restore an object instance from a compressed datablob . Returns an instance of a concrete subclass ."""
version , data = decompress_datablob ( DATA_BLOB_MAGIC_RETRY , blob ) if version == 1 : for clazz in cls . _all_subclasses ( ) : if clazz . __name__ == data [ "_class_name" ] : return clazz . _from_data_v1 ( data ) raise Exception ( "Invalid data blob data or version" )
def _get_placeholder_arg ( arg_name , placeholder ) : """Validate and return the Placeholder object that the template variable points to ."""
if placeholder is None : raise RuntimeWarning ( u"placeholder object is None" ) elif isinstance ( placeholder , Placeholder ) : return placeholder elif isinstance ( placeholder , Manager ) : manager = placeholder try : parent_object = manager . instance # read RelatedManager code exc...
def toggle ( self , section , option ) : """Toggles option in section ."""
self . set ( section , option , not self . get ( section , option ) )
def main ( api_key , token , board_id ) : """List out the board lists for our client"""
trello_client = TrelloClient ( api_key = api_key , token = token , ) board = Board ( client = trello_client , board_id = board_id ) print ( 'Lists' ) print ( '-----' ) print ( 'Name: Id' ) for card_list in board . all_lists ( ) : print ( '{card_list.name}: {card_list.id}' . format ( card_list = card_list ) )
def start_tasks ( self ) : """Start however many tasks we can based on our limits and what we have left to finish ."""
while self . tasks_at_once > len ( self . pending_results ) and self . _has_more_tasks ( ) : task , parent_result = self . tasks . popleft ( ) self . execute_task ( task , parent_result )
def _as_document ( self , dataset ) : """Converts dataset to document indexed by to FTS index . Args : dataset ( orm . Dataset ) : dataset to convert . Returns : dict with structure matches to BaseDatasetIndex . _ schema ."""
assert isinstance ( dataset , Dataset ) doc = super ( self . __class__ , self ) . _as_document ( dataset ) # SQLite FTS can ' t find terms with ` - ` , replace it with underscore here and while searching . # See http : / / stackoverflow . com / questions / 3865733 / how - do - i - escape - the - character - in - sqlite...
def roc_auc ( y_true , y_score ) : """Returns are under the ROC curve"""
notnull = ~ np . isnan ( y_true ) fpr , tpr , thresholds = sklearn . metrics . roc_curve ( y_true [ notnull ] , y_score [ notnull ] ) return sklearn . metrics . auc ( fpr , tpr )
def validate_uuid_representation ( dummy , value ) : """Validate the uuid representation option selected in the URI ."""
try : return _UUID_REPRESENTATIONS [ value ] except KeyError : raise ValueError ( "%s is an invalid UUID representation. " "Must be one of " "%s" % ( value , tuple ( _UUID_REPRESENTATIONS ) ) )
def save_relationship ( self , relationship_form , * args , ** kwargs ) : """Pass through to provider RelationshipAdminSession . update _ relationship"""
# Implemented from kitosid template for - # osid . resource . ResourceAdminSession . update _ resource if relationship_form . is_for_update ( ) : return self . update_relationship ( relationship_form , * args , ** kwargs ) else : return self . create_relationship ( relationship_form , * args , ** kwargs )
def get_account_api_key ( self , account_id , api_key , ** kwargs ) : # noqa : E501 """Get API key details . # noqa : E501 An endpoint for retrieving API key details . * * Example usage : * * ` curl https : / / api . us - east - 1 . mbedcloud . com / v3 / accounts / { accountID } / api - keys / { apiKey } - H ' A...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . get_account_api_key_with_http_info ( account_id , api_key , ** kwargs ) # noqa : E501 else : ( data ) = self . get_account_api_key_with_http_info ( account_id , api_key , ** kwargs ) # noqa : E501 return da...
def open ( self , fnames = None ) : """Open files with the appropriate application"""
if fnames is None : fnames = self . get_selected_filenames ( ) for fname in fnames : if osp . isfile ( fname ) and encoding . is_text_file ( fname ) : self . parent_widget . sig_open_file . emit ( fname ) else : self . open_outside_spyder ( [ fname ] )
def show_all_prs ( self ) : """Log all PRs grouped by state ."""
for __ , prs in self . collect_prs_info ( ) . items ( ) : for pr_info in prs : logger . info ( '{url} in state {state} ({merged})' . format ( ** pr_info ) )
def secure_randint ( min_value , max_value , system_random = None ) : """Return a random integer N such that a < = N < = b . Uses SystemRandom for generating random numbers . ( which uses os . urandom ( ) , which pulls from / dev / urandom )"""
if not system_random : system_random = random . SystemRandom ( ) return system_random . randint ( min_value , max_value )
def copy_texture_memory_args ( self , texmem_args ) : """adds texture memory arguments to the most recently compiled module : param texmem _ args : A dictionary containing the data to be passed to the device texture memory . TODO"""
filter_mode_map = { 'point' : drv . filter_mode . POINT , 'linear' : drv . filter_mode . LINEAR } address_mode_map = { 'border' : drv . address_mode . BORDER , 'clamp' : drv . address_mode . CLAMP , 'mirror' : drv . address_mode . MIRROR , 'wrap' : drv . address_mode . WRAP } logging . debug ( 'copy_texture_memory_args...
def get_private_key ( key_path , password_path = None ) : """Open a JSON - encoded private key and return it If a password file is provided , uses it to decrypt the key . If not , the password is asked interactively . Raw hex - encoded private keys are supported , but deprecated ."""
assert key_path , key_path if not os . path . exists ( key_path ) : log . fatal ( '%s: no such file' , key_path ) return None if not check_permission_safety ( key_path ) : log . fatal ( 'Private key file %s must be readable only by its owner.' , key_path ) return None if password_path and not check_perm...
def readGTF ( infile ) : """Reads a GTF file and labels the respective columns in agreement with GTF file standards : ' seqname ' , ' source ' , ' feature ' , ' start ' , ' end ' , ' score ' , ' strand ' , ' frame ' , ' attribute ' . : param infile : path / to / file . gtf : returns : a Pandas dataframe of th...
df = pd . read_table ( infile , sep = '\t' , comment = "#" , header = None , dtype = str ) df . columns = [ 'seqname' , 'source' , 'feature' , 'start' , 'end' , 'score' , 'strand' , 'frame' , 'attribute' ] # df = df . astype ( str ) # from DTC return df
def counter ( self , name ) : """Returns an existing or creates and returns a new counter : param name : name of the counter : return : the counter object"""
with self . _lock : if name not in self . _counters : if self . _registry . _ignore_patterns and any ( pattern . match ( name ) for pattern in self . _registry . _ignore_patterns ) : counter = noop_metric else : counter = Counter ( name ) self . _counters [ name ] = c...
def check_for_usable_environment ( self ) : """Check if the current env is usable and has everything ' s required ."""
# Do not let the user run Mackup as root if os . geteuid ( ) == 0 : utils . error ( "Running Mackup as a superuser is useless and" " dangerous. Don't do it!" ) # Do we have a folder to put the Mackup folder ? if not os . path . isdir ( self . _config . path ) : utils . error ( "Unable to find the storage folder...
def __decode_webpush_b64 ( self , data ) : """Re - pads and decodes urlsafe base64."""
missing_padding = len ( data ) % 4 if missing_padding != 0 : data += '=' * ( 4 - missing_padding ) return base64 . urlsafe_b64decode ( data )
def slang_time ( self , locale = "en" ) : """" Returns human slang representation of time . Keyword Arguments : locale - - locale to translate to , e . g . ' fr ' for french . ( default : ' en ' - English )"""
dt = self . datetime ( ) return pendulum . instance ( dt ) . diff_for_humans ( locale = locale )
def dir_df_boot ( dir_df , nb = 5000 , par = False ) : """Performs a bootstrap for direction DataFrame with optional parametric bootstrap Parameters _ _ _ _ _ dir _ df : Pandas DataFrame with columns : dir _ dec : mean declination dir _ inc : mean inclination Required for parametric bootstrap dir _ n ...
N = dir_df . dir_dec . values . shape [ 0 ] # number of data points BDIs = [ ] for k in range ( nb ) : pdir_df = dir_df . sample ( n = N , replace = True ) # bootstrap pseudosample pdir_df . reset_index ( inplace = True ) # reset the index if par : # do a parametric bootstrap for i in pdir_d...
def create ( self , handle = None , handle_type = None , ** args ) : """Creates an ontology based on a handle Handle is one of the following - ` FILENAME . json ` : creates an ontology from an obographs json file - ` obo : ONTID ` : E . g . obo : pato - creates an ontology from obolibrary PURL ( requires owlt...
if handle is None : self . test = self . test + 1 logging . info ( "T: " + str ( self . test ) ) global default_ontology if default_ontology is None : logging . info ( "Creating new instance of default ontology" ) default_ontology = create_ontology ( default_ontology_handle ) logging...
def inform ( self , msg ) : """Send an inform message to a particular client . Should only be used for asynchronous informs . Informs that are part of the response to a request should use : meth : ` reply _ inform ` so that the message identifier from the original request can be attached to the inform . ...
assert ( msg . mtype == Message . INFORM ) return self . _send_message ( msg )
def show_content ( self , with_content = False ) : """Checks if the state is a library with the ` show _ content ` flag set : param with _ content : If this parameter is ` True ` , the method return only True if the library represents a ContainerState : return : Whether the content of a library state is shown...
if isinstance ( self . model , LibraryStateModel ) and self . model . show_content ( ) : return not with_content or isinstance ( self . model . state_copy , ContainerStateModel ) return False
def handle_error ( self , error , req , schema , error_status_code , error_headers ) : """Handles errors during parsing . Aborts the current HTTP request and responds with a 400 error ."""
status_code = error_status_code or self . DEFAULT_VALIDATION_STATUS response = exception_response ( status_code , detail = text_type ( error ) , headers = error_headers , content_type = "application/json" , ) body = json . dumps ( error . messages ) response . body = body . encode ( "utf-8" ) if isinstance ( body , tex...
def _convert_appengine_app_assertion_credentials ( credentials ) : """Converts to : class : ` google . auth . app _ engine . Credentials ` . Args : credentials ( oauth2client . contrib . app _ engine . AppAssertionCredentials ) : The credentials to convert . Returns : google . oauth2 . service _ account ....
# pylint : disable = invalid - name return google . auth . app_engine . Credentials ( scopes = _helpers . string_to_scopes ( credentials . scope ) , service_account_id = credentials . service_account_id )
def to_request ( self , iface_name , func_name , params ) : """Converts the arguments to a JSON - RPC request dict . The ' id ' field is populated using the id _ gen function passed to the Client constructor . If validate _ request = = True on the Client constructor , the params are validated against the expe...
if self . validate_req : self . contract . validate_request ( iface_name , func_name , params ) method = "%s.%s" % ( iface_name , func_name ) reqid = self . id_gen ( ) return { "jsonrpc" : "2.0" , "id" : reqid , "method" : method , "params" : params }
def _ordered ( self , odict ) : """Convert the object into a plain OrderedDict ."""
ndict = OrderedDict ( ) if isinstance ( odict , CatDict ) or isinstance ( odict , Entry ) : key = odict . sort_func else : key = None nkeys = list ( sorted ( odict . keys ( ) , key = key ) ) for key in nkeys : if isinstance ( odict [ key ] , OrderedDict ) : odict [ key ] = self . _ordered ( odict [ ...
def _next_lexem ( self , lexem_type , source_code , source_code_size ) : """Return next readable lexem of given type in source _ code . If no value can be found , the neutral _ value will be used"""
# define reader as a lexem extractor def reader ( seq , block_size ) : identificator = '' for char in source_code : if len ( identificator ) == self . idnt_values_size [ lexem_type ] : yield self . table_values [ lexem_type ] [ identificator ] identificator = '' identific...
def input_value ( self , locator , text ) : """Sets the given value into text field identified by ` locator ` . This is an IOS only keyword , input value makes use of set _ value See ` introduction ` for details about locating elements ."""
self . _info ( "Setting text '%s' into text field '%s'" % ( text , locator ) ) self . _element_input_value_by_locator ( locator , text )
def get_controversial ( self , * args , ** kwargs ) : """Return a get _ content generator for controversial submissions . Corresponds to submissions provided by ` ` https : / / www . reddit . com / controversial / ` ` for the session . The additional parameters are passed directly into : meth : ` . get _ co...
return self . get_content ( self . config [ 'controversial' ] , * args , ** kwargs )
def findSequencesOnDisk ( cls , pattern , include_hidden = False , strictPadding = False ) : """Yield the sequences found in the given directory . Examples : > > > findSequencesOnDisk ( ' / path / to / files ' ) The ` pattern ` can also specify glob - like shell wildcards including the following : * ` ` ? `...
# reserve some functions we ' re going to need quick access to _not_hidden = lambda f : not f . startswith ( '.' ) _match_pattern = None _filter_padding = None _join = os . path . join seq = None dirpath = pattern # Support the pattern defining a filter for the files # in the existing directory if not os . path . isdir...
def trigger_event ( self , element , event , event_type = None , options = None ) : """: Description : Trigger specified event of the given element . : param element : Element for browser instance to target . : type element : WebElement , ( WebElement , . . . ) : param event : Event to trigger from target ele...
if not isinstance ( element , ( tuple , list ) ) : element = [ element ] if not isinstance ( event , ( tuple , list ) ) : event = [ event ] for el in element : for e in event : self . browser . execute_script ( 'e = new %s("%s"); ops = %s; if (ops) {for(key in ops) { \ Object...
def insert_file ( file , media_type ) : """Upsert the ` ` file ` ` and ` ` media _ type ` ` into the files table . Returns the ` ` fileid ` ` and ` ` sha1 ` ` of the upserted file ."""
resource_hash = get_file_sha1 ( file ) with db_connect ( ) as db_conn : with db_conn . cursor ( ) as cursor : cursor . execute ( "SELECT fileid FROM files WHERE sha1 = %s" , ( resource_hash , ) ) try : fileid = cursor . fetchone ( ) [ 0 ] except ( IndexError , TypeError ) : ...
def GetMemZipSavedMB ( self ) : '''Undocumented .'''
counter = c_uint ( ) ret = vmGuestLib . VMGuestLib_GetMemZipSavedMB ( self . handle . value , byref ( counter ) ) if ret != VMGUESTLIB_ERROR_SUCCESS : raise VMGuestLibException ( ret ) return counter . value
def implementation ( self , for_type = None , for_types = None ) : """Return a decorator that will register the implementation . Example : @ multimethod def add ( x , y ) : pass @ add . implementation ( for _ type = int ) def add ( x , y ) : return x + y @ add . implementation ( for _ type = SomeTyp...
for_types = self . __get_types ( for_type , for_types ) def _decorator ( implementation ) : self . implement ( implementation , for_types = for_types ) return self return _decorator
def make_common_parser ( ) : """Creates an argument parser ( argparse module ) with the options that should be common to all shells . The result can be used as a parent parser ( ` ` parents ` ` argument in ` ` argparse . ArgumentParser ` ` ) : return : An ArgumentParser object"""
parser = argparse . ArgumentParser ( add_help = False ) # Version number parser . add_argument ( "--version" , action = "version" , version = "Pelix {0} from {1}" . format ( pelix . __version__ , pelix . __file__ ) , ) # Framework options group = parser . add_argument_group ( "Framework options" ) group . add_argument ...
def _make_coroutine_wrapper ( func , replace_callback ) : """The inner workings of ` ` @ gen . coroutine ` ` and ` ` @ gen . engine ` ` . The two decorators differ in their treatment of the ` ` callback ` ` argument , so we cannot simply implement ` ` @ engine ` ` in terms of ` ` @ coroutine ` ` ."""
# On Python 3.5 , set the coroutine flag on our generator , to allow it # to be used with ' await ' . wrapped = func if hasattr ( types , 'coroutine' ) : func = types . coroutine ( func ) @ functools . wraps ( wrapped ) def wrapper ( * args , ** kwargs ) : future = TracebackFuture ( ) if replace_callback an...
def activate_introjs ( driver ) : """Allows you to use IntroJS Tours with SeleniumBase https : / / introjs . com /"""
intro_css = constants . IntroJS . MIN_CSS intro_js = constants . IntroJS . MIN_JS verify_script = ( """// Verify IntroJS activated var intro2 = introJs(); """ ) activate_bootstrap ( driver ) js_utils . wait_for_ready_state_complete ( driver ) js_utils . wait_for_angularjs ( dri...
def readPattern ( self ) : """Read the entire color pattern : return List of pattern line tuples"""
if ( self . dev == None ) : return '' pattern = [ ] for i in range ( 0 , 16 ) : # FIXME : adjustable for diff blink ( 1 ) models pattern . append ( self . readPatternLine ( i ) ) return pattern
def get_value_by_row_col ( self , row , col ) : """Get raster value by ( row , col ) . Args : row : row number . col : col number . Returns : raster value , None if the input are invalid ."""
if row < 0 or row >= self . nRows or col < 0 or col >= self . nCols : raise ValueError ( "The row or col must be >=0 and less than " "nRows (%d) or nCols (%d)!" % ( self . nRows , self . nCols ) ) else : value = self . data [ int ( round ( row ) ) ] [ int ( round ( col ) ) ] if value == self . noDataValue :...
def confidence_interval ( self , confidenceLevel ) : """Calculates for which value confidenceLevel % of the errors are closer to 0. : param float confidenceLevel : percentage of the errors that should be smaller than the returned value for overestimations and larger than the returned value for underestimation...
if not ( confidenceLevel >= 0 and confidenceLevel <= 1 ) : raise ValueError ( "Parameter percentage has to be in [0,1]" ) underestimations = [ ] overestimations = [ ] for error in self . _errorValues : if error is None : # None was in the lists causing some confidenceLevels not be calculated , not sure if that ...
def get_doc ( self ) : """Get the proposed object ' s docstring . Returns None if it can not be get ."""
if not self . pyname : return None pyobject = self . pyname . get_object ( ) if not hasattr ( pyobject , 'get_doc' ) : return None return self . pyname . get_object ( ) . get_doc ( )
def timed_connectivity_check ( self , event ) : """Tests internet connectivity in regular intervals and updates the nodestate accordingly"""
self . status = self . _can_connect ( ) self . log ( 'Timed connectivity check:' , self . status , lvl = verbose ) if self . status : if not self . old_status : self . log ( 'Connectivity gained' ) self . fireEvent ( backend_nodestate_toggle ( STATE_UUID_CONNECTIVITY , on = True , force = True ) ) e...
def roundrobin ( * iterables ) : "roundrobin ( ' ABC ' , ' D ' , ' EF ' ) - - > A D E B F C"
# Recipe credited to George Sakkis pending = len ( iterables ) nexts = itertools . cycle ( iter ( it ) . next for it in iterables ) while pending : try : for next in nexts : yield next ( ) except StopIteration : pending -= 1 nexts = itertools . cycle ( itertools . islice ( ne...
def last_time_non_ok_or_up ( self ) : """Get the last time the host was in a non - OK state : return : self . last _ time _ down if self . last _ time _ down > self . last _ time _ up , 0 otherwise : rtype : int"""
non_ok_times = [ x for x in [ self . last_time_down ] if x > self . last_time_up ] if not non_ok_times : last_time_non_ok = 0 # todo : program _ start would be better ? else : last_time_non_ok = min ( non_ok_times ) return last_time_non_ok
def show_system_monitor_output_switch_status_rbridge_id_out ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) show_system_monitor = ET . Element ( "show_system_monitor" ) config = show_system_monitor output = ET . SubElement ( show_system_monitor , "output" ) switch_status = ET . SubElement ( output , "switch-status" ) rbridge_id_out = ET . SubElement ( switch_status , "rbridge-id-out" ) rbri...
def cell_scalar ( mesh , name ) : """Returns cell scalars of a vtk object"""
vtkarr = mesh . GetCellData ( ) . GetArray ( name ) if vtkarr : if isinstance ( vtkarr , vtk . vtkBitArray ) : vtkarr = vtk_bit_array_to_char ( vtkarr ) return vtk_to_numpy ( vtkarr )
def deploy ( self , package = None ) : """If package is none , use ` deployment _ package . default ( ) `"""
if package is None : package = deployment_package . default ( ) package . deploy ( ) if self . proper_name in installed_functions ( ) : self . update ( package ) else : self . install ( package )
def copy_object ( self , bucket_name , object_name , object_source , conditions = None , source_sse = None , sse = None , metadata = None ) : """Copy a source object on object storage server to a new object . NOTE : Maximum object size supported by this API is 5GB . Examples : : param bucket _ name : Bucket o...
is_valid_bucket_name ( bucket_name ) is_non_empty_string ( object_name ) is_non_empty_string ( object_source ) headers = { } # Preserving the user - defined metadata in headers if metadata is not None : headers = amzprefix_user_metadata ( metadata ) headers [ "x-amz-metadata-directive" ] = "REPLACE" if conditio...
def _get_backend_router ( self , locations , item ) : """Returns valid router options for ordering a dedicated host ."""
mask = ''' id, hostname ''' cpu_count = item [ 'capacity' ] for capacity in item [ 'bundleItems' ] : for category in capacity [ 'categories' ] : if category [ 'categoryCode' ] == 'dedicated_host_ram' : mem_capacity = capacity [ 'capacity' ] if category [ '...
def check_vpc ( vpc_id = None , vpc_name = None , region = None , key = None , keyid = None , profile = None ) : '''Check whether a VPC with the given name or id exists . Returns the vpc _ id or None . Raises SaltInvocationError if both vpc _ id and vpc _ name are None . Optionally raise a CommandExecutionErr...
if not _exactly_one ( ( vpc_name , vpc_id ) ) : raise SaltInvocationError ( 'One (but not both) of vpc_id or vpc_name ' 'must be provided.' ) if vpc_name : vpc_id = _get_id ( vpc_name = vpc_name , region = region , key = key , keyid = keyid , profile = profile ) elif not _find_vpcs ( vpc_id = vpc_id , region = ...
def set_kernel_parameter_and_add_padding ( node , kp , pad_mode , pad_val , base_name , func_counter ) : """Set kernel related parameters ( strides , pads , kernel _ shape ) to the given parameter . This function also generates a padding function if we need a seperate pad function for asymmetry padding ."""
dims = [ ] strides = [ ] pads = [ ] kernel = [ ] for attr in node . attribute : if attr . name == "strides" : if attr . type != AttributeProto . INTS : raise ValueError ( "Only INTS are supported for strides in {}" . format ( node . op_type ) ) strides . extend ( attr . ints ) di...
def svg2paths2 ( svg_file_location , return_svg_attributes = True , convert_circles_to_paths = True , convert_ellipses_to_paths = True , convert_lines_to_paths = True , convert_polylines_to_paths = True , convert_polygons_to_paths = True , convert_rectangles_to_paths = True ) : """Convenience function ; identical t...
return svg2paths ( svg_file_location = svg_file_location , return_svg_attributes = return_svg_attributes , convert_circles_to_paths = convert_circles_to_paths , convert_ellipses_to_paths = convert_ellipses_to_paths , convert_lines_to_paths = convert_lines_to_paths , convert_polylines_to_paths = convert_polylines_to_pat...
def set_forbidden_uptodate ( self , uptodate ) : """Set all forbidden uptodate values : param uptodatees : a list with forbidden uptodate values : uptodate uptodatees : list : returns : None : ruptodate : None : raises : None"""
if self . _forbidden_uptodate == uptodate : return self . _forbidden_uptodate = uptodate self . invalidateFilter ( )
def drop ( self , arg ) : """overload of pandas . DataFrame . drop ( ) Parameters arg : iterable argument to pass to pandas . DataFrame . drop ( ) Returns Ensemble : Ensemble"""
df = super ( Ensemble , self ) . drop ( arg ) return type ( self ) ( data = df , pst = self . pst )
def save ( self , filename , store_password ) : """Convenience wrapper function ; calls the : func : ` saves ` and saves the content to a file ."""
with open ( filename , 'wb' ) as file : keystore_bytes = self . saves ( store_password ) file . write ( keystore_bytes )
def sparse_diff ( array , n = 1 , axis = - 1 ) : """A ported sparse version of np . diff . Uses recursion to compute higher order differences Parameters array : sparse array n : int , default : 1 differencing order axis : int , default : - 1 axis along which differences are computed Returns diff _...
if ( n < 0 ) or ( int ( n ) != n ) : raise ValueError ( 'Expected order is non-negative integer, ' 'but found: {}' . format ( n ) ) if not sp . sparse . issparse ( array ) : warnings . warn ( 'Array is not sparse. Consider using numpy.diff' ) if n == 0 : return array nd = array . ndim slice1 = [ slice ( Non...
def _do_lumping ( self ) : """Do the PCCA lumping . Notes 1 . Iterate over the eigenvectors , starting with the slowest . 2 . Calculate the spread of that eigenvector within each existing macrostate . 3 . Pick the macrostate with the largest eigenvector spread . 4 . Split the macrostate based on the sig...
# Extract non - perron eigenvectors right_eigenvectors = self . right_eigenvectors_ [ : , 1 : ] assert self . n_states_ > 0 microstate_mapping = np . zeros ( self . n_states_ , dtype = int ) def spread ( x ) : return x . max ( ) - x . min ( ) for i in range ( self . n_macrostates - 1 ) : v = right_eigenvectors ...
def castroData_from_pix_xy ( self , xy , colwise = False ) : """Build a CastroData object for a particular pixel"""
ipix = self . _tsmap . xy_pix_to_ipix ( xy , colwise ) return self . castroData_from_ipix ( ipix )
def read ( self , n ) : '''read some bytes'''
if len ( self . buf ) == 0 : self . _recv ( ) if len ( self . buf ) > 0 : if n > len ( self . buf ) : n = len ( self . buf ) ret = self . buf [ : n ] self . buf = self . buf [ n : ] if self . _debug >= 2 : for b in ret : self . debug ( "read 0x%x" % ord ( b ) , 2 ) re...
def set_pause_param ( self , autoneg , rx_pause , tx_pause ) : """Ethernet has flow control ! The inter - frame pause can be adjusted , by auto - negotiation through an ethernet frame type with a simple two - field payload , and by setting it explicitly . http : / / en . wikipedia . org / wiki / Ethernet _ fl...
# create a struct ethtool _ pauseparm # create a struct ifreq with its . ifr _ data pointing at the above ecmd = array . array ( 'B' , struct . pack ( 'IIII' , ETHTOOL_SPAUSEPARAM , bool ( autoneg ) , bool ( rx_pause ) , bool ( tx_pause ) ) ) buf_addr , _buf_len = ecmd . buffer_info ( ) ifreq = struct . pack ( '16sP' ,...
def delete_tabs ( self , tab , no_tabs = 1 ) : """Deletes no _ tabs tabs and marks grid as changed"""
# Mark content as changed post_command_event ( self . main_window , self . ContentChangedMsg ) try : self . code_array . delete ( tab , no_tabs , axis = 2 ) # Update TableChoiceIntCtrl shape = self . grid . code_array . shape post_command_event ( self . main_window , self . ResizeGridMsg , shape = shape...
def rt_update ( self , statement , linenum , mode , xparser ) : """Uses the specified line parser to parse the given line . : arg statement : a string of lines that are part of a single statement . : arg linenum : the line number of the first line in the list relative to the entire module contents . arg mod...
section = self . find_section ( self . module . charindex ( linenum , 1 ) ) if section == "body" : xparser . parse_line ( statement , self , mode ) elif section == "signature" : if mode == "insert" : xparser . parse_signature ( statement , self )
def receive ( self , timeout ) : """Receive ping responses from the socket . Attempts to read responses for all stored IDs ( as generated by send ( ) ) . Returns a tuple with a dict and a list : - Dict contains IP addresses for which we received a response and the time - List contains IP addresses for whi...
if not self . _id_to_addr : raise MultiPingError ( "No requests have been sent, yet." ) self . _receive_has_been_called = True # Continue with any remaining IDs for which we hadn ' t received an # answer , yet . . . if self . _remaining_ids is None : # . . . but if we don ' t have any stored yet , then we are just ...
def _construct_adb_cmd ( self , raw_name , args , shell ) : """Constructs an adb command with arguments for a subprocess call . Args : raw _ name : string , the raw unsanitized name of the adb command to format . args : string or list of strings , arguments to the adb command . See subprocess . Proc ( ) d...
args = args or '' name = raw_name . replace ( '_' , '-' ) if shell : args = utils . cli_cmd_to_string ( args ) # Add quotes around " adb " in case the ADB path contains spaces . This # is pretty common on Windows ( e . g . Program Files ) . if self . serial : adb_cmd = '"%s" -s "%s" %s %s' % ( A...
def _calc_damping_min ( self ) : """minimum damping [ decimal ]"""
return ( ( 0.8005 + 0.0129 * self . _plas_index * self . _ocr ** - 0.1069 ) * ( self . _stress_mean * KPA_TO_ATM ) ** - 0.2889 * ( 1 + 0.2919 * np . log ( self . _freq ) ) ) / 100
def predict ( self , X ) : """Predictions with the model . Returns posterior means and standard deviations at X ."""
X = np . atleast_2d ( X ) m = np . empty ( shape = ( 0 , 1 ) ) s = np . empty ( shape = ( 0 , 1 ) ) for k in range ( X . shape [ 0 ] ) : preds = [ ] for pred in self . model . estimators_ : preds . append ( pred . predict ( X [ k , : ] ) [ 0 ] ) m = np . vstack ( ( m , np . array ( preds ) . mean ( ...
def migrate_user ( instance ) : """Move User . organisations [ ' global ' ] [ ' role ' ] to top - level property and remove verified flag"""
instance . _resource . pop ( 'verified' , None ) if 'role' in instance . _resource : return instance global_org = instance . organisations . pop ( 'global' , { } ) instance . role = global_org . get ( 'role' , perch . User . roles . default . value ) return instance
def listBlockParents ( self , ** kwargs ) : """API to list block parents . : param block _ name : name of block who ' s parents needs to be found ( Required ) : type block _ name : str : returns : List of dictionaries containing following keys ( block _ name ) : rtype : list of dicts"""
validParameters = [ 'block_name' ] requiredParameters = { 'forced' : validParameters } checkInputParameter ( method = "listBlockParents" , parameters = kwargs . keys ( ) , validParameters = validParameters , requiredParameters = requiredParameters ) if isinstance ( kwargs [ "block_name" ] , list ) : return self . _...
def add_theme ( self , other , inplace = False ) : """Add themes together . Subclasses should not override this method . This will be called when adding two instances of class ' theme ' together . A complete theme will annihilate any previous themes . Partial themes can be added together and can be added ...
if other . complete : return other theme_copy = self if inplace else deepcopy ( self ) theme_copy . themeables . update ( deepcopy ( other . themeables ) ) return theme_copy
def _z2deriv ( self , R , z , phi = 0. , t = 0. ) : """NAME : _ z2deriv PURPOSE : evaluate the second vertical derivative for this potential INPUT : R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT : the second vertical derivative HISTORY : 2016-06-15 -...
if not self . isNonAxi : phi = 0. x , y , z = bovy_coords . cyl_to_rect ( R , phi , z ) if not self . _aligned : raise NotImplementedError ( "2nd potential derivatives of TwoPowerTriaxialPotential not implemented for rotated coordinated frames (non-trivial zvec and pa)" ) return self . _2ndderiv_xyz ( x , y , z...
def next ( self ) : """Next CapitainsCtsPassage ( Interactive CapitainsCtsPassage )"""
if self . nextId is not None : return super ( CapitainsCtsPassage , self ) . getTextualNode ( subreference = self . nextId )
def empty ( shape , ctx = None , dtype = None , stype = None ) : """Returns a new array of given shape and type , without initializing entries . Parameters shape : int or tuple of int The shape of the empty array . ctx : Context , optional An optional device context ( default is the current default contex...
if stype is None or stype == 'default' : return _empty_ndarray ( shape , ctx , dtype ) else : return _empty_sparse_ndarray ( stype , shape , ctx , dtype )
def execute_command ( self , cmd , timeout , wait_for_string , password ) : """Execute command ."""
try : self . last_command_result = None self . ctrl . send_command ( cmd , password = password ) if wait_for_string is None : wait_for_string = self . prompt_re # hide cmd in case it ' s password for further error messages or exceptions . if password : cmd = "*** Password ***" if...
def _set_random_seeds ( ) : """Set new random seeds for the process ."""
try : import numpy as np np . random . seed ( ) except : pass try : import scipy as sp sp . random . seed ( ) except : pass import random random . seed ( )
def get_configured_value ( system_property_name , specific_value , default_value ) : """Get configured value from system properties , method parameters or default value : param system _ property _ name : system property name : param specific _ value : test case specific value : param default _ value : default...
try : return os . environ [ system_property_name ] except KeyError : return specific_value if specific_value else default_value
def update_hash ( self ) : """update hash id of each layer , in topological order / recursively hash id will be used in weight sharing"""
_logger . debug ( 'update hash' ) layer_in_cnt = [ len ( layer . input ) for layer in self . layers ] topo_queue = deque ( [ i for i , layer in enumerate ( self . layers ) if not layer . is_delete and layer . graph_type == LayerType . input . value ] ) while topo_queue : layer_i = topo_queue . pop ( ) self . la...
def _keep_assembled_chrom ( bam_file , genome , config ) : """Remove contigs from the BAM file"""
fai = "%s.fai" % genome chrom = [ ] with open ( fai ) as inh : for line in inh : c = line . split ( "\t" ) [ 0 ] if c . find ( "_" ) < 0 : chrom . append ( c ) chroms = " " . join ( chrom ) out_file = utils . append_stem ( bam_file , '_chrom' ) samtools = config_utils . get_program ( "sa...
def ReqUserLogin ( self , user : str , pwd : str , broker : str ) : """登录 : param user : : param pwd : : param broker :"""
self . q . ReqUserLogin ( BrokerID = broker , UserID = user , Password = pwd )