signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def load_params ( self , fname ) : """Loads model parameters from file . Parameters fname : str Path to input param file . Examples > > > # An example of loading module parameters . > > > mod . load _ params ( ' myfile ' )"""
save_dict = ndarray . load ( fname ) arg_params = { } aux_params = { } for k , value in save_dict . items ( ) : arg_type , name = k . split ( ':' , 1 ) if arg_type == 'arg' : arg_params [ name ] = value elif arg_type == 'aux' : aux_params [ name ] = value else : raise ValueError ...
def run_and_exit ( command_class ) : '''A shortcut for reading from sys . argv and exiting the interpreter'''
cmd = command_class ( sys . argv [ 1 : ] ) if cmd . error : print ( 'error: {0}' . format ( cmd . error ) ) sys . exit ( 1 ) else : sys . exit ( cmd . run ( ) )
def delete_contacts ( self , uid , ** kwargs ) : """Unassign contacts from the specified list . If contacts assign only to the specified list , then delete permanently . Returns True if success . : Example : client . lists . delete _ contacts ( uid = 1901010 , contacts = " 1723812,1239912 " ) : param int ...
uri = "%s/%s/contacts" % ( self . uri , uid ) response , instance = self . request ( "DELETE" , uri , data = kwargs ) return response . status == 204
def node ( self , rows , ind , dep , depth = 0 , parent = None , parent_decisions = None ) : """internal method to create a node in the tree"""
depth += 1 if self . max_depth < depth : terminal_node = Node ( choices = parent_decisions , node_id = self . node_count , parent = parent , indices = rows , dep_v = dep ) self . _tree_store . append ( terminal_node ) self . node_count += 1 terminal_node . split . invalid_reason = InvalidSplitReason . M...
def check_license ( package_info , * args ) : """Does the package have a license classifier ? : param package _ info : package _ info dictionary : return : Tuple ( is the condition True or False ? , reason if it is False else None , score to be applied )"""
classifiers = package_info . get ( 'classifiers' ) reason = "No License" result = False if len ( [ c for c in classifiers if c . startswith ( 'License ::' ) ] ) > 0 : result = True return result , reason , HAS_LICENSE
def gen_modules ( self , initial_load = False ) : '''Tell the minion to reload the execution modules CLI Example : . . code - block : : bash salt ' * ' sys . reload _ modules'''
self . utils = salt . loader . utils ( self . opts ) self . functions = salt . loader . minion_mods ( self . opts , utils = self . utils , whitelist = self . whitelist , initial_load = initial_load ) self . serializers = salt . loader . serializers ( self . opts ) if self . mk_returners : self . returners = salt . ...
def config ( ) : '''Shows the current configuration .'''
config = get_config ( ) print ( 'Client version: {0}' . format ( click . style ( __version__ , bold = True ) ) ) print ( 'API endpoint: {0}' . format ( click . style ( str ( config . endpoint ) , bold = True ) ) ) print ( 'API version: {0}' . format ( click . style ( config . version , bold = True ) ) ) print ( 'Access...
def calculate_payload_hash ( payload , algorithm , content_type ) : """Calculates a hash for a given payload ."""
p_hash = hashlib . new ( algorithm ) parts = [ ] parts . append ( 'hawk.' + str ( HAWK_VER ) + '.payload\n' ) parts . append ( parse_content_type ( content_type ) + '\n' ) parts . append ( payload or '' ) parts . append ( '\n' ) for i , p in enumerate ( parts ) : # Make sure we are about to hash binary strings . if...
def assert_greater_equal ( first , second , msg_fmt = "{msg}" ) : """Fail if first is not greater than or equal to second . > > > assert _ greater _ equal ( ' foo ' , ' bar ' ) > > > assert _ greater _ equal ( 5 , 5) > > > assert _ greater _ equal ( 5 , 6) Traceback ( most recent call last ) : AssertionEr...
if not first >= second : msg = "{!r} is not greater than or equal to {!r}" . format ( first , second ) fail ( msg_fmt . format ( msg = msg , first = first , second = second ) )
def wait_for_unit ( service_name , timeout = 480 ) : """Wait ` timeout ` seconds for a given service name to come up ."""
wait_for_machine ( num_machines = 1 ) start_time = time . time ( ) while True : state = unit_info ( service_name , 'agent-state' ) if 'error' in state or state == 'started' : break if time . time ( ) - start_time >= timeout : raise RuntimeError ( 'timeout waiting for service to start' ) ...
def set_widgets ( self ) : """Set widgets on the LayerMode tab ."""
self . clear_further_steps ( ) # Set widgets purpose = self . parent . step_kw_purpose . selected_purpose ( ) subcategory = self . parent . step_kw_subcategory . selected_subcategory ( ) layer_mode_question = ( layer_mode_raster_question if is_raster_layer ( self . parent . layer ) else layer_mode_vector_question ) sel...
def get_first_category ( app_uid ) : '''Get the first , as the uniqe category of post .'''
recs = MPost2Catalog . query_by_entity_uid ( app_uid ) . objects ( ) if recs . count ( ) > 0 : return recs . get ( ) return None
def _build_command ( self , python_executable , lib_dir_fq , proxy_enabled ) : """Build the pip command for installing dependencies . Args : python _ executable ( str ) : The fully qualified path of the Python executable . lib _ dir _ fq ( str ) : The fully qualified path of the lib directory . Returns : ...
exe_command = [ os . path . expanduser ( python_executable ) , '-m' , 'pip' , 'install' , '-r' , self . requirements_file , '--ignore-installed' , '--quiet' , '--target' , lib_dir_fq , ] if self . args . no_cache_dir : exe_command . append ( '--no-cache-dir' ) if proxy_enabled : # trust the pypi hosts to avoid ssl ...
def add_menu ( self , name ) : """Add a menu with name ` name ` to the global menu bar . Returns a menu widget ."""
if self . menubar is None : raise ValueError ( "No menu bar configured" ) return self . menubar . add_name ( name )
def N ( self , ID , asp = 0 ) : """Returns the conjunction or opposition aspect of an object ."""
obj = self . chart . get ( ID ) . copy ( ) obj . relocate ( obj . lon + asp ) ID = 'N_%s_%s' % ( ID , asp ) return self . G ( ID , obj . lat , obj . lon )
def arm_and_takeoff ( aTargetAltitude ) : """Arms vehicle and fly to aTargetAltitude ."""
# Don ' t try to arm until autopilot is ready while not vehicle . is_armable : print ( " Waiting for vehicle to initialise..." ) time . sleep ( 1 ) # Set mode to GUIDED for arming and takeoff : while ( vehicle . mode . name != "GUIDED" ) : vehicle . mode = VehicleMode ( "GUIDED" ) time . sleep ( 0.1 ) #...
def get_vocabularies ( self ) : """Get the vocabularies to pull the qualifiers from ."""
# Timeout in seconds . timeout = 15 socket . setdefaulttimeout ( timeout ) # Create the ordered vocabulary URL . vocab_url = VOCABULARIES_URL . replace ( 'all' , 'all-verbose' ) # Request the vocabularies dictionary . try : vocab_dict = eval ( urllib2 . urlopen ( vocab_url ) . read ( ) ) except : raise UNTLStru...
def create_card ( self , title = None , subtitle = None , content = None , card_type = "Simple" ) : """card _ obj = JSON card object to substitute the ' card ' field in the raw _ response format : " type " : " Simple " , # COMPULSORY " title " : " string " , # OPTIONAL " subtitle " : " string " , # OPTIONAL...
card = { "type" : card_type } if title : card [ "title" ] = title if subtitle : card [ "subtitle" ] = subtitle if content : card [ "content" ] = content return card
def check_imports ( self ) : """Check the projects top level directory for missing imports . This method will check only files ending in * * . py * * and does not handle imports validation for sub - directories ."""
modules = [ ] for filename in sorted ( os . listdir ( self . app_path ) ) : if not filename . endswith ( '.py' ) : continue fq_path = os . path . join ( self . app_path , filename ) with open ( fq_path , 'rb' ) as f : # TODO : fix this code_lines = deque ( [ ( f . read ( ) , 1 ) ] ) ...
def get ( self , key , default = None ) : """Gets config from dynaconf variables if variables does not exists in dynaconf try getting from ` app . config ` to support runtime settings ."""
return self . _settings . get ( key , Config . get ( self , key , default ) )
def ingest ( self , co , classname = None , code_objects = { } , show_asm = None ) : """Pick out tokens from an uncompyle6 code object , and transform them , returning a list of uncompyle6 ' Token ' s . The transformations are made to assist the deparsing grammar . Specificially : - various types of LOAD _ ...
if not show_asm : show_asm = self . show_asm bytecode = self . build_instructions ( co ) # show _ asm = ' after ' if show_asm in ( 'both' , 'before' ) : for instr in bytecode . get_instructions ( co ) : print ( instr . disassemble ( ) ) # Container for tokens tokens = [ ] customize = { } if self . is_py...
def best_motif_in_cluster ( single_pwm , clus_pwm , clusters , fg_fa , background , stats = None , metrics = ( "roc_auc" , "recall_at_fdr" ) ) : """Return the best motif per cluster for a clustering results . The motif can be either the average motif or one of the clustered motifs . Parameters single _ pwm : ...
# combine original and clustered motifs motifs = read_motifs ( single_pwm ) + read_motifs ( clus_pwm ) motifs = dict ( [ ( str ( m ) , m ) for m in motifs ] ) # get the statistics for those motifs that were not yet checked clustered_motifs = [ ] for clus , singles in clusters : for motif in set ( [ clus ] + singles...
def AddRunsFromDirectory ( self , path , name = None ) : """Load runs from a directory ; recursively walks subdirectories . If path doesn ' t exist , no - op . This ensures that it is safe to call ` AddRunsFromDirectory ` multiple times , even before the directory is made . Args : path : A string path to a ...
logger . info ( 'Starting AddRunsFromDirectory: %s (as %s)' , path , name ) for subdir in io_wrapper . GetLogdirSubdirectories ( path ) : logger . info ( 'Processing directory %s' , subdir ) if subdir not in self . _run_loaders : logger . info ( 'Creating DB loader for directory %s' , subdir ) n...
def use_args ( self , argmap , req = None , locations = None , as_kwargs = False , validate = None , error_status_code = None , error_headers = None , ) : """Decorator that injects parsed arguments into a view function or method . Example usage with Flask : : : @ app . route ( ' / echo ' , methods = [ ' get ' ,...
locations = locations or self . locations request_obj = req # Optimization : If argmap is passed as a dictionary , we only need # to generate a Schema once if isinstance ( argmap , Mapping ) : argmap = dict2schema ( argmap , self . schema_class ) ( ) def decorator ( func ) : req_ = request_obj @ functools ....
def get_slack_users ( self , token ) : '''Get all users from Slack'''
ret = salt . utils . slack . query ( function = 'users' , api_key = token , opts = __opts__ ) users = { } if 'message' in ret : for item in ret [ 'message' ] : if 'is_bot' in item : if not item [ 'is_bot' ] : users [ item [ 'name' ] ] = item [ 'id' ] users [ item ...
def setup_tasks ( self , tasks ) : """Find task classes from category . namespace . name strings tasks - list of strings"""
task_classes = [ ] for task in tasks : category , namespace , name = task . split ( "." ) try : cls = find_in_registry ( category = category , namespace = namespace , name = name ) [ 0 ] except TypeError : log . error ( "Could not find the task with category.namespace.name {0}" . format ( ta...
def start ( self , segment ) : """Begin transfer for an indicated wal segment ."""
if self . closed : raise UserCritical ( msg = 'attempt to transfer wal after closing' , hint = 'report a bug' ) g = gevent . Greenlet ( self . transferer , segment ) g . link ( self . _complete_execution ) self . greenlets . add ( g ) # Increment . expect before starting the greenlet , or else a # very unlucky . jo...
def _create_driver ( self , ** kwargs ) : """Create webdriver , assign it to ` ` self . driver ` ` , and run webdriver initiation process , which is usually used for manual login ."""
if self . driver is None : self . driver = self . create_driver ( ** kwargs ) self . init_driver_func ( self . driver )
def evaluate ( self , x , * args ) : """One dimensional constant flux model function . Parameters x : number or ndarray Wavelengths in Angstrom . Returns y : number or ndarray Flux in PHOTLAM ."""
a = ( self . amplitude * np . ones_like ( x ) ) * self . _flux_unit y = units . convert_flux ( x , a , units . PHOTLAM ) return y . value
def execute ( self , input_data ) : '''Execute the Strings worker'''
raw_bytes = input_data [ 'sample' ] [ 'raw_bytes' ] strings = self . find_strings . findall ( raw_bytes ) return { 'string_list' : strings }
def get_bits ( block_representation , coin_symbol = 'btc' , api_key = None ) : '''Takes a block _ representation and returns the number of bits'''
return get_block_overview ( block_representation = block_representation , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'bits' ]
def this_week ( ) : """Return start and end date of the current week ."""
since = TODAY + delta ( weekday = MONDAY ( - 1 ) ) until = since + delta ( weeks = 1 ) return Date ( since ) , Date ( until )
def _map_unity_proxy_to_object ( value ) : """Map returning value , if it is unity SFrame , SArray , map it"""
vtype = type ( value ) if vtype in _proxy_map : return _proxy_map [ vtype ] ( value ) elif vtype == list : return [ _map_unity_proxy_to_object ( v ) for v in value ] elif vtype == dict : return { k : _map_unity_proxy_to_object ( v ) for k , v in value . items ( ) } else : return value
def send_contact ( self , chat_id , phone_number , first_name , last_name = None , vcard = None , disable_notification = None , reply_to_message_id = None , reply_markup = None ) : """Use this method to send phone contacts . On success , the sent Message is returned . https : / / core . telegram . org / bots / ap...
from pytgbot . api_types . sendable . reply_markup import ForceReply from pytgbot . api_types . sendable . reply_markup import InlineKeyboardMarkup from pytgbot . api_types . sendable . reply_markup import ReplyKeyboardMarkup from pytgbot . api_types . sendable . reply_markup import ReplyKeyboardRemove assert_type_or_r...
def _sign_simple_signature_fulfillment ( cls , input_ , message , key_pairs ) : """Signs a Ed25519Fulfillment . Args : input _ ( : class : ` ~ bigchaindb . common . transaction . Input ` ) The input to be signed . message ( str ) : The message to be signed key _ pairs ( dict ) : The keys to sign the Trans...
# NOTE : To eliminate the dangers of accidentally signing a condition by # reference , we remove the reference of input _ here # intentionally . If the user of this class knows how to use it , # this should never happen , but then again , never say never . input_ = deepcopy ( input_ ) public_key = input_ . owners_befor...
def decode_produce_response ( cls , response ) : """Decode ProduceResponse to ProduceResponsePayload Arguments : response : ProduceResponse Return : list of ProduceResponsePayload"""
return [ kafka . structs . ProduceResponsePayload ( topic , partition , error , offset ) for topic , partitions in response . topics for partition , error , offset in partitions ]
def ensure_arg ( args , arg , param = None ) : """Make sure the arg is present in the list of args . If arg is not present , adds the arg and the optional param . If present and param ! = None , sets the parameter following the arg to param . : param list args : strings representing an argument list . : par...
for idx , found_arg in enumerate ( args ) : if found_arg == arg : if param is not None : args [ idx + 1 ] = param return args args . append ( arg ) if param is not None : args . append ( param ) return args
def parse ( self , instr ) : # type : ( bytes ) - > bool '''A method to parse ISO hybridization info out of an existing ISO . Parameters : instr - The data for the ISO hybridization . Returns : Nothing .'''
if self . _initialized : raise pycdlibexception . PyCdlibInternalError ( 'This IsoHybrid object is already initialized' ) if len ( instr ) != 512 : raise pycdlibexception . PyCdlibInvalidISO ( 'Invalid size of the instr' ) if instr [ 0 : 32 ] == self . ORIG_HEADER : self . header = self . ORIG_HEADER elif i...
def populate_schema_objects ( self , schema , obj_type ) : """Returns list of tables or functions for a ( optional ) schema"""
metadata = self . dbmetadata [ obj_type ] schema = schema or self . dbname try : objects = metadata [ schema ] . keys ( ) except KeyError : # schema doesn ' t exist objects = [ ] return objects
def clean_fails ( self ) : """Check if there are any fails that were not subsequently retried . : return : Boolean"""
for item in self . data : if item . failure and not item . retries_left > 0 : return True return False
def _get_set ( self , key , operation , create = False ) : """Get ( and maybe create ) a set by name ."""
return self . _get_by_type ( key , operation , create , b'set' , set ( ) )
def clean_up_tabs ( self ) : """Method remove state - tabs for those no state machine exists anymore ."""
tabs_to_close = [ ] for state_identifier , tab_dict in list ( self . tabs . items ( ) ) : if tab_dict [ 'sm_id' ] not in self . model . state_machine_manager . state_machines : tabs_to_close . append ( state_identifier ) for state_identifier , tab_dict in list ( self . closed_tabs . items ( ) ) : if tab...
def _raise_error_from_response ( data ) : """Processes the response data"""
# Check the meta - data for why this request failed meta = data . get ( 'meta' ) if meta : # Account for foursquare conflicts # see : https : / / developer . foursquare . com / overview / responses if meta . get ( 'code' ) in ( 200 , 409 ) : return data exc = error_types . get ( meta . get ( 'errorType'...
def get_host_cache ( service_instance = None ) : '''Returns the host cache configuration on the proxy host . service _ instance Service instance ( vim . ServiceInstance ) of the vCenter / ESXi host . Default is None . . . code - block : : bash salt ' * ' vsphere . get _ host _ cache'''
# Default to getting all disks if no filtering is done ret_dict = { } host_ref = _get_proxy_target ( service_instance ) hostname = __proxy__ [ 'esxi.get_details' ] ( ) [ 'esxi_host' ] hci = salt . utils . vmware . get_host_cache ( host_ref ) if not hci : log . debug ( 'Host cache not configured on host \'%s\'' , ho...
def RemoveUser ( self , user ) : """Remove a Linux user account . Args : user : string , the Linux user account to remove ."""
self . logger . info ( 'Removing user %s.' , user ) if self . remove : command = self . userdel_cmd . format ( user = user ) try : subprocess . check_call ( command . split ( ' ' ) ) except subprocess . CalledProcessError as e : self . logger . warning ( 'Could not remove user %s. %s.' , use...
def run_task_json ( task_cls , task_data ) : """Instantiate and run the perform method od given task data . : param task _ cls : task class : param task _ data : task data : type task _ data : TaskData : return : task ' s result"""
# TODO what does set _ skipping _ json do ? task = instantiate ( task_cls ) task_callable = get_callable ( task ) td = TaskData ( task_data ) td . set_skipping_json ( True ) return task_callable ( td )
def add_live_points ( self ) : """Add the remaining set of live points to the current set of dead points . Instantiates a generator that will be called by the user . Returns the same outputs as : meth : ` sample ` ."""
# Check if the remaining live points have already been added # to the output set of samples . if self . added_live : raise ValueError ( "The remaining live points have already " "been added to the list of samples!" ) else : self . added_live = True # After N samples have been taken out , the remaining volume is...
def daily ( self , symbol = None ) : '''获取日线数据 : return : pd . dataFrame or None'''
reader = TdxExHqDailyBarReader ( ) symbol = self . find_path ( symbol ) if symbol is not None : return reader . get_df ( symbol ) return None
def file_list_projects ( object_id , input_params = { } , always_retry = True , ** kwargs ) : """Invokes the / file - xxxx / listProjects API method . For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Cloning # API - method % 3A - % 2Fclass - xxxx % 2FlistProjects"""
return DXHTTPRequest ( '/%s/listProjects' % object_id , input_params , always_retry = always_retry , ** kwargs )
def account_block_count ( self , account ) : """Get number of blocks for a specific * * account * * : param account : Account to get number of blocks for : type account : str : raises : : py : exc : ` nano . rpc . RPCException ` > > > rpc . account _ block _ count ( account = " xrb _ 3t6k35gi95xu6tergt6p69c...
account = self . _process_value ( account , 'account' ) payload = { "account" : account } resp = self . call ( 'account_block_count' , payload ) return int ( resp [ 'block_count' ] )
def read_file ( file_path ) : """Read yaml head and raw body content from a file . : param file _ path : file path : return : tuple ( meta , raw _ content )"""
with open ( file_path , 'r' , encoding = 'utf-8' ) as f : whole = f . read ( ) . strip ( ) if whole . startswith ( '---' ) : # may has yaml meta info , so we try to split it out sp = re . split ( r'-{3,}' , whole . lstrip ( '-' ) , maxsplit = 1 ) if len ( sp ) == 2 : # do have yaml meta info , so we read it...
def getConfigPath ( configFileName = None ) : """Auxiliar function to get the configuration path depending on the system ."""
if configFileName != None : # Returning the path of the configuration file if sys . platform == 'win32' : return os . path . expanduser ( os . path . join ( '~\\' , 'Deepify' , configFileName ) ) else : return os . path . expanduser ( os . path . join ( '~/' , '.config' , 'Deepify' , configFileN...
def plot_entropy ( self , tmin , tmax , ntemp , ylim = None , ** kwargs ) : """Plots the vibrational entrpy in a temperature range . Args : tmin : minimum temperature tmax : maximum temperature ntemp : number of steps ylim : tuple specifying the y - axis limits . kwargs : kwargs passed to the matplotlib...
temperatures = np . linspace ( tmin , tmax , ntemp ) if self . structure : ylabel = r"$S$ (J/K/mol)" else : ylabel = r"$S$ (J/K/mol-c)" fig = self . _plot_thermo ( self . dos . entropy , temperatures , ylabel = ylabel , ylim = ylim , ** kwargs ) return fig
def entities ( self , subject_id ) : """Returns all the entities of assertions for a subject , disregarding whether the assertion still is valid or not . : param subject _ id : The identifier of the subject : return : A possibly empty list of entity identifiers"""
try : return [ i [ "entity_id" ] for i in self . _cache . find ( { "subject_id" : subject_id } ) ] except ValueError : return [ ]
def _create_font_size_combo ( self ) : """Creates font size combo box"""
self . std_font_sizes = config [ "font_default_sizes" ] font_size = str ( get_default_font ( ) . GetPointSize ( ) ) self . font_size_combo = wx . ComboBox ( self , - 1 , value = font_size , size = ( 60 , - 1 ) , choices = map ( unicode , self . std_font_sizes ) , style = wx . CB_DROPDOWN | wx . TE_PROCESS_ENTER ) self ...
def PROFILE_VOIGT ( sg0 , GamD , Gam0 , sg ) : """# Voigt profile based on HTP . # Input parameters : # sg0 : Unperturbed line position in cm - 1 ( Input ) . # GamD : Doppler HWHM in cm - 1 ( Input ) # Gam0 : Speed - averaged line - width in cm - 1 ( Input ) . # sg : Current WaveNumber of the Computation ...
return PROFILE_HTP ( sg0 , GamD , Gam0 , cZero , cZero , cZero , cZero , cZero , sg )
def macro_tpm_sbs ( self , state_by_state_micro_tpm ) : """Create a state - by - state coarse - grained macro TPM . Args : micro _ tpm ( nd . array ) : The state - by - state TPM of the micro - system . Returns : np . ndarray : The state - by - state TPM of the macro - system ."""
validate . tpm ( state_by_state_micro_tpm , check_independence = False ) mapping = self . make_mapping ( ) num_macro_states = 2 ** len ( self . macro_indices ) macro_tpm = np . zeros ( ( num_macro_states , num_macro_states ) ) micro_states = range ( 2 ** len ( self . micro_indices ) ) micro_state_transitions = itertool...
def authenticate_with_email_and_pwd ( user_email , user_password ) : '''Authenticate the user by passing the email and password . This function avoids prompting the command line for user credentials and is useful for calling tools programmatically'''
if user_email is None or user_password is None : raise ValueError ( 'Could not authenticate user. Missing username or password' ) upload_token = uploader . get_upload_token ( user_email , user_password ) if not upload_token : print ( "Authentication failed for user name " + user_name + ", please try again." ) ...
def update ( self ) : """Determine all AR coefficients . > > > from hydpy . models . arma import * > > > parameterstep ( ' 1d ' ) > > > responses ( ( ( 1 . , 2 . ) , ( 1 . , ) ) , th _ 3 = ( ( 1 . , ) , ( 1 . , 2 . , 3 . ) ) ) > > > derived . ar _ coefs . update ( ) > > > derived . ar _ coefs ar _ coefs...
pars = self . subpars . pars coefs = pars . control . responses . ar_coefs self . shape = coefs . shape self ( coefs ) pars . model . sequences . logs . logout . shape = self . shape
def get_queryset ( self , request ) : """Limit Pages to those that belong to the request ' s user ."""
qs = super ( VISADeviceAdmin , self ) . get_queryset ( request ) return qs . filter ( protocol_id = PROTOCOL_ID )
def fetch_lists ( keyword , max_results = 20 ) : """Fetch the urls of up to max _ results Twitter lists that match the provided keyword . > > > len ( fetch _ lists ( ' politics ' , max _ results = 4 ) )"""
# CONFIG FILE READ api_key = config . get ( 'GOOGLE_CSE_KEYS' , 'API_KEY' ) cse_id = config . get ( 'GOOGLE_CSE_KEYS' , 'CSE_ID' ) results = [ ] start_c = 1 search_term = "inurl:lists + " + keyword while len ( results ) < max_results : temp_res = google_search ( search_term , api_key , cse_id , num = 10 , start = s...
def _check_heartbeats ( self , ts , * args , ** kwargs ) : """Checks if the heartbeats are on - time . If not , the channel id is escalated to self . _ late _ heartbeats and a warning is issued ; once a hb is received again from this channel , it ' ll be removed from this dict , and an Info message logged . ...
for chan_id in self . _heartbeats : if ts - self . _heartbeats [ chan_id ] >= 10 : if chan_id not in self . _late_heartbeats : try : # This is newly late ; escalate log . warning ( "BitfinexWSS.heartbeats: Channel %s hasn't " "sent a heartbeat in %s seconds!" , self . channel_lab...
def current_version_string ( ) : """Current system python version as string major . minor . micro"""
return "{0}.{1}.{2}" . format ( sys . version_info . major , sys . version_info . minor , sys . version_info . micro )
def find_page_of_state_m ( self , state_m ) : """Return the identifier and page of a given state model : param state _ m : The state model to be searched : return : page containing the state and the state _ identifier"""
for state_identifier , page_info in list ( self . tabs . items ( ) ) : if page_info [ 'state_m' ] is state_m : return page_info [ 'page' ] , state_identifier return None , None
def delFromTimeInv ( self , * params ) : '''Removes any number of parameters from time _ inv for this instance . Parameters params : string Any number of strings naming attributes to be removed from time _ inv Returns None'''
for param in params : if param in self . time_inv : self . time_inv . remove ( param )
def get_consumed_write_units_percent ( table_name , gsi_name , lookback_window_start = 15 , lookback_period = 5 ) : """Returns the number of consumed write units in percent : type table _ name : str : param table _ name : Name of the DynamoDB table : type gsi _ name : str : param gsi _ name : Name of the GS...
try : metrics = __get_aws_metric ( table_name , gsi_name , lookback_window_start , lookback_period , 'ConsumedWriteCapacityUnits' ) except BotoServerError : raise if metrics : lookback_seconds = lookback_period * 60 consumed_write_units = ( float ( metrics [ 0 ] [ 'Sum' ] ) / float ( lookback_seconds ) ...
def sqlvm_group_list ( client , resource_group_name = None ) : '''Lists all SQL virtual machine groups in a resource group or subscription .'''
if resource_group_name : # List all sql vm groups in the resource group return client . list_by_resource_group ( resource_group_name = resource_group_name ) # List all sql vm groups in the subscription return client . list ( )
def _create_adapter_type ( network_adapter , adapter_type , network_adapter_label = '' ) : '''Returns a vim . vm . device . VirtualEthernetCard object specifying a virtual ethernet card information network _ adapter None or VirtualEthernet object adapter _ type String , type of adapter network _ adapter...
log . trace ( 'Configuring virtual machine network ' 'adapter adapter_type=%s' , adapter_type ) if adapter_type in [ 'vmxnet' , 'vmxnet2' , 'vmxnet3' , 'e1000' , 'e1000e' ] : edited_network_adapter = salt . utils . vmware . get_network_adapter_type ( adapter_type ) if isinstance ( network_adapter , type ( edite...
def save_rnn_checkpoint ( cells , prefix , epoch , symbol , arg_params , aux_params ) : """Save checkpoint for model using RNN cells . Unpacks weight before saving . Parameters cells : mxnet . rnn . RNNCell or list of RNNCells The RNN cells used by this symbol . prefix : str Prefix of model name . epo...
if isinstance ( cells , BaseRNNCell ) : cells = [ cells ] for cell in cells : arg_params = cell . unpack_weights ( arg_params ) save_checkpoint ( prefix , epoch , symbol , arg_params , aux_params )
def set_irreps ( self , q , is_little_cogroup = False , nac_q_direction = None , degeneracy_tolerance = 1e-4 ) : """Identify ir - reps of phonon modes . The design of this API is not very satisfactory and is expceted to be redesined in the next major versions once the use case of the API for ir - reps feature...
if self . _dynamical_matrix is None : msg = ( "Dynamical matrix has not yet built." ) raise RuntimeError ( msg ) self . _irreps = IrReps ( self . _dynamical_matrix , q , is_little_cogroup = is_little_cogroup , nac_q_direction = nac_q_direction , factor = self . _factor , symprec = self . _symprec , degeneracy_t...
def grad_desc_update ( x , a , c , step = 0.01 ) : """Given a value of x , return a better x using gradient descent"""
return x - step * gradient ( x , a , c )
def history_backward ( self , count = 1 ) : """Move backwards through history ."""
self . _set_history_search ( ) # Go back in history . found_something = False for i in range ( self . working_index - 1 , - 1 , - 1 ) : if self . _history_matches ( i ) : self . working_index = i count -= 1 found_something = True if count == 0 : break # If we move to another entr...
def lookupjoin ( left , right , key = None , lkey = None , rkey = None , missing = None , presorted = False , buffersize = None , tempdir = None , cache = True , lprefix = None , rprefix = None ) : """Perform a left join , but where the key is not unique in the right - hand table , arbitrarily choose the first ro...
lkey , rkey = keys_from_args ( left , right , key , lkey , rkey ) return LookupJoinView ( left , right , lkey , rkey , presorted = presorted , missing = missing , buffersize = buffersize , tempdir = tempdir , cache = cache , lprefix = lprefix , rprefix = rprefix )
def find_domain ( session , name ) : """Find a domain . Find a domain by its domain name using the given ` session ` . When the domain does not exist the function will return ` None ` . : param session : database session : param name : name of the domain to find : returns : a domain object ; ` None ` wh...
domain = session . query ( Domain ) . filter ( Domain . domain == name ) . first ( ) return domain
def scanJoiner ( self , xEUI = '*' , strPSKd = 'threadjpaketest' ) : """scan Joiner Args : xEUI : Joiner ' s EUI - 64 strPSKd : Joiner ' s PSKd for commissioning Returns : True : successful to add Joiner ' s steering data False : fail to add Joiner ' s steering data"""
print '%s call scanJoiner' % self . port if not isinstance ( xEUI , str ) : eui64 = self . __convertLongToString ( xEUI ) # prepend 0 at the beginning if len ( eui64 ) < 16 : eui64 = eui64 . zfill ( 16 ) print eui64 else : eui64 = xEUI # long timeout value to avoid automatic joiner remov...
def glBufferData ( target , data , usage ) : """Data can be numpy array or the size of data to allocate ."""
if isinstance ( data , int ) : size = data data = ctypes . c_voidp ( 0 ) else : if not data . flags [ 'C_CONTIGUOUS' ] or not data . flags [ 'ALIGNED' ] : data = data . copy ( 'C' ) data_ = data size = data_ . nbytes data = data_ . ctypes . data try : nativefunc = glBufferData . _nat...
def get_visible_profiles ( self , user = None ) : """Returns all the visible profiles available to this user . For now keeps it simple by just applying the cases when a user is not active , a user has it ' s profile closed to everyone or a user only allows registered users to view their profile . : param us...
profiles = self . select_related ( ) . all ( ) filter_kwargs = { 'is_active' : True } profiles = profiles . filter ( ** filter_kwargs ) if user and isinstance ( user , AnonymousUser ) : profiles = [ ] return profiles
def length ( self , t0 = 0 , t1 = 1 , error = LENGTH_ERROR , min_depth = LENGTH_MIN_DEPTH ) : """Calculate the length of the path up to a certain position"""
if t0 == 0 and t1 == 1 : if self . _length_info [ 'bpoints' ] == self . bpoints ( ) and self . _length_info [ 'error' ] >= error and self . _length_info [ 'min_depth' ] >= min_depth : return self . _length_info [ 'length' ] # using scipy . integrate . quad is quick if _quad_available : s = quad ( lambda...
def getProjectAreas ( self , archived = False , returned_properties = None ) : """Get all : class : ` rtcclient . project _ area . ProjectArea ` objects If no : class : ` rtcclient . project _ area . ProjectArea ` objects are retrieved , ` None ` is returned . : param archived : ( default is False ) whether t...
return self . _getProjectAreas ( archived = archived , returned_properties = returned_properties )
def update_or_create ( cls , filter_key = None , with_status = False , ** kwargs ) : """Update or create the element . If the element exists , update it using the kwargs provided if the provided kwargs after resolving differences from existing values . When comparing values , strings and ints are compared dir...
updated = False # Providing this flag will return before updating and require the calling # class to call update if changes were made . defer_update = kwargs . pop ( 'defer_update' , False ) if defer_update : with_status = True element , created = cls . get_or_create ( filter_key = filter_key , with_status = True ,...
def log_message ( self , msg , * args ) : """Hook to log a message ."""
if args : msg = msg % args self . logger . info ( msg )
def autoinit ( fn ) : """Automates initialization so things are more composable . * All specified kwargs in the class and all autoinit classes in inheritance hierarchy will be setattr ' d at the end of initialization , with defaults derived from the inheritance hierarchy as well . * If * * kwargs is explici...
if fn is None : fn = _empty_init if fn_has_args ( fn ) : raise Error ( "*args support is not available in autoinit." ) # its pretty hard to support this , though doable if really needed . . . __defaults = fn_kwargs ( fn ) avail_ac = fn_available_argcount ( fn ) avail_args = list ( fn . __code__ . co_varname...
def __one_equals_true ( value ) : '''Test for ` ` 1 ` ` as a number or a string and return ` ` True ` ` if it is . Args : value : string or number or None . Returns : bool : ` ` True ` ` if 1 otherwise ` ` False ` ` .'''
if isinstance ( value , six . integer_types ) and value == 1 : return True elif ( isinstance ( value , six . string_types ) and re . match ( r'\d+' , value , flags = re . IGNORECASE + re . UNICODE ) is not None and six . text_type ( value ) == '1' ) : return True return False
def batch_move_file ( path , dest , in_name = None , copy = True ) : """将path目录下文件名中包含的in _ name的文件移动到dest目录下 parameters path 需要转移文件的目录 dest 目标目录 in _ name str , 默认是None 。 文件名过滤规则 example # 将path目录下的所有txt文件转移到dest目录 move _ file ( path , dest , in _ name = ' . txt ' ) 默认会覆盖目标目录下的同名文件"""
assert os . path . exists ( path ) , '%s 文件夹不存在' % path assert os . path . exists ( dest ) , '%s 文件夹不存在' % dest if copy : mv = shutil . copy else : mv = shutil . move if in_name is None : file_list = os . listdir ( path ) else : file_list = [ i for i in os . listdir ( path ) if in_name in i ] if len ( f...
def wrap_call ( self , call_cmd ) : """" wraps " the call _ cmd so it can be executed by subprocess . call ( and related flavors ) as " args " argument : param call _ cmd : original args like argument ( string or sequence ) : return : a sequence with the original command " executed " under trickle"""
if isinstance ( call_cmd , basestring ) : # FIXME python 3 unsafe call_cmd = [ call_cmd ] return [ self . _trickle_cmd , "-s" ] + self . _settings . to_argument_list ( ) + list ( call_cmd )
def put_object ( self , parent_object , connection_name , ** data ) : """Writes the given object to the graph , connected to the given parent . For example , graph . put _ object ( " me " , " feed " , message = " Hello , world " ) writes " Hello , world " to the active user ' s wall . Likewise , this will c...
assert self . access_token , "Write operations require an access token" return self . request ( "{0}/{1}/{2}" . format ( self . version , parent_object , connection_name ) , post_args = data , method = "POST" , )
def registerAccount ( self , person , vendorSpecific = None ) : """See Also : registerAccountResponse ( ) Args : person : vendorSpecific : Returns :"""
response = self . registerAccountResponse ( person , vendorSpecific ) return self . _read_boolean_response ( response )
def make_id ( ) : '''Return a new unique ID for a Bokeh object . Normally this function will return simple monotonically increasing integer IDs ( as strings ) for identifying Bokeh objects within a Document . However , if it is desirable to have globally unique for every object , this behavior can be overri...
global _simple_id if settings . simple_ids ( True ) : with _simple_id_lock : _simple_id += 1 return str ( _simple_id ) else : return make_globally_unique_id ( )
def finalize ( self ) : """Finalizes the pull request processing by updating the wiki page with details , posting success / failure to the github pull request ' s commit ."""
# Determine the percentage success on the unit tests . Also see the total time for all # the unit tests . stotal = 0 ttotal = 0 for test in self . repo . testing . tests : stotal += ( 1 if test [ "success" ] == True else 0 ) ttotal += ( test [ "end" ] - test [ "start" ] ) . seconds self . percent = stotal / flo...
def get_list_class ( context , list ) : """Returns the class to use for the passed in list . We just build something up from the object type for the list ."""
return "list_%s_%s" % ( list . model . _meta . app_label , list . model . _meta . model_name )
def __prepare_gprest_call ( self , requestURL , params = None , headers = None , restType = 'GET' , body = None ) : """Returns Authorization type and GP headers"""
if self . __serviceAccount . is_iam_enabled ( ) : auth = None iam_api_key_header = { self . __AUTHORIZATION_HEADER_KEY : str ( 'API-KEY ' + self . __serviceAccount . get_api_key ( ) ) } if not headers is None : headers . update ( iam_api_key_header ) else : headers = iam_api_key_header e...
def present ( name , ip , clean = False ) : # pylint : disable = C0103 '''Ensures that the named host is present with the given ip name The host to assign an ip to ip The ip addr ( s ) to apply to the host . Can be a single IP or a list of IP addresses . clean : False Remove any entries which don ' t ...
ret = { 'name' : name , 'changes' : { } , 'result' : None if __opts__ [ 'test' ] else True , 'comment' : '' } if not isinstance ( ip , list ) : ip = [ ip ] all_hosts = __salt__ [ 'hosts.list_hosts' ] ( ) comments = [ ] to_add = set ( ) to_remove = set ( ) # First check for IPs not currently in the hosts file to_add...
def destroy_ebs_volume ( connection , region , volume_id , log = False ) : """destroys an ebs volume"""
if ebs_volume_exists ( connection , region , volume_id ) : if log : log_yellow ( 'destroying EBS volume ...' ) try : connection . delete_volume ( volume_id ) except : # our EBS volume may be gone , but AWS info tables are stale # wait a bit and ask again sleep ( 5 ) if no...
def _parse_irc ( self ) : """Parse intrinsic reaction coordinate calculation . returns a dictionary containing : geometries : a list of Molecule instances representing each point in the IRC energies : a list of total energies ( Hartree ) distances : distance from the starting point in mass - weighted coords...
irc_geoms = sections ( re . escape ( "***** NEXT POINT ON IRC FOUND *****" ) , re . escape ( "INTERNUCLEAR DISTANCES (ANGS.)" ) , self . text ) # get and store the energy energies = [ entry . splitlines ( ) [ 5 ] for entry in irc_geoms ] # The total energy line energies = [ float ( entry . split ( ) [ 3 ] ) for entry i...
def process ( self , sessionRecord , message ) : """: param sessionRecord : : param message : : type message : PreKeyWhisperMessage"""
messageVersion = message . getMessageVersion ( ) theirIdentityKey = message . getIdentityKey ( ) unsignedPreKeyId = None if not self . identityKeyStore . isTrustedIdentity ( self . recipientId , theirIdentityKey ) : raise UntrustedIdentityException ( self . recipientId , theirIdentityKey ) if messageVersion == 2 : ...
def _handle_parentof ( self , node , scope , ctxt , stream ) : """Handle the parentof unary operator : node : TODO : scope : TODO : ctxt : TODO : stream : TODO : returns : TODO"""
# if someone does something like parentof ( this ) . blah , # we ' ll end up with a StructRef instead of an ID ref # for node . expr , but we ' ll also end up with a structref # if the user does parentof ( a . b . c ) . . . # TODO how to differentiate between the two ? ? # the proper way would be to do ( parentof ( a ....
def replace ( self , text , to_template = '{name} ({url})' , from_template = None , name_matcher = Matcher ( looks_like_name ) , url_matcher = Matcher ( r'.*[^:]+$' ) ) : """Replace all occurrences of rendered from _ template in text with ` template ` rendered from each match . groupdict ( ) TODO : from _ templat...
self . name_matcher = name_matcher or Matcher ( ) self . url_matcher = url_matcher or Matcher ( ) matches = self . finditer ( text ) newdoc = copy ( text ) logger . debug ( 'before translate: {}' . format ( newdoc ) ) for m in matches : # this outer m . captures ( ) loop is overkill : # overlapping pattern matches prob...
def bad_syntax ( cls , syntax , resource_name , ex = None ) : """Exception used when the resource name cannot be parsed ."""
if ex : msg = "The syntax is '%s' (%s)." % ( syntax , ex ) else : msg = "The syntax is '%s'." % syntax msg = "Could not parse '%s'. %s" % ( resource_name , msg ) return cls ( msg )
def CreateServer ( frontend = None ) : """Start frontend http server ."""
max_port = config . CONFIG . Get ( "Frontend.port_max" , config . CONFIG [ "Frontend.bind_port" ] ) for port in range ( config . CONFIG [ "Frontend.bind_port" ] , max_port + 1 ) : server_address = ( config . CONFIG [ "Frontend.bind_address" ] , port ) try : httpd = GRRHTTPServer ( server_address , GRRHT...
def and_filter_from_opts ( opts ) : '''build an AND filter from the provided opts dict as passed to a command from the filter _ options decorator . Assumes all dict values are lists of filter dict constructs .'''
return filters . and_filter ( * list ( chain . from_iterable ( [ o for o in opts . values ( ) if o ] ) ) )