idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
4,100
def minmax ( arrays , masks = None , dtype = None , out = None , zeros = None , scales = None , weights = None , nmin = 1 , nmax = 1 ) : return generic_combine ( intl_combine . minmax_method ( nmin , nmax ) , arrays , masks = masks , dtype = dtype , out = out , zeros = zeros , scales = scales , weights = weights )
Combine arrays using mix max rejection with masks .
4,101
def flatcombine ( arrays , masks = None , dtype = None , scales = None , low = 3.0 , high = 3.0 , blank = 1.0 ) : result = sigmaclip ( arrays , masks = masks , dtype = dtype , scales = scales , low = low , high = high ) mm = result [ 0 ] <= 0 result [ 0 , mm ] = blank result [ 1 : 2 , mm ] = 0 return result
Combine flat arrays .
4,102
def zerocombine ( arrays , masks , dtype = None , scales = None ) : result = median ( arrays , masks = masks , dtype = dtype , scales = scales ) return result
Combine zero arrays .
4,103
def sum ( arrays , masks = None , dtype = None , out = None , zeros = None , scales = None ) : return generic_combine ( intl_combine . sum_method ( ) , arrays , masks = masks , dtype = dtype , out = out , zeros = zeros , scales = scales )
Combine arrays by addition with masks and offsets .
4,104
def generic_combine ( method , arrays , masks = None , dtype = None , out = None , zeros = None , scales = None , weights = None ) : arrays = [ numpy . asarray ( arr , dtype = dtype ) for arr in arrays ] if masks is not None : masks = [ numpy . asarray ( msk ) for msk in masks ] if out is None : try : outshape = ( 3 , ...
Stack arrays using different methods .
4,105
def compute_fwhm_1d_simple ( Y , xc , X = None ) : return compute_fw_at_frac_max_1d_simple ( Y , xc , X = X , f = 0.5 )
Compute the FWHM .
4,106
def compute_fw_at_frac_max_1d_simple ( Y , xc , X = None , f = 0.5 ) : yy = np . asarray ( Y ) if yy . ndim != 1 : raise ValueError ( 'array must be 1-d' ) if yy . size == 0 : raise ValueError ( 'array is empty' ) if X is None : xx = np . arange ( yy . shape [ 0 ] ) else : xx = X xpix = coor_to_pix_1d ( xc - xx [ 0 ] )...
Compute the full width at fraction f of the maximum
4,107
def _fwhm_side_lineal ( uu , vv ) : res1 , = np . nonzero ( vv < 0 ) if len ( res1 ) == 0 : return 0 , 1 else : i2 = res1 [ 0 ] i1 = i2 - 1 dx = uu [ i2 ] - uu [ i1 ] dy = vv [ i2 ] - vv [ i1 ] r12 = uu [ i1 ] - vv [ i1 ] * dx / dy return r12 , 0
Compute r12 using linear interpolation .
4,108
def get_ZPE ( viblist ) : if type ( viblist ) is str : l = ast . literal_eval ( viblist ) else : l = viblist l = [ float ( w ) for w in l ] ZPE = 0.5 * sum ( l ) * cm2ev return ( ZPE )
Returns the zero point energy from a list of frequencies .
4,109
def auto_labels ( df ) : systems = list ( df . system ) facets = list ( df . facet ) systems_labels = [ w . replace ( '_' , '\ ' ) for w in systems ] systems_labels = [ sub ( w ) for w in systems_labels ] systems_labels = [ w . replace ( '}$$_{' , '' ) for w in systems_labels ] systems_labels = [ w . replace ( '$' , ''...
Transforms atomic system information into well - formatted labels .
4,110
def proton_hydroxide_free_energy ( temperature , pressure , pH ) : H2 = GasMolecule ( 'H2' ) H2O = GasMolecule ( 'H2O' ) G_H2 = H2 . get_free_energy ( temperature = temperature , pressure = pressure ) G_H2O = H2O . get_free_energy ( temperature = temperature ) G_H = ( 0.5 * G_H2 ) - ( ( R * temperature ) / ( z * F ) ) ...
Returns the Gibbs free energy of proton in bulk solution .
4,111
def get_FEC ( molecule_list , temperature , pressure , electronic_energy = 'Default' ) : if not temperature or not pressure : return ( 0 ) else : molecule_list = [ m for m in molecule_list if m != 'star' ] FEC_sum = [ ] for molecule in molecule_list : if 'gas' in molecule : mol = GasMolecule ( molecule . replace ( 'gas...
Returns the Gibbs free energy corrections to be added to raw reaction energies .
4,112
def select_data ( db_file , slab = None , facet = None ) : con = sql . connect ( db_file ) cur = con . cursor ( ) if slab and facet : select_command = 'select chemical_composition, facet, reactants, products, reaction_energy ' 'from reaction where facet=' + str ( facet ) + ' and chemical_composition LIKE "%' + slab + '...
Gathers relevant data from SQL database generated by CATHUB .
4,113
def file_to_df ( file_name ) : filename , file_extension = os . path . splitext ( file_name ) if file_extension == '.csv' : df = pd . read_csv ( file_name , sep = ',' , header = 0 ) . iloc [ : , 1 : ] elif file_extension == '.tsv' : df = pd . read_csv ( file_name , sep = '\t' , header = 0 ) . iloc [ : , 1 : ] else : pr...
Read in file and return pandas data_frame .
4,114
def db_to_df ( db_file , slabs = None , facet = None ) : systems = [ ] data = [ ] if slabs : for slab in slabs : data_tmp = select_data ( db_file , slab = slab , facet = facet ) data . append ( data_tmp ) subsystem = [ tup [ 0 ] for i , tup in enumerate ( data_tmp ) ] systems . append ( list ( set ( subsystem ) ) [ 0 ]...
Transforms database to data frame .
4,115
def unique_reactions ( df ) : reaction_list = [ ] for idx , entry in enumerate ( df [ 'reactants' ] ) : reaction = [ ] for x in entry : reaction . append ( x ) reaction . append ( ' ) for y in df [ 'products' ] [ idx ] : reaction . append ( y ) reaction_list . append ( reaction ) string_list = [ str ( reaction ) for re...
Identifies unique elementary reactions in data frame .
4,116
def get_helmholtz_energy ( self , temperature , electronic_energy = 0 , verbose = False ) : thermo_object = HarmonicThermo ( vib_energies = self . vib_energies , potentialenergy = electronic_energy ) self . helmholtz_energy = thermo_object . get_helmholtz_energy ( temperature = temperature , verbose = verbose ) return ...
Returns the Helmholtz energy of an adsorbed molecule .
4,117
def get_vib_energies ( self ) : vibs = self . molecule_dict [ self . name ] [ 'vibrations' ] vibs = np . array ( vibs ) * cm2ev return ( vibs )
Returns a list of vibration in energy units eV .
4,118
def set_intermediates ( self , intermediates , betas = None , transition_states = None ) : self . intermediates = intermediates self . betas = betas self . transition_states = transition_states if self . corrections is None : self . net_corrections = [ 0.0 for _ in intermediates ] if not self . betas : self . betas = [...
Sets up intermediates and specifies whether it s an electrochemical step . Either provide individual contributions or net contributions . If both are given only the net contributions are used .
4,119
def debugger ( ) : sdb = _current [ 0 ] if sdb is None or not sdb . active : sdb = _current [ 0 ] = Sdb ( ) return sdb
Return the current debugger instance or create if none .
4,120
def global_matches ( self , text ) : matches = [ ] n = len ( text ) for word in self . namespace : if word [ : n ] == text and word != "__builtins__" : matches . append ( word ) return matches
Compute matches when text is a simple name . Return a list of all keywords built - in functions and names currently defined in self . namespace that match .
4,121
def dec2str ( n ) : s = hex ( int ( n ) ) [ 2 : ] . rstrip ( 'L' ) if len ( s ) % 2 != 0 : s = '0' + s return hex2str ( s )
decimal number to string .
4,122
def bin2str ( b ) : ret = [ ] for pos in range ( 0 , len ( b ) , 8 ) : ret . append ( chr ( int ( b [ pos : pos + 8 ] , 2 ) ) ) return '' . join ( ret )
Binary to string .
4,123
def n2s ( n ) : s = hex ( n ) [ 2 : ] . rstrip ( "L" ) if len ( s ) % 2 != 0 : s = "0" + s return s . decode ( "hex" )
Number to string .
4,124
def s2b ( s ) : ret = [ ] for c in s : ret . append ( bin ( ord ( c ) ) [ 2 : ] . zfill ( 8 ) ) return "" . join ( ret )
String to binary .
4,125
def long_to_bytes ( n , blocksize = 0 ) : s = b'' n = int ( n ) pack = struct . pack while n > 0 : s = pack ( '>I' , n & 0xffffffff ) + s n = n >> 32 for i in range ( len ( s ) ) : if s [ i ] != b'\000' [ 0 ] : break else : s = b'\000' i = 0 s = s [ i : ] if blocksize > 0 and len ( s ) % blocksize : s = ( blocksize - l...
Convert an integer to a byte string .
4,126
def make_request ( endpoint , ** kwargs ) : data = kwargs . get ( 'json' , [ ] ) package = kwargs . get ( 'package' , None ) method = kwargs . get ( 'method' , 'GET' ) function = getattr ( requests , method . lower ( ) ) try : if package : response = function ( endpoint , data = data , files = { 'file' : package } ) el...
Send a request to server .
4,127
def get_napps ( self ) : endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'napps' , '' ) res = self . make_request ( endpoint ) if res . status_code != 200 : msg = 'Error getting NApps from server (%s) - %s' LOG . error ( msg , res . status_code , res . reason ) sys . exit ( 1 ) return json . lo...
Get all NApps from the server .
4,128
def get_napp ( self , username , name ) : endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'napps' , username , name , '' ) res = self . make_request ( endpoint ) if res . status_code == 404 : return None if res . status_code != 200 : msg = 'Error getting %s/%s from server: (%d) - %s' raise Kyto...
Return napp metadata or None if not found .
4,129
def reload_napps ( self , napps = None ) : if napps is None : napps = [ ] api = self . _config . get ( 'kytos' , 'api' ) endpoint = os . path . join ( api , 'api' , 'kytos' , 'core' , 'reload' , 'all' ) response = self . make_request ( endpoint ) for napp in napps : api = self . _config . get ( 'kytos' , 'api' ) endpoi...
Reload a specific NApp or all Napps .
4,130
def upload_napp ( self , metadata , package ) : endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'napps' , '' ) metadata [ 'token' ] = self . _config . get ( 'auth' , 'token' ) request = self . make_request ( endpoint , json = metadata , package = package , method = "POST" ) if request . status_...
Upload the napp from the current directory to the napps server .
4,131
def register ( self , user_dict ) : endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'users' , '' ) res = self . make_request ( endpoint , method = 'POST' , json = user_dict ) return res . content . decode ( 'utf-8' )
Send an user_dict to NApps server using POST request .
4,132
def on_message ( self , message ) : if message . address != self . _address : return if isinstance ( message , velbus . ChannelNamePart1Message ) or isinstance ( message , velbus . ChannelNamePart1Message2 ) : self . _process_channel_name_message ( 1 , message ) elif isinstance ( message , velbus . ChannelNamePart2Mess...
Process received message
4,133
def load ( self , callback ) : if callback is None : def callb ( ) : pass callback = callb if len ( self . _loaded_callbacks ) == 0 : self . _request_module_status ( ) self . _request_channel_name ( ) else : print ( "++++++++++++++++++++++++++++++++++" ) self . _loaded_callbacks . append ( callback ) self . _load ( )
Retrieve names of channels
4,134
def _name_messages_complete ( self ) : for channel in range ( 1 , self . number_of_channels ( ) + 1 ) : try : for name_index in range ( 1 , 4 ) : if not isinstance ( self . _name_data [ channel ] [ name_index ] , str ) : return False except Exception : return False return True
Check if all name messages have been received
4,135
def as_json ( self ) : self . _config [ 'applyCss' ] = self . applyCss self . _json [ 'config' ] = self . _config return self . _json
Represent effect as JSON dict .
4,136
def _delete_stale ( self ) : for name , hash_ in self . _stale_files . items ( ) : path = self . download_root . joinpath ( name ) if not path . exists ( ) : continue current_hash = self . _path_hash ( path ) if current_hash == hash_ : progress_logger . info ( 'deleting: %s which is stale...' , name ) path . unlink ( )...
Delete files left in self . _stale_files . Also delete their directories if empty .
4,137
def _file_path ( self , src_path , dest , regex ) : m = re . search ( regex , src_path ) if dest . endswith ( '/' ) or dest == '' : dest += '{filename}' names = m . groupdict ( ) if not names and m . groups ( ) : names = { 'filename' : m . groups ( ) [ - 1 ] } for name , value in names . items ( ) : dest = dest . repla...
check src_path complies with regex and generate new filename
4,138
def _lock ( self , url : str , name : str , hash_ : str ) : self . _new_lock . append ( { 'url' : url , 'name' : name , 'hash' : hash_ , } ) self . _stale_files . pop ( name , None )
Add details of the files downloaded to _new_lock so they can be saved to the lock file . Also remove path from _stale_files whatever remains at the end therefore is stale and can be deleted .
4,139
def setup_smtp ( self , host , port , user , passwd , recipients , ** kwargs ) : self . _smtp = kwargs self . _smtp . update ( { 'host' : host , 'port' : port , 'user' : user , 'passwd' : passwd , 'recipients' : recipients } ) try : self . _smtp [ 'timeout' ] = int ( kwargs . get ( 'timeout' , SMTP_DEFAULT_TIMEOUT ) ) ...
Set up the crash reporter to send reports via email using SMTP
4,140
def enable ( self ) : if not CrashReporter . active : CrashReporter . active = True self . _excepthook = sys . excepthook sys . excepthook = self . exception_handler self . logger . info ( 'CrashReporter: Enabled' ) if self . report_dir : if os . path . exists ( self . report_dir ) : if self . get_offline_reports ( ) :...
Enable the crash reporter . CrashReporter is defaulted to be enabled on creation .
4,141
def disable ( self ) : if CrashReporter . active : CrashReporter . active = False sys . excepthook = self . _excepthook self . stop_watcher ( ) self . logger . info ( 'CrashReporter: Disabled' )
Disable the crash reporter . No reports will be sent or saved .
4,142
def start_watcher ( self ) : if self . _watcher and self . _watcher . is_alive : self . _watcher_running = True else : self . logger . info ( 'CrashReporter: Starting watcher.' ) self . _watcher = Thread ( target = self . _watcher_thread , name = 'offline_reporter' ) self . _watcher . setDaemon ( True ) self . _watcher...
Start the watcher that periodically checks for offline reports and attempts to upload them .
4,143
def stop_watcher ( self ) : if self . _watcher : self . _watcher_running = False self . logger . info ( 'CrashReporter: Stopping watcher.' )
Stop the watcher thread that tries to send offline reports .
4,144
def subject ( self ) : if self . application_name and self . application_version : return 'Crash Report - {name} (v{version})' . format ( name = self . application_name , version = self . application_version ) else : return 'Crash Report'
Return a string to be used as the email subject line .
4,145
def store_report ( self , payload ) : offline_reports = self . get_offline_reports ( ) if offline_reports : for ii , report in enumerate ( reversed ( offline_reports ) ) : rpath , ext = os . path . splitext ( report ) n = int ( re . findall ( '(\d+)' , rpath ) [ - 1 ] ) new_name = os . path . join ( self . report_dir ,...
Save the crash report to a file . Keeping the last offline_report_limit files in a cyclical FIFO buffer . The newest crash report always named is 01
4,146
def _watcher_thread ( self ) : while 1 : time . sleep ( self . check_interval ) if not self . _watcher_running : break self . logger . info ( 'CrashReporter: Attempting to send offline reports.' ) self . submit_offline_reports ( ) remaining_reports = len ( self . get_offline_reports ( ) ) if remaining_reports == 0 : br...
Periodically attempt to upload the crash reports . If any upload method is successful delete the saved reports .
4,147
def colorize ( style , msg , resp ) : code = resp . status . split ( maxsplit = 1 ) [ 0 ] if code [ 0 ] == '2' : msg = style . HTTP_SUCCESS ( msg ) elif code [ 0 ] == '1' : msg = style . HTTP_INFO ( msg ) elif code == '304' : msg = style . HTTP_NOT_MODIFIED ( msg ) elif code [ 0 ] == '3' : msg = style . HTTP_REDIRECT (...
Taken and modified from django . utils . log . ServerFormatter . format to mimic runserver s styling .
4,148
def access ( self , resp , req , environ , request_time ) : if not ( self . cfg . accesslog or self . cfg . logconfig or self . cfg . syslog ) : return msg = self . make_access_message ( resp , req , environ , request_time ) try : self . access_log . info ( msg ) except : self . error ( traceback . format_exc ( ) )
Override to apply styling on access logs .
4,149
def update ( cls , args ) : kytos_api = KytosConfig ( ) . config . get ( 'kytos' , 'api' ) url = f"{kytos_api}api/kytos/core/web/update" version = args [ "<version>" ] if version : url += f"/{version}" try : result = requests . post ( url ) except ( HTTPError , URLError , requests . exceptions . ConnectionError ) : LOG...
Call the method to update the Web UI .
4,150
def disable ( cls , args ) : mgr = NAppsManager ( ) if args [ 'all' ] : napps = mgr . get_enabled ( ) else : napps = args [ '<napp>' ] for napp in napps : mgr . set_napp ( * napp ) LOG . info ( 'NApp %s:' , mgr . napp_id ) cls . disable_napp ( mgr )
Disable subcommand .
4,151
def disable_napp ( mgr ) : if mgr . is_enabled ( ) : LOG . info ( ' Disabling...' ) mgr . disable ( ) LOG . info ( ' Disabled.' ) else : LOG . error ( " NApp isn't enabled." )
Disable a NApp .
4,152
def enable ( cls , args ) : mgr = NAppsManager ( ) if args [ 'all' ] : napps = mgr . get_disabled ( ) else : napps = args [ '<napp>' ] cls . enable_napps ( napps )
Enable subcommand .
4,153
def enable_napp ( cls , mgr ) : try : if not mgr . is_enabled ( ) : LOG . info ( ' Enabling...' ) mgr . enable ( ) LOG . info ( ' Enabled.' ) except ( FileNotFoundError , PermissionError ) as exception : LOG . error ( ' %s' , exception )
Install one NApp using NAppManager object .
4,154
def enable_napps ( cls , napps ) : mgr = NAppsManager ( ) for napp in napps : mgr . set_napp ( * napp ) LOG . info ( 'NApp %s:' , mgr . napp_id ) cls . enable_napp ( mgr )
Enable a list of NApps .
4,155
def uninstall ( cls , args ) : mgr = NAppsManager ( ) for napp in args [ '<napp>' ] : mgr . set_napp ( * napp ) LOG . info ( 'NApp %s:' , mgr . napp_id ) if mgr . is_installed ( ) : if mgr . is_enabled ( ) : cls . disable_napp ( mgr ) LOG . info ( ' Uninstalling...' ) mgr . uninstall ( ) LOG . info ( ' Uninstalled.' ...
Uninstall and delete NApps .
4,156
def install_napps ( cls , napps ) : mgr = NAppsManager ( ) for napp in napps : mgr . set_napp ( * napp ) LOG . info ( ' NApp %s:' , mgr . napp_id ) if not mgr . is_installed ( ) : try : cls . install_napp ( mgr ) if not mgr . is_enabled ( ) : cls . enable_napp ( mgr ) napp_dependencies = mgr . dependencies ( ) if napp...
Install local or remote NApps .
4,157
def install_napp ( cls , mgr ) : try : LOG . info ( ' Searching local NApp...' ) mgr . install_local ( ) LOG . info ( ' Found and installed.' ) except FileNotFoundError : LOG . info ( ' Not found. Downloading from NApps Server...' ) try : mgr . install_remote ( ) LOG . info ( ' Downloaded and installed.' ) ...
Install a NApp .
4,158
def search ( cls , args ) : safe_shell_pat = re . escape ( args [ '<pattern>' ] ) . replace ( r'\*' , '.*' ) pat_str = '.*{}.*' . format ( safe_shell_pat ) pattern = re . compile ( pat_str , re . IGNORECASE ) remote_json = NAppsManager . search ( pattern ) remote = set ( ) for napp in remote_json : username = napp . ge...
Search for NApps in NApps server matching a pattern .
4,159
def _print_napps ( cls , napp_list ) : mgr = NAppsManager ( ) enabled = mgr . get_enabled ( ) installed = mgr . get_installed ( ) napps = [ ] for napp , desc in sorted ( napp_list ) : status = 'i' if napp in installed else '-' status += 'e' if napp in enabled else '-' status = '[{}]' . format ( status ) name = '{}/{}' ...
Format the NApp list to be printed .
4,160
def list ( cls , args ) : mgr = NAppsManager ( ) napps = [ napp + ( '[ie]' , ) for napp in mgr . get_enabled ( ) ] napps += [ napp + ( '[i-]' , ) for napp in mgr . get_disabled ( ) ] napps . sort ( ) napps_ordered = [ ] for user , name , status in napps : description = mgr . get_description ( user , name ) version = mg...
List all installed NApps and inform whether they are enabled .
4,161
def print_napps ( napps ) : if not napps : print ( 'No NApps found.' ) return stat_w = 6 name_w = max ( len ( n [ 1 ] ) for n in napps ) desc_w = max ( len ( n [ 2 ] ) for n in napps ) term_w = os . popen ( 'stty size' , 'r' ) . read ( ) . split ( ) [ 1 ] remaining = max ( 0 , int ( term_w ) - stat_w - name_w - 6 ) des...
Print status name and description .
4,162
def delete ( args ) : mgr = NAppsManager ( ) for napp in args [ '<napp>' ] : mgr . set_napp ( * napp ) LOG . info ( 'Deleting NApp %s from server...' , mgr . napp_id ) try : mgr . delete ( ) LOG . info ( ' Deleted.' ) except requests . HTTPError as exception : if exception . response . status_code == 405 : LOG . error...
Delete NApps from server .
4,163
def reload ( cls , args ) : LOG . info ( 'Reloading NApps...' ) mgr = NAppsManager ( ) try : if args [ 'all' ] : mgr . reload ( None ) else : napps = args [ '<napp>' ] mgr . reload ( napps ) LOG . info ( '\tReloaded.' ) except requests . HTTPError as exception : if exception . response . status_code != 200 : msg = json...
Reload NApps code .
4,164
def choices ( self ) : model_parent_part = self . part . model ( ) property_model = model_parent_part . property ( self . name ) referenced_model = self . _client . model ( pk = property_model . _value [ 'id' ] ) possible_choices = self . _client . parts ( model = referenced_model ) return possible_choices
Retrieve the parts that you can reference for this ReferenceProperty .
4,165
def opensignals_hierarchy ( root = None , update = False , clone = False ) : if root is None : root = os . getcwd ( ) categories = list ( NOTEBOOK_KEYS . keys ( ) ) current_dir = root + "\\opensignalstools_environment" if not os . path . isdir ( current_dir ) : os . makedirs ( current_dir ) for var in [ "images" , "sty...
Function that generates the OpenSignalsTools Notebooks File Hierarchy programatically .
4,166
def _generate_notebook_by_tag_body ( notebook_object , dict_by_tag ) : tag_keys = list ( dict_by_tag . keys ( ) ) tag_keys . sort ( ) for tag in tag_keys : if tag . lower ( ) not in SIGNAL_TYPE_LIST : markdown_cell = group_tag_code . TAG_TABLE_HEADER markdown_cell = markdown_cell . replace ( "Tag i" , tag ) for noteboo...
Internal function that is used for generation of the page where notebooks are organized by tag values .
4,167
def add_markdown_cell ( self , content , tags = None ) : self . notebook [ "cells" ] . append ( nb . v4 . new_markdown_cell ( content , ** { "metadata" : { "tags" : tags } } ) )
Class method responsible for adding a markdown cell with content content to the Notebook object .
4,168
def add_code_cell ( self , content , tags = None ) : self . notebook [ "cells" ] . append ( nb . v4 . new_code_cell ( content , ** { "metadata" : { "tags" : tags } } ) )
Class method responsible for adding a code cell with content content to the Notebook object .
4,169
def is_tracking_shield_displayed ( self ) : with self . selenium . context ( self . selenium . CONTEXT_CHROME ) : if self . window . firefox_version >= 63 : el = self . root . find_element ( * self . _tracking_protection_shield_locator ) return el . get_attribute ( "active" ) is not None el = self . root . find_element...
Tracking Protection shield .
4,170
def validate_registration ( self ) : url = '/api/%s' % self . username response = self . make_request ( 'GET' , url ) if 'error' in response : return False return True
Checks if the device + username have already been registered with the bridge .
4,171
def connect ( self ) : if self . validate_registration ( ) : return True body = { 'devicetype' : self . device_type , 'username' : self . username , } response = self . make_request ( 'POST' , '/api' , body ) if 'error' in response : if response [ 'error' ] [ 'type' ] == 101 : msg = 'Please press the link button and tr...
Registers a new device + username with the bridge
4,172
def get_lights ( self ) : url = '/api/%s/lights' % self . username response = self . make_request ( 'GET' , url ) lights = [ ] if 'error' in response : raise Exception ( response [ 'error' ] [ 'description' ] ) for id_ , data in response . items ( ) : lights . append ( Light ( id_ , data [ 'modelid' ] , data [ 'name' ]...
Lists all available lights on the bridge .
4,173
def set_color ( self , light_id , hex_value , brightness = None ) : light = self . get_light ( light_id ) xy = get_xy_from_hex ( hex_value ) data = { 'xy' : [ xy . x , xy . y ] , } if brightness is not None : data [ 'bri' ] = brightness return self . set_state ( light . light_id , ** data )
This will set the light color based on a hex value
4,174
def plotfft ( s , fmax , doplot = False ) : fs = abs ( np . fft . fft ( s ) ) f = linspace ( 0 , fmax / 2 , len ( s ) / 2 ) if doplot : pass return ( f [ 1 : int ( len ( s ) / 2 ) ] . copy ( ) , fs [ 1 : int ( len ( s ) / 2 ) ] . copy ( ) )
This functions computes the fft of a signal returning the frequency and their magnitude values .
4,175
def discover ( service , timeout = 5 , retries = 5 ) : group = ( '239.255.255.250' , 1900 ) message = '\r\n' . join ( [ 'M-SEARCH * HTTP/1.1' , 'HOST: {0}:{1}' , 'MAN: "ssdp:discover"' , 'ST: {st}' , 'MX: 3' , '' , '' ] ) socket . setdefaulttimeout ( timeout ) responses = { } for _ in range ( retries ) : sock = socket ...
Discovers services on a network using the SSDP Protocol .
4,176
def _isinstance ( self , model , raise_error = True ) : rv = isinstance ( model , self . __model__ ) if not rv and raise_error : raise ValueError ( '%s is not of type %s' % ( model , self . __model__ ) ) return rv
Checks if the specified model instance matches the class model . By default this method will raise a ValueError if the model is not of expected type .
4,177
def _preprocess_params ( cls , kwargs ) : for attr , val in kwargs . items ( ) : if cls . is_the_primary_key ( attr ) and cls . _prevent_primary_key_initialization_ : del kwargs [ attr ] continue if val == "" : kwargs [ attr ] = None continue if attr in class_mapper ( cls ) . relationships and attr not in cls . _no_ove...
Returns a preprocessed dictionary of parameters . Use this to filter the kwargs passed to new create build methods .
4,178
def update ( self , ** kwargs ) : kwargs = self . _preprocess_params ( kwargs ) kwargs = self . preprocess_kwargs_before_update ( kwargs ) for key , value in kwargs . iteritems ( ) : cls = type ( self ) if not hasattr ( cls , key ) or isinstance ( getattr ( cls , key ) , property ) : continue if key not in self . _no_o...
Updates an instance .
4,179
def filter_by ( cls , ** kwargs ) : limit = kwargs . pop ( 'limit' , None ) reverse = kwargs . pop ( 'reverse' , False ) q = cls . query . filter_by ( ** kwargs ) if reverse : q = q . order_by ( cls . id . desc ( ) ) if limit : q = q . limit ( limit ) return q
Same as SQLAlchemy s filter_by . Additionally this accepts two special keyword arguments limit and reverse for limiting the results and reversing the order respectively .
4,180
def count ( cls , * criterion , ** kwargs ) : if criterion or kwargs : return cls . filter ( * criterion , ** kwargs ) . count ( ) else : return cls . query . count ( )
Returns a count of the instances meeting the specified filter criterion and kwargs .
4,181
def new ( cls , ** kwargs ) : kwargs = cls . preprocess_kwargs_before_new ( kwargs ) if cls . __mapper__ . polymorphic_on is not None : discriminator_key = cls . __mapper__ . polymorphic_on . name discriminator_val = kwargs . get ( discriminator_key ) if discriminator_val is not None and discriminator_val in cls . __ma...
Returns a new unsaved instance of the model class .
4,182
def add ( cls , model , commit = True ) : if not isinstance ( model , cls ) : raise ValueError ( '%s is not of type %s' % ( model , cls ) ) cls . session . add ( model ) try : if commit : cls . session . commit ( ) return model except : cls . session . rollback ( ) raise
Adds a model instance to session and commits the transaction .
4,183
def add_all ( cls , models , commit = True , check_type = False ) : if check_type : for model in models : if not isinstance ( model , cls ) : raise ValueError ( '%s is not of type %s' ( model , cls ) ) if None in models : cls . session . add_all ( [ m for m in models if m is not None ] ) else : cls . session . add_all ...
Batch method for adding a list of model instances to the db in one get_or_404 .
4,184
def get ( cls , keyval , key = 'id' , user_id = None ) : if keyval is None : return None if ( key in cls . __table__ . columns and cls . __table__ . columns [ key ] . primary_key ) : return cls . query . get ( keyval ) else : result = cls . query . filter ( getattr ( cls , key ) == keyval ) return result . first ( )
Fetches a single instance which has value keyval for the attribute key .
4,185
def get_all ( cls , keyvals , key = 'id' , user_id = None ) : if len ( keyvals ) == 0 : return [ ] original_keyvals = keyvals keyvals_set = list ( set ( keyvals ) ) resultset = cls . query . filter ( getattr ( cls , key ) . in_ ( keyvals_set ) ) key_result_mapping = { getattr ( result , key ) : result for result in res...
Works like a map function from keyvals to instances .
4,186
def create ( cls , ** kwargs ) : try : return cls . add ( cls . new ( ** kwargs ) ) except : cls . session . rollback ( ) raise
Initializes a new instance adds it to the db and commits the transaction .
4,187
def find_or_create ( cls , ** kwargs ) : keys = kwargs . pop ( 'keys' ) if 'keys' in kwargs else [ ] return cls . first ( ** subdict ( kwargs , keys ) ) or cls . create ( ** kwargs )
Checks if an instance already exists by filtering with the kwargs . If yes returns that instance . If not creates a new instance with kwargs and returns it
4,188
def update_or_create ( cls , ** kwargs ) : keys = kwargs . pop ( 'keys' ) if 'keys' in kwargs else [ ] filter_kwargs = subdict ( kwargs , keys ) if filter_kwargs == { } : obj = None else : obj = cls . first ( ** filter_kwargs ) if obj is not None : for key , value in kwargs . iteritems ( ) : if ( key not in keys and ke...
Checks if an instance already exists by filtering with the kwargs . If yes updates the instance with new kwargs and returns that instance . If not creates a new instance with kwargs and returns it .
4,189
def create_all ( cls , list_of_kwargs ) : try : return cls . add_all ( [ cls . new ( ** kwargs ) if kwargs is not None else None for kwargs in list_of_kwargs ] ) except : cls . session . rollback ( ) raise
Batch method for creating a list of instances
4,190
def find_or_create_all ( cls , list_of_kwargs , keys = [ ] ) : list_of_kwargs_wo_dupes , markers = remove_and_mark_duplicate_dicts ( list_of_kwargs , keys ) added_objs = cls . add_all ( [ cls . first ( ** subdict ( kwargs , keys ) ) or cls . new ( ** kwargs ) for kwargs in list_of_kwargs_wo_dupes ] ) result_objs = [ ] ...
Batch method for querying for a list of instances and creating them if required
4,191
def update_or_create_all ( cls , list_of_kwargs , keys = [ ] ) : objs = [ ] for kwargs in list_of_kwargs : filter_kwargs = subdict ( kwargs , keys ) if filter_kwargs == { } : obj = None else : obj = cls . first ( ** filter_kwargs ) if obj is not None : for key , value in kwargs . iteritems ( ) : if ( key not in keys an...
Batch method for updating a list of instances and creating them if required
4,192
def build ( cls , ** kwargs ) : return cls . add ( cls . new ( ** kwargs ) , commit = False )
Similar to create . But the transaction is not committed
4,193
def find_or_build ( cls , ** kwargs ) : keys = kwargs . pop ( 'keys' ) if 'keys' in kwargs else [ ] return cls . first ( ** subdict ( kwargs , keys ) ) or cls . build ( ** kwargs )
Checks if an instance already exists in db with these kwargs else returns a new saved instance of the service s model class .
4,194
def build_all ( cls , list_of_kwargs ) : return cls . add_all ( [ cls . new ( ** kwargs ) for kwargs in list_of_kwargs ] , commit = False )
Similar to create_all . But transaction is not committed .
4,195
def find_or_build_all ( cls , list_of_kwargs ) : return cls . add_all ( [ cls . first ( ** kwargs ) or cls . new ( ** kwargs ) for kwargs in list_of_kwargs ] , commit = False )
Similar to find_or_create_all . But transaction is not committed .
4,196
def update_all ( cls , * criterion , ** kwargs ) : try : r = cls . query . filter ( * criterion ) . update ( kwargs , 'fetch' ) cls . session . commit ( ) return r except : cls . session . rollback ( ) raise
Batch method for updating all instances obeying the criterion
4,197
def peakdelta ( v , delta , x = None ) : maxtab = [ ] mintab = [ ] if x is None : x = arange ( len ( v ) ) v = asarray ( v ) if len ( v ) != len ( x ) : sys . exit ( 'Input vectors v and x must have same length' ) if not isscalar ( delta ) : sys . exit ( 'Input argument delta must be a scalar' ) if delta <= 0 : sys . e...
Returns two arrays
4,198
def on_status_update ( self , channel , callback ) : if channel not in self . _callbacks : self . _callbacks [ channel ] = [ ] self . _callbacks [ channel ] . append ( callback )
Callback to execute on status of update of channel
4,199
def temp_chdir ( cwd = None ) : if six . PY3 : from tempfile import TemporaryDirectory with TemporaryDirectory ( ) as tempwd : origin = cwd or os . getcwd ( ) os . chdir ( tempwd ) try : yield tempwd if os . path . exists ( tempwd ) else '' finally : os . chdir ( origin ) else : from tempfile import mkdtemp tempwd = mk...
Create and return a temporary directory which you can use as a context manager .