signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _request ( self , url , params = None ) : """Make a signed request to the API , raise any API errors , and returning a tuple of ( data , metadata )"""
response = get ( url , params = params , headers = self . headers , timeout = 30 ) if response . status_code != 200 : raise APIError ( 'Request to {} returned {}' . format ( response . url , response . status_code ) ) response = response . json ( ) error_text = response [ 'service_meta' ] [ 'error_text' ] if error_...
def findMin ( arr ) : """in comparison to argrelmax ( ) more simple and reliable peak finder"""
out = np . zeros ( shape = arr . shape , dtype = bool ) _calcMin ( arr , out ) return out
def _compute_heating_rates ( self ) : """Computes energy flux convergences to get heating rates in : math : ` W / m ^ 2 ` ."""
self . _compute_emission ( ) for varname , value in self . state . items ( ) : self . heating_rate [ varname ] = - self . OLR
def add_stock ( identifier , subs , expression , initial_condition , subscript_dict ) : """Creates new model element dictionaries for the model elements associated with a stock . Parameters identifier : basestring the python - safe name of the stock subs : list a list of subscript elements expression ...
new_structure = [ ] if len ( subs ) == 0 : stateful_py_expr = 'functions.Integ(lambda: %s, lambda: %s)' % ( expression , initial_condition ) else : stateful_py_expr = 'functions.Integ(lambda: _d%s_dt(), lambda: _init_%s())' % ( identifier , identifier ) try : decoded = initial_condition . decode ( '...
def latex ( self ) : """Return LaTeX representation of the abstract ."""
s = ( '{authors}, \\textit{{{title}}}, {journal}, {volissue}, ' '{pages}, ({date}). {doi}, {scopus_url}.' ) if len ( self . authors ) > 1 : authors = ', ' . join ( [ str ( a . given_name ) + ' ' + str ( a . surname ) for a in self . authors [ 0 : - 1 ] ] ) authors += ( ' and ' + str ( self . authors [ - 1 ] . g...
def callback ( self ) : """Generate callback url for provider"""
next = request . args . get ( 'next' ) or None endpoint = 'social.{}.handle' . format ( self . provider ) return url_for ( endpoint , _external = True , next = next )
def post_processor_population_displacement_function ( hazard = None , classification = None , hazard_class = None , population = None ) : """Private function used in the displacement postprocessor . : param hazard : The hazard to use . : type hazard : str : param classification : The hazard classification to ...
_ = population # NOQA return get_displacement_rate ( hazard , classification , hazard_class )
def use_step_method ( self , step_method_class , * args , ** kwds ) : """M . use _ step _ method ( step _ method _ class , * args , * * kwds ) Example of usage : To handle stochastic A with a Metropolis instance , M . use _ step _ method ( Metropolis , A , sig = . 1) To subsequently get a reference to the new...
new_method = step_method_class ( * args , ** kwds ) if self . verbose > 1 : print_ ( 'Using step method %s. Stochastics: ' % step_method_class . __name__ ) for s in new_method . stochastics : self . step_method_dict [ s ] . append ( new_method ) if self . verbose > 1 : print_ ( '\t' + s . __name__ )...
def remaining ( self ) -> str : """Return the remaining part of the input string ."""
res = self . input [ self . offset : ] self . offset = len ( self . input ) return res
def all_same_proj ( self ) : """All contained data array are in the same projection ."""
all_areas = [ x . attrs . get ( 'area' , None ) for x in self . values ( ) ] all_areas = [ x for x in all_areas if x is not None ] return all ( all_areas [ 0 ] . proj_str == x . proj_str for x in all_areas [ 1 : ] )
def check_alert ( self , text ) : """Assert an alert is showing with the given text ."""
try : alert = Alert ( world . browser ) if alert . text != text : raise AssertionError ( "Alert text expected to be {!r}, got {!r}." . format ( text , alert . text ) ) except WebDriverException : # PhantomJS is kinda poor pass
def _fileobj_to_fd ( fileobj ) : """Return a file descriptor from a file object . If given an integer will simply return that integer back ."""
if isinstance ( fileobj , _INTEGER_TYPES ) : fd = fileobj else : for _integer_type in _INTEGER_TYPES : try : fd = _integer_type ( fileobj . fileno ( ) ) break except ( AttributeError , TypeError , ValueError ) : continue else : raise ValueError ( "...
def __execute_queries ( self ) : """Execute all condition and filter result data"""
def func ( item ) : or_check = False for queries in self . _queries : and_check = True for query in queries : and_check &= self . _matcher . _match ( item . get ( query . get ( 'key' ) , None ) , query . get ( 'operator' ) , query . get ( 'value' ) ) or_check |= and_check ...
def add_account_user_to_groups ( self , account_id , user_id , body , ** kwargs ) : # noqa : E501 """Add user to a list of groups . # noqa : E501 An endpoint for adding user to groups . * * Example usage : * * ` curl - X POST https : / / api . us - east - 1 . mbedcloud . com / v3 / accounts / { accountID } / user...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'asynchronous' ) : return self . add_account_user_to_groups_with_http_info ( account_id , user_id , body , ** kwargs ) # noqa : E501 else : ( data ) = self . add_account_user_to_groups_with_http_info ( account_id , user_id , body , ** kwargs ) ...
def etextno ( lines ) : """Retrieves the id for an etext . Args : lines ( iter ) : The lines of the etext to search . Returns : int : The id of the etext . Raises : ValueError : If no etext id was found . Examples : > > > etextno ( [ ' Release Date : March 17 , 2004 [ EBook # 11609 ] ' ] ) 11609 ...
for line in lines : match = ETEXTRE . search ( line ) if match is not None : front_match = match . group ( 'etextid_front' ) back_match = match . group ( 'etextid_back' ) if front_match is not None : return int ( front_match ) elif back_match is not None : ...
def p_global_stmt ( p ) : """global _ stmt : GLOBAL global _ list SEMI | GLOBAL ident EQ expr SEMI"""
p [ 0 ] = node . global_stmt ( p [ 2 ] ) for ident in p [ 0 ] : ident . props = "G"
def purge ( self , doc_ids ) : '''a method to remove docs from the collection : param doc _ ids : string or list of strings with document ids to purge : return : list of strings of doc ids purged'''
# https : / / developer . couchbase . com / documentation / mobile / 1.5 / references / sync - gateway / admin - rest - api / index . html # / document / post _ _ db _ _ _ purge title = '%s.purge' % self . __class__ . __name__ # ingest arguments if isinstance ( doc_ids , str ) : doc_ids = [ doc_ids ] # validate inp...
def open ( self ) : """Open the serial connection ."""
if not self . _is_connected : print ( "Connecting to arduino on {}... " . format ( self . device ) , end = "" ) self . comm = serial . Serial ( ) self . comm . port = self . device self . comm . baudrate = self . baud_rate self . comm . timeout = self . timeout self . dtr = self . enable_dtr ...
def libvlc_audio_set_callbacks ( mp , play , pause , resume , flush , drain , opaque ) : '''Set callbacks and private data for decoded audio . Use L { libvlc _ audio _ set _ format } ( ) or L { libvlc _ audio _ set _ format _ callbacks } ( ) to configure the decoded audio format . @ param mp : the media playe...
f = _Cfunctions . get ( 'libvlc_audio_set_callbacks' , None ) or _Cfunction ( 'libvlc_audio_set_callbacks' , ( ( 1 , ) , ( 1 , ) , ( 1 , ) , ( 1 , ) , ( 1 , ) , ( 1 , ) , ( 1 , ) , ) , None , None , MediaPlayer , AudioPlayCb , AudioPauseCb , AudioResumeCb , AudioFlushCb , AudioDrainCb , ctypes . c_void_p ) return f ( m...
def abort ( self , inplace = True ) : """Abort task : param inplace Apply action on the current object or return a new one . : return : Task object ."""
extra = { 'resource' : self . __class__ . __name__ , 'query' : { 'id' : self . id } } logger . info ( 'Aborting task' , extra = extra ) task_data = self . _api . post ( url = self . _URL [ 'abort' ] . format ( id = self . id ) ) . json ( ) return Task ( api = self . _api , ** task_data )
def decode_keys ( self , keys ) : """Run the decoder on a dict of values"""
return dict ( ( ( k , self . decode ( v ) ) for k , v in six . iteritems ( keys ) ) )
def _query ( self ) : # pylint : disable = E0202 """Query WMI using WMI Query Language ( WQL ) & parse the results . Returns : List of WMI objects or ` TimeoutException ` ."""
formated_property_names = "," . join ( self . property_names ) wql = "Select {property_names} from {class_name}{filters}" . format ( property_names = formated_property_names , class_name = self . class_name , filters = self . formatted_filters ) self . logger . debug ( u"Querying WMI: {0}" . format ( wql ) ) try : # Fr...
def post ( self ) : """Accepts jsorpc post request . Retrieves data from request body ."""
# type ( data ) = dict data = json . loads ( self . request . body . decode ( ) ) # type ( method ) = str method = data [ "method" ] # type ( params ) = dict params = data [ "params" ] if method == "sendmail" : response = dispatch ( [ sendmail ] , { 'jsonrpc' : '2.0' , 'method' : 'sendmail' , 'params' : [ params ] ...
def _inherited_value ( self , attr_name ) : """Return the attribute value , e . g . ' width ' of the base placeholder this placeholder inherits from ."""
base_placeholder = self . _base_placeholder if base_placeholder is None : return None inherited_value = getattr ( base_placeholder , attr_name ) return inherited_value
def process_config ( self ) : super ( ProcessResourcesCollector , self ) . process_config ( ) """prepare self . processes , which is a descriptor dictionary in pg _ name : { exe : [ regex ] , name : [ regex ] , cmdline : [ regex ] , selfmon : [ boolean ] , procs : [ psutil . Process ] , count _ wo...
self . processes = { } self . processes_info = { } for pg_name , cfg in self . config [ 'process' ] . items ( ) : pg_cfg = { } for key in ( 'exe' , 'name' , 'cmdline' ) : pg_cfg [ key ] = cfg . get ( key , [ ] ) if not isinstance ( pg_cfg [ key ] , list ) : pg_cfg [ key ] = [ pg_cfg ...
def wild_card_logs ( ) : """Pull Retrosheet Wild Card Game Logs"""
file_name = 'GLWC.TXT' z = get_zip_file ( wild_card_url ) data = pd . read_csv ( z . open ( file_name ) , header = None , sep = ',' , quotechar = '"' ) data . columns = gamelog_columns return data
def start_output ( self ) : """Write generic start checking info ."""
super ( TextLogger , self ) . start_output ( ) if self . has_part ( 'intro' ) : self . write_intro ( ) self . flush ( )
def _update_database_helper_table ( self ) : """* Update the sherlock catalogues database helper table with the time - stamp of when this catlogue was last updated * * * Usage : * * . . code - block : : python self . _ update _ database _ helper _ table ( )"""
self . log . debug ( 'starting the ``_update_database_helper_table`` method' ) tableName = self . dbTableName sqlQuery = u""" update tcs_helper_catalogue_tables_info set last_updated = now() where table_name = "%(tableName)s"; """ % locals ( ) writequery ( log = self . log , sqlQuery = sqlQuery , db...
def clean_file ( self ) : """Analyse the uploaded file , and return the parsed lines . Returns : tuple of tuples of cells content ( as text ) ."""
data = self . cleaned_data [ 'file' ] available_parsers = self . get_parsers ( ) for parser in available_parsers : try : return parser . parse_file ( data ) except parsers . ParserError : pass raise forms . ValidationError ( "No parser could read the file. Tried with parsers %s." % ( ", " % ( fo...
def handle_defect ( self , obj , defect ) : """Based on policy , either raise defect or call register _ defect . handle _ defect ( obj , defect ) defect should be a Defect subclass , but in any case must be an Exception subclass . obj is the object on which the defect should be registered if it is not raise...
if self . raise_on_defect : raise defect self . register_defect ( obj , defect )
def peakdet ( signal , delta , x = None ) : """Find the local maxima and minima ( peaks ) in a 1 - dimensional signal . Converted from MATLAB script < http : / / billauer . co . il / peakdet . html > : param array signal : A 1 - dimensional array or list ( the signal ) . : type signal : array : param delta ...
maxtab = [ ] mintab = [ ] if x is None : x = np . arange ( len ( signal ) ) v = np . asarray ( signal ) if len ( v ) != len ( x ) : sys . exit ( 'Input vectors v and x must have same length' ) if not np . isscalar ( delta ) : sys . exit ( 'Input argument delta must be a scalar' ) if delta <= 0 : sys . e...
def plot_pie ( self , key = "wall_time" , minfract = 0.05 , ** kwargs ) : """Plot pie charts of the different timers . Args : key : Keyword used to extract data from timers . minfract : Don ' t show sections whose relative weight is less that minfract . Returns : ` matplotlib ` figure"""
timers = self . timers ( ) n = len ( timers ) # Make square figures and axes import matplotlib . pyplot as plt from matplotlib . gridspec import GridSpec fig = plt . gcf ( ) gspec = GridSpec ( n , 1 ) for idx , timer in enumerate ( timers ) : ax = plt . subplot ( gspec [ idx , 0 ] ) ax . set_title ( str ( timer...
def force_unicode ( value ) : """Forces a bytestring to become a Unicode string ."""
if IS_PY3 : # Python 3 . X if isinstance ( value , bytes ) : value = value . decode ( 'utf-8' , errors = 'replace' ) elif not isinstance ( value , str ) : value = str ( value ) else : # Python 2 . X if isinstance ( value , str ) : value = value . decode ( 'utf-8' , 'replace' ) el...
def _get_query_params ( query ) : """> > > _ get _ query _ params ( { ' query ' : { ' a ' : 1 , ' c ' : 3 , ' b ' : 5 } } ) ' a = 1 b = 5 c = 3'"""
query_params = OrderedDict ( sorted ( query [ 'query' ] . items ( ) ) ) return ' ' . join ( [ '{}={}' . format ( k , v ) for k , v in query_params . items ( ) ] )
def wave_range ( bins , cenwave , npix , round = 'round' ) : """Get the wavelength range covered by the given number of pixels centered on the given wavelength . Parameters bins : ndarray Wavelengths of pixel centers . Must be in the same units as ` ` cenwave ` ` . cenwave : float Central wavelength o...
# make sure that the round keyword is valid if round not in ( None , 'round' , 'min' , 'max' ) : raise ValueError ( "round keyword must be one of (None,'round','min','max')" ) # make sure cenwave is within binset if cenwave < bins [ 0 ] : raise exceptions . OverlapError ( "cenwave is not within binset. Min = %f...
def handle_config_change ( self , new_config ) : """Handle the new configuration . Args : new _ config ( dict ) : The new configuration"""
if self . user_handler : self . user_handler ( self . current_config , new_config ) self . _call_spec_handlers ( new_config ) self . current_config = copy . deepcopy ( new_config )
def ParseFileObject ( self , parser_mediator , file_object ) : """Parses a Safari binary cookie file - like object . Args : parser _ mediator ( ParserMediator ) : parser mediator . file _ object ( dfvfs . FileIO ) : file - like object to be parsed . Raises : UnableToParseFile : when the file cannot be par...
file_header_map = self . _GetDataTypeMap ( 'binarycookies_file_header' ) try : file_header , file_header_data_size = self . _ReadStructureFromFileObject ( file_object , 0 , file_header_map ) except ( ValueError , errors . ParseError ) as exception : raise errors . UnableToParseFile ( 'Unable to read file header...
def load_img ( self , img_path ) : """Return an image object that can be immediately plotted with matplotlib"""
with open_file ( self . uuid , img_path ) as f : return mpimg . imread ( f )
def dump ( ) : """Print current environment Environment is outputted in a YAML - friendly format Usage : $ be dump Prefixed : - BE _ TOPICS = hulk bruce animation"""
if not self . isactive ( ) : lib . echo ( "ERROR: Enter a project first" ) sys . exit ( lib . USER_ERROR ) # Print custom environment variables first custom = sorted ( os . environ . get ( "BE_ENVIRONMENT" , "" ) . split ( ) ) if custom : lib . echo ( "Custom:" ) for key in custom : lib . echo (...
async def _report ( self ) : """Call _ update _ cb with the status dict as an argument whenever a status update occurs . This method is a coroutine"""
while True : oldstatus = dict ( self . status ) stat = await self . _updateq . get ( ) if self . _update_cb is not None and oldstatus != stat : # Each client gets its own copy of the dict . self . loop . create_task ( self . _update_cb ( dict ( stat ) ) )
def get_processing_block_event ( ) : """Return the latest Processing Block event"""
event = DB . rpoplpush ( 'processing_block_events' , 'processing_block_event_history' ) if event : event = json . loads ( event . decode ( 'utf-8' ) ) return event
def decorate_event_js ( js_code ) : """setup a method as an event , adding also javascript code to generate Args : js _ code ( str ) : javascript code to generate the event client - side . js _ code is added to the widget html as widget . attributes [ ' onclick ' ] = js _ code % { ' emitter _ identifier ' :...
def add_annotation ( method ) : setattr ( method , "__is_event" , True ) setattr ( method , "_js_code" , js_code ) return method return add_annotation
def disconnect ( self ) : """diconnect from the connected device : return : bool"""
cmd_response = self . __send_command ( const . CMD_EXIT ) if cmd_response . get ( 'status' ) : self . is_connect = False if self . __sock : self . __sock . close ( ) return True else : raise ZKErrorResponse ( "can't disconnect" )
def blockcirculant ( A ) : """Construct a block circulant matrix from a tuple of arrays . This is a block - matrix variant of : func : ` scipy . linalg . circulant ` . Parameters A : tuple of array _ like Tuple of arrays corresponding to the first block column of the output block matrix Returns B : nd...
r , c = A [ 0 ] . shape B = np . zeros ( ( len ( A ) * r , len ( A ) * c ) , dtype = A [ 0 ] . dtype ) for k in range ( len ( A ) ) : for l in range ( len ( A ) ) : kl = np . mod ( k + l , len ( A ) ) B [ r * kl : r * ( kl + 1 ) , c * k : c * ( k + 1 ) ] = A [ l ] return B
def load_csv ( path ) : """Load data from a CSV file . Args : path ( str ) : A path to the CSV format file containing data . dense ( boolean ) : An optional variable indicating if the return matrix should be dense . By default , it is false . Returns : Data matrix X and target vector y"""
with open ( path ) as f : line = f . readline ( ) . strip ( ) X = np . loadtxt ( path , delimiter = ',' , skiprows = 0 if is_number ( line . split ( ',' ) [ 0 ] ) else 1 ) y = np . array ( X [ : , 0 ] ) . flatten ( ) X = X [ : , 1 : ] return X , y
def GetOptionBool ( self , section , option ) : """Get the value of an option in the config file . Args : section : string , the section of the config file to check . option : string , the option to retrieve the value of . Returns : bool , True if the option is enabled or not set ."""
return ( not self . config . has_option ( section , option ) or self . config . getboolean ( section , option ) )
def as_search_action ( self , * , index , action ) : """Return an object as represented in a bulk api operation . Bulk API operations have a very specific format . This function will call the standard ` as _ search _ document ` method on the object and then wrap that up in the correct format for the action sp...
if action not in ( "index" , "update" , "delete" ) : raise ValueError ( "Action must be 'index', 'update' or 'delete'." ) document = { "_index" : index , "_type" : self . search_doc_type , "_op_type" : action , "_id" : self . pk , } if action == "index" : document [ "_source" ] = self . as_search_document ( ind...
def rollback_app ( self , app_id , version , force = False ) : """Roll an app back to a previous version . : param str app _ id : application ID : param str version : application version : param bool force : apply even if a deployment is in progress : returns : a dict containing the deployment id and versio...
params = { 'force' : force } data = json . dumps ( { 'version' : version } ) response = self . _do_request ( 'PUT' , '/v2/apps/{app_id}' . format ( app_id = app_id ) , params = params , data = data ) return response . json ( )
def _bootstrap_deb ( root , arch , flavor , repo_url = None , static_qemu = None , pkgs = None , exclude_pkgs = None , ) : '''Bootstrap an image using the Debian tools root The root of the image to install to . Will be created as a directory if it does not exist . ( e . x . : / root / wheezy ) arch Archit...
if repo_url is None : repo_url = 'http://ftp.debian.org/debian/' if not salt . utils . path . which ( 'debootstrap' ) : log . error ( 'Required tool debootstrap is not installed.' ) return False if static_qemu and not salt . utils . validate . path . is_executable ( static_qemu ) : log . error ( 'Requir...
def data_iterator_simple ( load_func , num_examples , batch_size , shuffle = False , rng = None , with_memory_cache = True , with_file_cache = True , cache_dir = None , epoch_begin_callbacks = [ ] , epoch_end_callbacks = [ ] ) : """A generator that ` ` yield ` ` s minibatch data as a tuple , as defined in ` ` load ...
return data_iterator ( SimpleDataSource ( load_func , num_examples , shuffle = shuffle , rng = rng ) , batch_size = batch_size , with_memory_cache = with_memory_cache , with_file_cache = with_file_cache , cache_dir = cache_dir , epoch_begin_callbacks = epoch_begin_callbacks , epoch_end_callbacks = epoch_end_callbacks )
def export ( self , nidm_version , export_dir ) : """Create prov entities and activities ."""
self . add_attributes ( ( ( PROV [ 'type' ] , self . type ) , ( NIDM_GROUP_NAME , self . group_name ) , ( NIDM_NUMBER_OF_SUBJECTS , self . num_subjects ) , ( PROV [ 'label' ] , self . label ) ) )
def api_rebuild ( ) : """Rebuild the site ( internally ) ."""
if db is None : return '{"error": "single-user mode"}' build_job = q . fetch_job ( 'build' ) orphans_job = q . fetch_job ( 'orphans' ) if not build_job and not orphans_job : build_job = q . enqueue_call ( func = coil . tasks . build , args = ( app . config [ 'REDIS_URL' ] , app . config [ 'NIKOLA_ROOT' ] , '' )...
def setChanged ( self , value = 1 ) : """Set changed flag"""
# set through dictionary to avoid another call to _ _ setattr _ _ if value : self . __dict__ [ 'flags' ] = self . flags | _changedFlag else : self . __dict__ [ 'flags' ] = self . flags & ~ _changedFlag
def load_job ( self , job ) : """Load the job from the given ` ` Job ` ` object . : param job : the job to load : type job : : class : ` ~ aeneas . job . Job ` : raises : : class : ` ~ aeneas . executejob . ExecuteJobInputError ` : if ` ` job ` ` is not an instance of : class : ` ~ aeneas . job . Job `"""
if not isinstance ( job , Job ) : self . log_exc ( u"job is not an instance of Job" , None , True , ExecuteJobInputError ) self . job = job
def eigenvalue_band_properties ( self ) : """Band properties from the eigenvalues as a tuple , ( band gap , cbm , vbm , is _ band _ gap _ direct ) ."""
vbm = - float ( "inf" ) vbm_kpoint = None cbm = float ( "inf" ) cbm_kpoint = None for spin , d in self . eigenvalues . items ( ) : for k , val in enumerate ( d ) : for ( eigenval , occu ) in val : if occu > self . occu_tol and eigenval > vbm : vbm = eigenval vbm_k...
def query ( self , query , additional_locals = None , safe_mode = False ) : """Executes the given SQLAlchemy query string . Args : query : The SQLAlchemy ORM query ( or Python code ) to be executed . additional _ locals : Any additional local variables to inject into the execution context when executing the...
logger . debug ( "Attempting to execute database query: %s" , query ) if safe_mode and not isinstance ( query , dict ) : raise SafetyViolationError ( context = self . error_context ) if isinstance ( query , dict ) : logger . debug ( "Executing query in safe mode (MLAlchemy)" ) return mlalchemy . parse_query...
def es_migration ( self , hosts , project_name , indexes = None , query = None , scroll = "5m" , logstore_index_mappings = None , pool_size = 10 , time_reference = None , source = None , topic = None , wait_time_in_secs = 60 , auto_creation = True ) : """migrate data from elasticsearch to aliyun log service : typ...
from . es_migration import MigrationManager from . es_migration import MigrationResponse migration_manager = MigrationManager ( hosts = hosts , indexes = indexes , query = query , scroll = scroll , endpoint = self . _endpoint , project_name = project_name , access_key_id = self . _accessKeyId , access_key = self . _acc...
def track_from_md5 ( md5 , timeout = DEFAULT_ASYNC_TIMEOUT ) : """Create a track object from an md5 hash . NOTE : Does not create the detailed analysis for the Track . Call Track . get _ analysis ( ) for that . Args : md5 : A string 32 characters long giving the md5 checksum of a track already analyzed . ...
param_dict = dict ( md5 = md5 ) return _profile ( param_dict , timeout )
def insert_system ( cur , system_name , encoded_data = None ) : """Insert a system name into the cache . Args : cur ( : class : ` sqlite3 . Cursor ` ) : An sqlite3 cursor . This function is meant to be run within a : obj : ` with ` statement . system _ name ( str ) : The unique name of a system encoded ...
if encoded_data is None : encoded_data = { } if 'system_name' not in encoded_data : encoded_data [ 'system_name' ] = system_name insert = "INSERT OR IGNORE INTO system(system_name) VALUES (:system_name);" cur . execute ( insert , encoded_data )
def smembers ( self , key , * , encoding = _NOTSET ) : """Get all the members in a set ."""
return self . execute ( b'SMEMBERS' , key , encoding = encoding )
def compile_schema ( self , schema ) : """Compile the current schema into a callable validator : return : Callable validator : rtype : callable : raises SchemaError : Schema compilation error"""
compiler = self . get_schema_compiler ( schema ) if compiler is None : raise SchemaError ( _ ( u'Unsupported schema data type {!r}' ) . format ( type ( schema ) . __name__ ) ) return compiler ( schema )
def _plain_authentication ( self , login , password , authz_id = b"" ) : """SASL PLAIN authentication : param login : username : param password : clear password : return : True on success , False otherwise ."""
if isinstance ( login , six . text_type ) : login = login . encode ( "utf-8" ) if isinstance ( password , six . text_type ) : password = password . encode ( "utf-8" ) params = base64 . b64encode ( b'\0' . join ( [ authz_id , login , password ] ) ) code , data = self . __send_command ( "AUTHENTICATE" , [ b"PLAIN...
def invalidate_cache_after_error ( f ) : """catch any exception and invalidate internal cache with list of nodes"""
@ wraps ( f ) def wrapper ( self , * args , ** kwds ) : try : return f ( self , * args , ** kwds ) except Exception : self . clear_cluster_nodes_cache ( ) raise return wrapper
def _wait_response ( self , message ) : """Private function to get responses from the server . : param message : the received message"""
if message is None or message . code != defines . Codes . CONTINUE . number : self . queue . put ( message )
def calculatePathIntegrationError ( self , time , dt = None , trajectory = None , envelope = False , inputNoise = None ) : """Calculate the error of our path integration , relative to an ideal module . To do this , we track the movement of an individual bump Note that the network must be trained before this is ...
# Set up plotting if self . plotting : self . fig = plt . figure ( ) self . ax1 = self . fig . add_subplot ( 411 ) self . ax2 = self . fig . add_subplot ( 412 ) self . ax3 = self . fig . add_subplot ( 413 ) self . ax4 = self . fig . add_subplot ( 414 ) plt . tight_layout ( ) plt . ion ( ) ...
def action_checkbox ( self , obj ) : """A list _ display column containing a checkbox widget ."""
if self . check_concurrent_action : return helpers . checkbox . render ( helpers . ACTION_CHECKBOX_NAME , force_text ( "%s,%s" % ( obj . pk , get_revision_of_object ( obj ) ) ) ) else : # pragma : no cover return super ( ConcurrencyActionMixin , self ) . action_checkbox ( obj )
def is_tensor_final ( self , tensor_name ) : """Whether a tensor is a final output of the computation . Args : tensor _ name : a string , name of a tensor in the graph . Returns : a boolean indicating whether the tensor was a final output ."""
tensor = self . _name_to_tensor ( tensor_name ) return tensor in self . _final_tensors
def set_edisp_flag ( self , name , flag = True ) : """Enable / Disable the energy dispersion correction for a source ."""
src = self . roi . get_source_by_name ( name ) name = src . name self . like [ name ] . src . set_edisp_flag ( flag )
def parse_scalar_operation ( operation : str ) -> 'QueryOpSpec' : """Parse scalar operations . A scalar operation can one of the following : * single value : start _ date : 12 , metric1 : > 0.9 , metric1 : > = - 0.12 * negation single value : metric1 : ~ 1112 , metric1 : ~ < 1112 equivalent to metric1 : > = 1...
_operation = operation . strip ( ) if not _operation : raise QueryParserException ( 'Operation is not valid: {}' . format ( operation ) ) # Check not allowed ops if '|' in _operation : raise QueryParserException ( '`|` is not allowed for scalar operations. ' 'Operation: {}' . format ( operation ) ) if '..' in _...
def stream_download ( url , target_path , verbose = False ) : """Download a large file without loading it into memory ."""
response = requests . get ( url , stream = True ) handle = open ( target_path , "wb" ) if verbose : print ( "Beginning streaming download of %s" % url ) start = datetime . now ( ) try : content_length = int ( response . headers [ 'Content-Length' ] ) content_MB = content_length / 1048576.0 ...
def assets ( self ) : """Access the assets : returns : twilio . rest . serverless . v1 . service . asset . AssetList : rtype : twilio . rest . serverless . v1 . service . asset . AssetList"""
if self . _assets is None : self . _assets = AssetList ( self . _version , service_sid = self . _solution [ 'sid' ] , ) return self . _assets
def _handle_expander_message ( self , data ) : """Handle expander messages . : param data : expander message to parse : type data : string : returns : : py : class : ` ~ alarmdecoder . messages . ExpanderMessage `"""
msg = ExpanderMessage ( data ) self . _update_internal_states ( msg ) self . on_expander_message ( message = msg ) return msg
def add_to_starred ( self , starred ) : """: calls : ` PUT / user / starred / : owner / : repo < http : / / developer . github . com / v3 / activity / starring > ` _ : param starred : : class : ` github . Repository . Repository ` : rtype : None"""
assert isinstance ( starred , github . Repository . Repository ) , starred headers , data = self . _requester . requestJsonAndCheck ( "PUT" , "/user/starred/" + starred . _identity )
def slugify ( scheme_file ) : """Format $ scheme _ file _ name to be used as a slug variable ."""
scheme_file_name = os . path . basename ( scheme_file ) if scheme_file_name . endswith ( '.yaml' ) : scheme_file_name = scheme_file_name [ : - 5 ] return scheme_file_name . lower ( ) . replace ( ' ' , '-' )
def aggregateStatsDF ( stats_df ) : '''return a dataframe with aggregated counts per UMI'''
grouped = stats_df . groupby ( "UMI" ) agg_dict = { 'counts' : [ np . median , len , np . sum ] } agg_df = grouped . agg ( agg_dict ) agg_df . columns = [ 'median_counts' , 'times_observed' , 'total_counts' ] return agg_df
def parallel_map ( client , task , args , message , batchsize = 1 , background = False , nargs = None ) : """Helper to map a function over a sequence of inputs , in parallel , with progress meter . : param client : IPython . parallel . Client instance : param task : Function : param args : Must be a list of t...
show_progress = bool ( message ) njobs = get_njobs ( nargs , args ) nproc = len ( client ) logger . debug ( 'parallel_map: len(client) = {}' . format ( len ( client ) ) ) view = client . load_balanced_view ( ) if show_progress : message += ' (IP:{}w:{}b)' . format ( nproc , batchsize ) pbar = setup_progressbar ...
def _domain_event_pmsuspend_cb ( conn , domain , reason , opaque ) : '''Domain suspend events handler'''
_salt_send_domain_event ( opaque , conn , domain , opaque [ 'event' ] , { 'reason' : 'unknown' # currently unused } )
def ip_rtm_config_route_static_bfd_bfd_static_route_bfd_interval_attributes_interval ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) ip = ET . SubElement ( config , "ip" , xmlns = "urn:brocade.com:mgmt:brocade-common-def" ) rtm_config = ET . SubElement ( ip , "rtm-config" , xmlns = "urn:brocade.com:mgmt:brocade-rtm" ) route = ET . SubElement ( rtm_config , "route" ) static = ET . SubElement ( route , "static" ) bfd...
def add_eval ( self , agent , e , fr = None ) : """Add or change agent ' s evaluation of the artifact with given framing information . : param agent : Name of the agent which did the evaluation . : param float e : Evaluation for the artifact . : param object fr : Framing information for the evaluation ."""
self . _evals [ agent . name ] = e self . _framings [ agent . name ] = fr
def get_metadata ( self , queue ) : """Returns the metadata for the specified queue ."""
uri = "/%s/%s/metadata" % ( self . uri_base , utils . get_id ( queue ) ) resp , resp_body = self . api . method_get ( uri ) return resp_body
def get_all_images ( self , image_ids = None , owners = None , executable_by = None , filters = None ) : """Retrieve all the EC2 images available on your account . : type image _ ids : list : param image _ ids : A list of strings with the image IDs wanted : type owners : list : param owners : A list of owne...
params = { } if image_ids : self . build_list_params ( params , image_ids , 'ImageId' ) if owners : self . build_list_params ( params , owners , 'Owner' ) if executable_by : self . build_list_params ( params , executable_by , 'ExecutableBy' ) if filters : self . build_filter_params ( params , filters ) ...
def console ( self ) : """The faked Console representing the faked HMC ( an object of : class : ` ~ zhmcclient _ mock . FakedConsole ` ) . The object is cached ."""
if self . _console is None : self . _console = self . list ( ) [ 0 ] return self . _console
def move ( self , x , y ) : """Changes the overlay ' s position relative to the IFramebuffer . in x of type int in y of type int"""
if not isinstance ( x , baseinteger ) : raise TypeError ( "x can only be an instance of type baseinteger" ) if not isinstance ( y , baseinteger ) : raise TypeError ( "y can only be an instance of type baseinteger" ) self . _call ( "move" , in_p = [ x , y ] )
def resolve_redirects ( self , resp , req , stream = False , timeout = None , verify = True , cert = None , proxies = None ) : """Receives a Response . Returns a generator of Responses ."""
i = 0 hist = [ ] # keep track of history while resp . is_redirect : prepared_request = req . copy ( ) if i > 0 : # Update history and keep track of redirects . hist . append ( resp ) new_hist = list ( hist ) resp . history = new_hist try : resp . content # Consume soc...
def clip_end ( self , seq , mm_score ) : """Clip a sequence from the end of this sequence - - we assume the sequence to be clipped will always begin somewhere in this sequence , but may not be fully contained . If found , replaced with Ns . : param seq : sequence to be clipped : param mm _ score : the numbe...
lim = mm_score - 1 other_end = len ( seq ) - 1 other_start = 0 for i in range ( len ( self . sequenceData ) - 1 , lim - 1 , - 1 ) : self_end = i self_start = i - ( len ( seq ) - 1 ) if self_start < 0 : self_start = 0 other_start = other_end - self_end score = self . similarity ( self_sta...
def is_top ( self ) : """If this is a TOP value . : return : True if this is a TOP"""
return ( self . stride == 1 and self . lower_bound == self . _modular_add ( self . upper_bound , 1 , self . bits ) )
def show ( self , only_status = False , show_cluster = True ) : """Print infos on this node configuration ."""
self . __update_status ( ) indent = '' . join ( [ " " for i in xrange ( 0 , len ( self . name ) + 2 ) ] ) print_ ( "{}: {}" . format ( self . name , self . __get_status_string ( ) ) ) if not only_status : if show_cluster : print_ ( "{}{}={}" . format ( indent , 'cluster' , self . cluster . name ) ) prin...
def enumerate ( vendor_id = 0 , product_id = 0 ) : """Enumerate the HID Devices . Returns a generator that yields all of the HID devices attached to the system . : param vendor _ id : Only return devices which match this vendor id : type vendor _ id : int : param product _ id : Only return devices which m...
info = hidapi . hid_enumerate ( vendor_id , product_id ) while info : yield DeviceInfo ( info ) info = info . next hidapi . hid_free_enumeration ( info )
def default_reply ( * args , ** kwargs ) : """Decorator declaring the wrapped function to the default reply hanlder . May be invoked as a simple , argument - less decorator ( i . e . ` ` @ default _ reply ` ` ) or with arguments customizing its behavior ( e . g . ` ` @ default _ reply ( matchstr = ' pattern ' )...
invoked = bool ( not args or kwargs ) matchstr = kwargs . pop ( 'matchstr' , r'^.*$' ) flags = kwargs . pop ( 'flags' , 0 ) if not invoked : func = args [ 0 ] def wrapper ( func ) : PluginsManager . commands [ 'default_reply' ] [ re . compile ( matchstr , flags ) ] = func logger . info ( 'registered default...
def _fit_tfa_inner ( self , data , R , template_centers , template_widths , template_centers_mean_cov , template_widths_mean_var_reci ) : """Fit TFA model , the inner loop part Parameters data : 2D array , in shape [ n _ voxel , n _ tr ] The fMRI data of a subject R : 2D array , in shape [ n _ voxel , n _ d...
nfeature = data . shape [ 0 ] nsample = data . shape [ 1 ] feature_indices = np . random . choice ( nfeature , self . max_num_voxel , replace = False ) sample_features = np . zeros ( nfeature ) . astype ( bool ) sample_features [ feature_indices ] = True samples_indices = np . random . choice ( nsample , self . max_num...
def _get_all_policy_ids ( zap_helper ) : """Get all policy IDs ."""
policies = zap_helper . zap . ascan . policies ( ) return [ p [ 'id' ] for p in policies ]
def remove ( self , package , echo = None , options = None , timeout = shutit_global . shutit_global_object . default_timeout , note = None ) : """Distro - independent remove function . Takes a package name and runs relevant remove function . @ param package : Package to remove , which is run through package _ ...
# If separated by spaces , remove separately shutit = self . shutit if note != None : shutit . handle_note ( 'Removing package: ' + package + '\n' + note ) if options is None : options = { } install_type = self . current_environment . install_type cmd = '' if install_type == 'src' : # If this is a src build , w...
def presigned_get_object ( self , bucket_name , object_name , expires = timedelta ( days = 7 ) , response_headers = None , request_date = None ) : """Presigns a get object request and provides a url Example : from datetime import timedelta presignedURL = presigned _ get _ object ( ' bucket _ name ' , ' obje...
return self . presigned_url ( 'GET' , bucket_name , object_name , expires , response_headers = response_headers , request_date = request_date )
def get_start_date ( module , x ) : """曜日による最初の授業の日を返す"""
weekdays = [ '月' , '火' , '水' , '木' , '金' , '土' , '日' ] a , b = parse_module ( module ) module = a + b [ 0 ] d = datetime . datetime ( * start_dates [ module ] ) days = weekdays . index ( x ) - d . weekday ( ) if days < 0 : days += 7 delta = datetime . timedelta ( days = days ) return d + delta
def index ( self , x , x_link = None ) : """Make an index of record pairs . Use a custom function to make record pairs of one or two dataframes . Each function should return a pandas . MultiIndex with record pairs . Parameters x : pandas . DataFrame A pandas DataFrame . When ` x _ link ` is None , the alg...
if x is None : # error raise ValueError ( "provide at least one dataframe" ) elif x_link is not None : # linking ( two arg ) x = ( x , x_link ) elif isinstance ( x , ( list , tuple ) ) : # dedup or linking ( single arg ) x = tuple ( x ) else : # dedup ( single arg ) x = ( x , ) if self . verify_integrit...
def default ( self , obj ) : """: returns : obj . _ reprJSON ( ) if it is defined , else json . JSONEncoder . default ( obj )"""
if hasattr ( obj , '_reprJSON' ) : return obj . _reprJSON ( ) # Let the base class default method raise the TypeError return json . JSONEncoder . default ( self , obj )
def set_acl ( self , ** kwargs ) : # noqa : E501 """Set ACL for the specified dashboards # noqa : E501 # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . set _ acl ( async _ req = True ) > > > r...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . set_acl_with_http_info ( ** kwargs ) # noqa : E501 else : ( data ) = self . set_acl_with_http_info ( ** kwargs ) # noqa : E501 return data
def commit ( self , index_update = True , label_guesser_update = True ) : """Apply the changes to the index"""
logger . info ( "Index: Commiting changes" ) self . docsearch . index . commit ( index_update = index_update , label_guesser_update = label_guesser_update )
def _add_handler ( logger , handler = None , loglevel = None ) : """Add a handler to an existing logging . Logger object"""
handler . setLevel ( loglevel or DEFAULT_LOGLEVEL ) if handler . level <= logging . DEBUG : _fmt = '%(asctime)s| %(levelname)-4.3s|%(threadName)10.9s/' '%(lineno)04d@%(module)-10.9s| %(message)s' handler . setFormatter ( logging . Formatter ( _fmt ) ) else : handler . setFormatter ( logging . Formatter ( '%...
def _get_cibfile_tmp ( cibname ) : '''Get the full path of a temporary CIB - file with the name of the CIB'''
cibfile_tmp = '{0}.tmp' . format ( _get_cibfile ( cibname ) ) log . trace ( 'cibfile_tmp: %s' , cibfile_tmp ) return cibfile_tmp