signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_by_entityid ( self , entityid ) : """Returns the entity with the given entity ID as a dict"""
data = self . list ( entityid = entityid ) if len ( data ) == 0 : return None eid = int ( next ( iter ( data ) ) ) entity = self . get ( eid ) self . debug ( 0x01 , entity ) return entity
def row_contributions ( self , X ) : """Returns the row contributions towards each principal component ."""
utils . validation . check_is_fitted ( self , 's_' ) # Check input if self . check_input : utils . check_array ( X , dtype = [ str , np . number ] ) # Prepare input X = self . _prepare_input ( X ) return super ( ) . row_contributions ( self . _build_X_global ( X ) )
def batch ( batch_size , items ) : "Batch items into groups of batch _ size"
items = list ( items ) if batch_size is None : return [ items ] MISSING = object ( ) padded_items = items + [ MISSING ] * ( batch_size - 1 ) groups = zip ( * [ padded_items [ i : : batch_size ] for i in range ( batch_size ) ] ) return [ [ item for item in group if item != MISSING ] for group in groups ]
def parse ( self , response ) : """Parse zabbix response ."""
info = response . get ( 'info' ) res = self . _regex . search ( info ) self . _processed += int ( res . group ( 1 ) ) self . _failed += int ( res . group ( 2 ) ) self . _total += int ( res . group ( 3 ) ) self . _time += Decimal ( res . group ( 4 ) ) self . _chunk += 1
def bna_config_cmd_output_session_id ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) bna_config_cmd = ET . Element ( "bna_config_cmd" ) config = bna_config_cmd output = ET . SubElement ( bna_config_cmd , "output" ) session_id = ET . SubElement ( output , "session-id" ) session_id . text = kwargs . pop ( 'session_id' ) callback = kwargs . pop ( 'callback' , self . _cal...
def create_database_migration_numbered_style ( alembic_ini_file : str , alembic_versions_dir : str , message : str , n_sequence_chars : int = 4 ) -> None : """Create a new Alembic migration script . Alembic compares the * * state of the database * * to the * * state of the metadata * * , and generates a migrati...
# noqa _ , _ , existing_version_filenames = next ( os . walk ( alembic_versions_dir ) , ( None , None , [ ] ) ) existing_version_filenames = [ x for x in existing_version_filenames if x != "__init__.py" ] log . debug ( "Existing Alembic version script filenames: {!r}" , existing_version_filenames ) current_seq_strs = [...
def on_art_source ( self , * args ) : """When I get a new ` ` art _ source ` ` , load it as an : class : ` Image ` and store that in ` ` art _ image ` ` ."""
if self . art_source : self . art_image = Image ( source = self . art_source )
def identity ( self ) : """Get the daemon identity This will return an object containing some properties : - alignak : the Alignak instance name - version : the Alignak version - type : the daemon type - name : the daemon name : return : daemon identity : rtype : dict"""
res = self . app . get_id ( ) res . update ( { "start_time" : self . start_time } ) res . update ( { "running_id" : self . running_id } ) return res
def _handle ( self , msg ) : """Pass a received message to the registered handlers . : param msg : received message : type msg : : class : ` fatbotslim . irc . Message `"""
def handler_yielder ( ) : for handler in self . handlers : yield handler def handler_callback ( _ ) : if msg . propagate : try : h = hyielder . next ( ) g = self . _pool . spawn ( handler_runner , h ) g . link ( handler_callback ) except StopIteration ...
def plan ( self ) : """Return a new raw REST interface to account plan : rtype : : py : class : ` ns1 . rest . account . Plan `"""
import ns1 . rest . account return ns1 . rest . account . Plan ( self . config )
def euler_totient ( n ) : """Euler ' s totient function or Phi function . Time Complexity : O ( sqrt ( n ) ) ."""
result = n ; for i in range ( 2 , int ( n ** 0.5 ) + 1 ) : if n % i == 0 : while n % i == 0 : n //= i result -= result // i if n > 1 : result -= result // n ; return result ;
def get_requirements ( ) : """Load list of dependencies ."""
install_requires = [ ] with open ( "requirements/project.txt" ) as f : for line in f : if not line . startswith ( "#" ) : install_requires . append ( line . strip ( ) ) return install_requires
def on_execute__set_surface_alphas ( self , request ) : '''. . versionchanged : : 0.12 Queue redraw after setting surface alphas .'''
data = decode_content_data ( request ) logger . debug ( '[on_execute__set_surface_alphas] %s' , data [ 'surface_alphas' ] ) for name , alpha in data [ 'surface_alphas' ] . iteritems ( ) : self . parent . canvas_slave . set_surface_alpha ( name , alpha ) self . parent . canvas_slave . render ( ) gobject . idle_add (...
def complete_handle ( self ) -> Generator [ Any , None , None ] : """完成回调"""
if self . _request is None : return self . _response = Response ( self . _loop , cast ( asyncio . Transport , self . _transport ) , self . _request . version or DEFAULT_HTTP_VERSION , self . _response_charset , ) keep_alive = self . _request . should_keep_alive if not keep_alive : self . _response . set ( "Conn...
def get_files ( path : PathOrStr , extensions : Collection [ str ] = None , recurse : bool = False , include : Optional [ Collection [ str ] ] = None ) -> FilePathList : "Return list of files in ` path ` that have a suffix in ` extensions ` ; optionally ` recurse ` ."
if recurse : res = [ ] for i , ( p , d , f ) in enumerate ( os . walk ( path ) ) : # skip hidden dirs if include is not None and i == 0 : d [ : ] = [ o for o in d if o in include ] else : d [ : ] = [ o for o in d if not o . startswith ( '.' ) ] res += _get_files (...
def _findSubsetProteins ( proteins , protToPeps , pepToProts ) : """Find proteins which peptides are a sub - set , but not a same - set to other proteins . : param proteins : iterable , proteins that are tested for being a subset : param pepToProts : dict , for each peptide ( = key ) contains a set of parent ...
proteinsEqual = lambda prot1 , prot2 : protToPeps [ prot1 ] == protToPeps [ prot2 ] subGroups = list ( ) for protein in proteins : peptideCounts = Counter ( ) for peptide in protToPeps [ protein ] : proteins = pepToProts [ peptide ] peptideCounts . update ( proteins ) peptideCount = peptideC...
def toc ( message = 'Elapsed time : {} s' ) : """Python implementation of Matlab toc ( ) function"""
t = time . time ( ) print ( message . format ( t - __time_tic_toc ) ) return t - __time_tic_toc
def atleast_1d ( * arrs ) : r"""Convert inputs to arrays with at least one dimension . Scalars are converted to 1 - dimensional arrays , whilst other higher - dimensional inputs are preserved . This is a thin wrapper around ` numpy . atleast _ 1d ` to preserve units . Parameters arrs : arbitrary positiona...
mags = [ a . magnitude if hasattr ( a , 'magnitude' ) else a for a in arrs ] orig_units = [ a . units if hasattr ( a , 'units' ) else None for a in arrs ] ret = np . atleast_1d ( * mags ) if len ( mags ) == 1 : if orig_units [ 0 ] is not None : return units . Quantity ( ret , orig_units [ 0 ] ) else : ...
def _normalize_unit ( cls , unit ) : """Resolve a unit to its real name if it ' s an alias . : param unit str : the unit to normalize : return : the normalized unit , or None one isn ' t found : rtype : Union [ None , str ]"""
if unit in cls . UNITS_IN_SECONDS : return unit return cls . UNIT_ALIASES_REVERSE . get ( unit , None )
def add ( self , opt , val = None ) : """Add a suboption ."""
ov = opt . split ( '=' , 1 ) o = ov [ 0 ] v = len ( ov ) > 1 and ov [ 1 ] or None if ( v ) : if val != None : raise AttributeError ( "ambiguous option value" ) val = v if val == False : return if val in ( None , True ) : self . optlist . add ( o ) else : self . optdict [ o ] = val
def separate_words ( text , acronyms = None ) : """Return text in " seperate words " style . Args : text : input string to convert case detect _ acronyms : should attempt to detect acronyms acronyms : a list of acronyms to detect > > > separate _ words ( " HELLO _ WORLD " ) ' HELLO WORLD ' > > > separ...
words , _case , _sep = case_parse . parse_case ( text , acronyms , preserve_case = True ) return ' ' . join ( words )
def get_size ( self ) : """Retrieves the size of the file - like object . Returns : int : size of the decoded stream . Raises : IOError : if the file - like object has not been opened . OSError : if the file - like object has not been opened ."""
if not self . _is_open : raise IOError ( 'Not opened.' ) if self . _decoded_stream_size is None : self . _decoded_stream_size = self . _GetDecodedStreamSize ( ) return self . _decoded_stream_size
def generate_hcard ( template = None , ** kwargs ) : """Generate a hCard document . Template specific key - value pairs need to be passed as ` ` kwargs ` ` , see classes . : arg template : Ready template to fill with args , for example " diaspora " ( optional ) : returns : HTML document ( str )"""
if template == "diaspora" : hcard = DiasporaHCard ( ** kwargs ) else : raise NotImplementedError ( ) return hcard . render ( )
def _set_repo_urls_from_channels ( self , channels ) : """Convert a channel into a normalized repo name including . Channels are assumed in normalized url form ."""
repos = [ ] sys_platform = self . _conda_api . get_platform ( ) for channel in channels : url = '{0}/{1}/repodata.json.bz2' . format ( channel , sys_platform ) repos . append ( url ) return repos
def as_html ( self , max_rows = 0 ) : """Format table as HTML ."""
if not max_rows or max_rows > self . num_rows : max_rows = self . num_rows omitted = max ( 0 , self . num_rows - max_rows ) labels = self . labels lines = [ ( 0 , '<table border="1" class="dataframe">' ) , ( 1 , '<thead>' ) , ( 2 , '<tr>' ) , ( 3 , ' ' . join ( '<th>' + label + '</th>' for label in labels ) ) , ( 2...
def get_update_api ( self , resource ) : """Generates the meta descriptor for the resource listing api ."""
update_api = { 'path' : '/%s/{id}/' % resource . get_api_name ( ) , 'description' : 'Operations on %s' % resource . model . __name__ , 'operations' : [ { 'httpMethod' : 'PUT' , 'nickname' : 'update%ss' % resource . model . __name__ , 'summary' : 'Update %ss' % resource . model . __name__ , 'parameters' : [ { 'paramType...
def CreateSmartShoppingAd ( client , ad_group_id ) : """Adds a new Smart Shopping ad . Args : client : an AdWordsClient instance . ad _ group _ id : an integer ID for an ad group ."""
ad_group_ad_service = client . GetService ( 'AdGroupAdService' , version = 'v201809' ) # Create an AdGroup Ad . adgroup_ad = { 'adGroupId' : ad_group_id , # Create a Smart Shopping ad ( Goal - optimized Shopping ad ) . 'ad' : { 'xsi_type' : 'GoalOptimizedShoppingAd' } } ad_operation = { 'operator' : 'ADD' , 'operand' :...
def getDatabaseStats ( self ) : """Returns database block read , transaction and tuple stats for each database . @ return : Nested dictionary of stats ."""
headers = ( 'datname' , 'numbackends' , 'xact_commit' , 'xact_rollback' , 'blks_read' , 'blks_hit' , 'tup_returned' , 'tup_fetched' , 'tup_inserted' , 'tup_updated' , 'tup_deleted' , 'disk_size' ) cur = self . _conn . cursor ( ) cur . execute ( "SELECT %s, pg_database_size(datname) FROM pg_stat_database;" % "," . join ...
def prime3 ( a ) : """Simple trial division prime detection : param a : : return :"""
if a < 2 : return False if a == 2 or a == 3 : return True # manually test 2 and 3 if a % 2 == 0 or a % 3 == 0 : return False # exclude multiples of 2 and 3 max_divisor = int ( math . ceil ( a ** 0.5 ) ) d , i = 5 , 2 while d <= max_divisor : if a % d == 0 : return False d += i i = 6 ...
def get_member_types ( obj , member_name , prop_getter = False ) : """Still experimental , incomplete and hardly tested . Works like get _ types , but is also applicable to descriptors ."""
cls = obj . __class__ member = getattr ( cls , member_name ) slf = not ( isinstance ( member , staticmethod ) or isinstance ( member , classmethod ) ) clsm = isinstance ( member , classmethod ) return _get_types ( member , clsm , slf , cls , prop_getter )
def predict_topk ( self , dataset , output_type = 'probability' , k = 3 , output_frequency = 'per_row' ) : """Return top - k predictions for the ` ` dataset ` ` , using the trained model . Predictions are returned as an SFrame with three columns : ` prediction _ id ` , ` class ` , and ` probability ` , or ` ran...
_tkutl . _check_categorical_option_type ( 'output_type' , output_type , [ 'probability' , 'rank' ] ) id_target_map = self . _id_target_map preds = self . predict ( dataset , output_type = 'probability_vector' , output_frequency = output_frequency ) if output_frequency == 'per_row' : probs = preds elif output_freque...
def exception_to_unicode ( exception ) : """Obtains unicode representation of an Exception . This wrapper is used to circumvent Python 2.7 problems with built - in exceptions with unicode messages . Steps used : * Try to obtain Exception . _ _ unicode _ _ * Try to obtain Exception . _ _ str _ _ and decode...
if six . PY2 : try : # First , try to obtain _ _ unicode _ _ as defined by the Exception return six . text_type ( exception ) except UnicodeDecodeError : try : # If that fails , try decoding with utf - 8 which is the strictest # and will complain loudly . return bytes ( excep...
def _parse_ver ( ver ) : '''> > > _ parse _ ver ( " ' 3.4 ' # pyzmq 17.1.0 stopped building wheels for python3.4 " ) '3.4' > > > _ parse _ ver ( ' " 3.4 " ' ) '3.4' > > > _ parse _ ver ( ' " 2.6.17 " ' ) '2.6.17' '''
if '#' in ver : ver , _ = ver . split ( '#' , 1 ) ver = ver . strip ( ) return ver . strip ( '\'' ) . strip ( '"' )
def get_allowed_plugins ( self , placeholder_slot ) : """Return the plugins which are supported in the given placeholder name ."""
# See if there is a limit imposed . slot_config = appsettings . FLUENT_CONTENTS_PLACEHOLDER_CONFIG . get ( placeholder_slot ) or { } plugins = slot_config . get ( 'plugins' ) if not plugins : return self . get_plugins ( ) else : try : return self . get_plugins_by_name ( * plugins ) except PluginNotF...
def _calculate_bounds ( self ) : """Calculate beginning and end of logfile ."""
if self . _bounds_calculated : # Assume no need to recalc bounds for lifetime of a Logfile object return if self . from_stdin : return False # we should be able to find a valid log line within max _ start _ lines max_start_lines = 10 lines_checked = 0 # get start datetime for line in self . filehandle : log...
def host_domains ( self , ip = None , limit = None , ** kwargs ) : """Pass in an IP address ."""
return self . _results ( 'reverse-ip' , '/v1/{0}/host-domains' . format ( ip ) , limit = limit , ** kwargs )
def extract_stack ( start = 0 ) : """SNAGGED FROM traceback . py Altered to return Data Extract the raw traceback from the current stack frame . Each item in the returned list is a quadruple ( filename , line number , function name , text ) , and the entries are in order from newest to oldest"""
try : raise ZeroDivisionError except ZeroDivisionError : trace = sys . exc_info ( ) [ 2 ] f = trace . tb_frame . f_back for i in range ( start ) : f = f . f_back stack = [ ] while f is not None : stack . append ( { "line" : f . f_lineno , "file" : f . f_code . co_filename , "method" : f . f_code . c...
def get_logs ( self , login = None , ** kwargs ) : """Get a user ' s logs . : param str login : User ' s login ( Default : self . _ login ) : return : JSON"""
_login = kwargs . get ( 'login' , login ) log_events_url = GSA_LOGS_URL . format ( login = _login ) return self . _request_api ( url = log_events_url ) . json ( )
def time_to_next_poll ( self ) : """Return seconds ( float ) remaining until : meth : ` . poll ` should be called again"""
if not self . config [ 'enable_auto_commit' ] : return self . time_to_next_heartbeat ( ) if time . time ( ) > self . next_auto_commit_deadline : return 0 return min ( self . next_auto_commit_deadline - time . time ( ) , self . time_to_next_heartbeat ( ) )
def component_on_date ( self , date : datetime . date ) -> Optional [ "Interval" ] : """Returns the part of this interval that falls on the date given , or ` ` None ` ` if the interval doesn ' t have any part during that date ."""
return self . intersection ( Interval . wholeday ( date ) )
def _get_attr_like_prefix ( self , sig ) : """Return prefix text for attribute or data directive ."""
sig_match = chpl_attr_sig_pattern . match ( sig ) if sig_match is None : return ChapelObject . get_signature_prefix ( self , sig ) prefixes , _ , _ , _ = sig_match . groups ( ) if prefixes : return prefixes . strip ( ) + ' ' elif self . objtype == 'type' : return 'type' + ' ' else : return ChapelObject ...
def merge_accounts ( self , request ) : """Attach NetID account to regular django account and then redirect user . In this situation user dont have to fill extra fields because he filled them when first account ( request . user ) was created . Note that self . indentity must be already set in this stage by ...
# create new net ID record in database # and attach it to request . user account . try : netid = NetID . objects . get ( identity = self . identity , provider = self . provider ) except NetID . DoesNotExist : netid = NetID ( user = request . user , identity = self . identity , provider = self . provider ) n...
def check_process_by_name ( self , process ) : """Checks if a named process is found in / proc / [ 0-9 ] * / cmdline . Returns either True or False ."""
status = False cmd_line_glob = "/proc/[0-9]*/cmdline" try : cmd_line_paths = glob . glob ( cmd_line_glob ) for path in cmd_line_paths : f = open ( path , 'r' ) cmd_line = f . read ( ) . strip ( ) if process in cmd_line : status = True except IOError as e : return False re...
def set_mode ( self , controlmode , drivemode ) : """Higher level abstraction for setting the mode register . This will set the mode according the the @ controlmode and @ drivemode you specify . @ controlmode and @ drivemode should come from the ControlMode and DriveMode class respectively ."""
self . set_register ( Addr . Mode , [ 0x01 | controlmode | drivemode ] )
def perms_for_user ( cls , instance , user , db_session = None ) : """returns all permissions that given user has for this resource from groups and directly set ones too : param instance : : param user : : param db _ session : : return :"""
db_session = get_db_session ( db_session , instance ) query = db_session . query ( cls . models_proxy . GroupResourcePermission . group_id . label ( "owner_id" ) , cls . models_proxy . GroupResourcePermission . perm_name , sa . literal ( "group" ) . label ( "type" ) , ) query = query . filter ( cls . models_proxy . Gro...
def exception ( maxTBlevel = None ) : """Retrieve useful information about an exception . Returns a bunch ( attribute - access dict ) with the following information : * name : exception class name * cls : the exception class * exception : the exception instance * trace : the traceback instance * formatt...
try : from marrow . util . bunch import Bunch cls , exc , trbk = sys . exc_info ( ) excName = cls . __name__ excArgs = getattr ( exc , 'args' , None ) excTb = '' . join ( traceback . format_exception ( cls , exc , trbk , maxTBlevel ) ) return Bunch ( name = excName , cls = cls , exception = exc ...
def onelineaddress ( self , address , ** kwargs ) : '''Geocode an an address passed as one string . e . g . " 4600 Silver Hill Rd , Suitland , MD 20746"'''
fields = { 'address' : address , } return self . _fetch ( 'onelineaddress' , fields , ** kwargs )
def getBoneHierarchy ( self , action , unIndexArayCount ) : """Fills the given array with the index of each bone ' s parent in the skeleton associated with the given action"""
fn = self . function_table . getBoneHierarchy pParentIndices = BoneIndex_t ( ) result = fn ( action , byref ( pParentIndices ) , unIndexArayCount ) return result , pParentIndices
def _search_pn ( self , href = None , limit = None , embed_items = None , embed_tracks = None , embed_metadata = None , embed_insights = None ) : """Function called to retrieve pages 2 - n ."""
url_components = urlparse ( href ) path = url_components . path data = parse_qs ( url_components . query ) # Change all lists into discrete values . for key in data . keys ( ) : data [ key ] = data [ key ] [ 0 ] # Deal with limit overriding . if limit is not None : data [ 'limit' ] = limit # Deal with embeds ov...
def delete_refund_transaction_by_id ( cls , refund_transaction_id , ** kwargs ) : """Delete RefundTransaction Delete an instance of RefundTransaction by its ID . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . del...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _delete_refund_transaction_by_id_with_http_info ( refund_transaction_id , ** kwargs ) else : ( data ) = cls . _delete_refund_transaction_by_id_with_http_info ( refund_transaction_id , ** kwargs ) return data
def ls ( self , what ) : """List actuators , programs or sensors ( what is string )"""
for i in getattr ( self . system , what ) : self . logger . info ( '%s: %s: %s' , i . __class__ . __name__ , i , i . status ) return True
def paginator ( context , adjacent_pages = 2 ) : """To be used in conjunction with the object _ list generic view . Adds pagination context variables for use in displaying first , adjacent and last page links in addition to those created by the object _ list generic view ."""
current_page = context . get ( 'page' ) paginator = context . get ( 'paginator' ) if not paginator : return pages = paginator . num_pages current_range = range ( current_page - adjacent_pages , current_page + adjacent_pages + 1 ) page_numbers = [ n for n in current_range if n > 0 and n <= pages ] slugtype = '' if '...
def InternalExchange ( self , cmd , payload_in ) : """Sends and receives a message from the device ."""
# make a copy because we destroy it below self . logger . debug ( 'payload: ' + str ( list ( payload_in ) ) ) payload = bytearray ( ) payload [ : ] = payload_in for _ in range ( 2 ) : self . InternalSend ( cmd , payload ) ret_cmd , ret_payload = self . InternalRecv ( ) if ret_cmd == UsbHidTransport . U2FHID...
def new_db_from_pandas ( self , frame , table = None , data = None , load = True , ** kwargs ) : """Create a new db partition from a pandas data frame . If the table does not exist , it will be created"""
from . . orm import Column # from dbexceptions import ConfigurationError # Create the table from the information in the data frame . with self . bundle . session : sch = self . bundle . schema t = sch . new_table ( table ) if frame . index . name : id_name = frame . index . name else : i...
def _process_results ( self , results ) : """Returns a sanitized copy of raw LDAP results . This scrubs out references , decodes utf8 , normalizes DNs , etc ."""
results = [ r for r in results if r [ 0 ] is not None ] results = _DeepStringCoder ( 'utf-8' ) . decode ( results ) # The normal form of a DN is lower case . results = [ ( r [ 0 ] . lower ( ) , r [ 1 ] ) for r in results ] result_dns = [ result [ 0 ] for result in results ] logger . debug ( u"search_s('%s', %d, '%s') r...
def slits_to_ds9_reg ( ds9reg , slits ) : """Transform fiber traces to ds9 - region format . Parameters ds9reg : BinaryIO Handle to output file name in ds9 - region format ."""
# open output file and insert header ds9reg . write ( '# Region file format: DS9 version 4.1\n' ) ds9reg . write ( 'global color=green dashlist=8 3 width=1 font="helvetica 10 ' 'normal roman" select=1 highlite=1 dash=0 fixed=0 edit=1 ' 'move=1 delete=1 include=1 source=1\n' ) ds9reg . write ( 'physical\n' ) for idx , s...
def getWhatIf ( number ) : """Returns a : class : ` WhatIf ` object corresponding to the What If article of index passed to the function . If the index is less than zero or greater than the maximum number of articles published thus far , None is returned instead . Like all the routines for handling What If ...
archive = getWhatIfArchive ( ) latest = getLatestWhatIfNum ( archive ) if type ( number ) is str and number . isdigit ( ) : number = int ( number ) if number > latest or latest <= 0 : return None return archive [ number ]
def _populate_trie ( self , values : List [ str ] ) -> CharTrie : """Takes a list and inserts its elements into a new trie and returns it"""
if self . _default_tokenizer : return reduce ( self . _populate_trie_reducer , iter ( values ) , CharTrie ( ) ) return reduce ( self . _populate_trie_reducer_regex , iter ( values ) , CharTrie ( ) )
def _master_opts ( self , load ) : '''Return the master options to the minion'''
mopts = { } file_roots = { } envs = self . _file_envs ( ) for saltenv in envs : if saltenv not in file_roots : file_roots [ saltenv ] = [ ] mopts [ 'file_roots' ] = file_roots mopts [ 'top_file_merging_strategy' ] = self . opts [ 'top_file_merging_strategy' ] mopts [ 'env_order' ] = self . opts [ 'env_order...
def get_polnum ( self , obj ) : """AP polnum minus ' polnum ' prefix if polnum else ` ` None ` ` ."""
ap_id = obj . candidate_election . candidate . ap_candidate_id if 'polnum-' in ap_id : return ap_id . replace ( 'polnum-' , '' ) return None
def build_type ( self , build_type ) : """Sets the build _ type of this BuildConfigurationRest . : param build _ type : The build _ type of this BuildConfigurationRest . : type : str"""
allowed_values = [ "MVN" , "NPM" ] if build_type not in allowed_values : raise ValueError ( "Invalid value for `build_type` ({0}), must be one of {1}" . format ( build_type , allowed_values ) ) self . _build_type = build_type
def to_dict ( cls , obj ) : '''Serialises the object , by default serialises anything that isn ' t prefixed with _ _ , isn ' t in the blacklist , and isn ' t callable .'''
return { k : getattr ( obj , k ) for k in dir ( obj ) if cls . serialisable ( k , obj ) }
def QA_user_sign_up ( name , password , client ) : """只做check ! 具体逻辑需要在自己的函数中实现 参见 : QAWEBSERVER中的实现 Arguments : name { [ type ] } - - [ description ] password { [ type ] } - - [ description ] client { [ type ] } - - [ description ] Returns : [ type ] - - [ description ]"""
coll = client . user if ( coll . find ( { 'username' : name } ) . count ( ) > 0 ) : print ( name ) QA_util_log_info ( 'user name is already exist' ) return False else : return True
def create ( self , api_version = values . unset , friendly_name = values . unset , sms_application_sid = values . unset , sms_fallback_method = values . unset , sms_fallback_url = values . unset , sms_method = values . unset , sms_url = values . unset , status_callback = values . unset , status_callback_method = value...
data = values . of ( { 'PhoneNumber' : phone_number , 'AreaCode' : area_code , 'ApiVersion' : api_version , 'FriendlyName' : friendly_name , 'SmsApplicationSid' : sms_application_sid , 'SmsFallbackMethod' : sms_fallback_method , 'SmsFallbackUrl' : sms_fallback_url , 'SmsMethod' : sms_method , 'SmsUrl' : sms_url , 'Stat...
def get ( self , key , recursive = False , sorted = False , quorum = False , timeout = None ) : """Gets a value of key ."""
return self . adapter . get ( key , recursive = recursive , sorted = sorted , quorum = quorum , timeout = timeout )
def readlines ( self ) : """Returns a list of all lines ( optionally parsed ) in the file ."""
if self . grammar : tot = [ ] # Used this way instead of a ' for ' loop against # self . file . readlines ( ) so that there wasn ' t two copies of the file # in memory . while 1 : line = self . file . readline ( ) if not line : break tot . append ( line ) retu...
def default_value ( self , argname ) : """Get the default value for an argument . : param argname : The name of the argument to get the default value for . : type argname : str : raises NoDefault : If there is no default value defined for the given argument ."""
i = _find_arg ( argname , self . args ) [ 0 ] if i is not None : idx = i - ( len ( self . args ) - len ( self . defaults ) ) if idx >= 0 : return self . defaults [ idx ] i = _find_arg ( argname , self . kwonlyargs ) [ 0 ] if i is not None and self . kw_defaults [ i ] is not None : return self . kw_d...
def update ( self ) : """Updates this range format"""
if self . _track_changes : data = self . to_api_data ( restrict_keys = self . _track_changes ) if data : response = self . session . patch ( self . build_url ( '' ) , data = data ) if not response : return False self . _track_changes . clear ( ) if self . _font . _track_chang...
def _file_path ( self , dirname , filename ) : '''Builds an absolute path and creates the directory and file if they don ' t already exist . @ dirname - Directory path . @ filename - File name . Returns a full path of ' dirname / filename ' .'''
if not os . path . exists ( dirname ) : try : os . makedirs ( dirname ) except KeyboardInterrupt as e : raise e except Exception : pass fpath = os . path . join ( dirname , filename ) if not os . path . exists ( fpath ) : try : open ( fpath , "w" ) . close ( ) except ...
def Close ( self ) : """Disconnects from the database . This method will create the necessary indices and commit outstanding transactions before disconnecting ."""
# Build up indices for the fields specified in the args . # It will commit the inserts automatically before creating index . if not self . _append : for field_name in self . _fields : query = 'CREATE INDEX {0:s}_idx ON log2timeline ({0:s})' . format ( field_name ) self . _cursor . execute ( query ) ...
def get_explicit_resnorms ( self , indices = None ) : '''Explicitly computes the Ritz residual norms .'''
res = self . get_explicit_residual ( indices ) # apply preconditioner linear_system = self . _deflated_solver . linear_system Mres = linear_system . M * res # compute norms resnorms = numpy . zeros ( res . shape [ 1 ] ) for i in range ( resnorms . shape [ 0 ] ) : resnorms [ i ] = utils . norm ( res [ : , [ i ] ] , ...
def populate_regions ( self , tectonic_region_dict ) : '''Populates the tectonic region from the list of dictionaries , where each region is a dictionary of with the following format : : region = { ' Shear _ Modulus ' : [ ( val1 , weight1 ) , ( val2 , weight2 ) , . . . ] , ' Displacement _ Length _ Ratio ' : ...
for tect_reg in tectonic_region_dict : if 'Shear_Modulus' in tect_reg . keys ( ) : shear_modulus = tect_reg [ 'Shear_Modulus' ] else : shear_modulus = DEFAULT_SHEAR_MODULUS if 'Displacement_Length_Ratio' in tect_reg . keys ( ) : disp_length_ratio = tect_reg [ 'Displacement_Length_Rat...
def delete_free_shipping_by_id ( cls , free_shipping_id , ** kwargs ) : """Delete FreeShipping Delete an instance of FreeShipping by its ID . This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . delete _ free _ shippin...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _delete_free_shipping_by_id_with_http_info ( free_shipping_id , ** kwargs ) else : ( data ) = cls . _delete_free_shipping_by_id_with_http_info ( free_shipping_id , ** kwargs ) return data
def get_function_spec ( name ) : """Return a dictionary with the specification of a function : parameter names and defaults ( value , bounds , scale , etc . ) . Returns par _ names : list List of parameter names for this function . norm _ par : str Name of normalization parameter . default : dict Pa...
if not hasattr ( get_function_spec , 'fndict' ) : modelfile = os . path . join ( '$FERMIPY_ROOT' , 'data' , 'models.yaml' ) modelfile = os . path . expandvars ( modelfile ) get_function_spec . fndict = yaml . load ( open ( modelfile ) ) if not name in get_function_spec . fndict . keys ( ) : raise Except...
def rowcount ( self ) : """This read - only attribute specifies the number of rows that the last . execute * ( ) produced ( for DQL statements like ` ` SELECT ` ` ) or affected ( for DML statements like ` ` UPDATE ` ` or ` ` INSERT ` ` ) ."""
if ( self . _closed or not self . _result or "rows" not in self . _result ) : return - 1 return self . _result . get ( "rowcount" , - 1 )
def process ( self , data ) : """Process the results from episode processing . : param list data : result instances"""
fields = [ ] for res in data : for epname , out in six . iteritems ( res . status ) : fields . append ( [ out . get ( 'state' ) , epname , out . get ( 'formatted_filename' ) , out . get ( 'messages' ) ] ) if fields : table . write_output ( fields )
def users ( self ) : """returns all users that have permissions for this resource"""
return sa . orm . relationship ( "User" , secondary = "users_resources_permissions" , passive_deletes = True , passive_updates = True , )
def get_user_avatar ( self , userid ) : '''get avatar by user id'''
response , status_code = self . __pod__ . User . get_v1_admin_user_uid_avatar ( sessionToken = self . __session , uid = userid ) . result ( ) self . logger . debug ( '%s: %s' % ( status_code , response ) ) return status_code , response
def calcaAJac ( xv , aA , dxv = None , freqs = False , dOdJ = False , actionsFreqsAngles = False , lb = False , coordFunc = None , vo = 220. , ro = 8. , R0 = 8. , Zsun = 0.025 , vsun = [ - 11.1 , 8. * 30.24 , 7.25 ] , _initacfs = None ) : """NAME : calcaAJac PURPOSE : calculate the Jacobian d ( J , theta ) / ...
if lb : coordFunc = lambda x : lbCoordFunc ( xv , vo , ro , R0 , Zsun , vsun ) if not coordFunc is None : R , vR , vT , z , vz , phi = coordFunc ( xv ) else : R , vR , vT , z , vz , phi = xv [ 0 ] , xv [ 1 ] , xv [ 2 ] , xv [ 3 ] , xv [ 4 ] , xv [ 5 ] if dxv is None : dxv = 10. ** - 8. * numpy . ones ( ...
def make_library_levels ( graph ) : """Create third party library logging level configurations . Tunes down overly verbose logs in commonly used libraries ."""
# inject the default components ; these can , but probably shouldn ' t , be overridden levels = { } for level in [ "DEBUG" , "INFO" , "WARN" , "ERROR" ] : levels . update ( { component : { "level" : level , } for component in graph . config . logging . levels . default [ level . lower ( ) ] } ) # override component...
def _ensure_product_string ( cls , product ) : """Ensure that all product locations are strings . Older components specify paths as lists of path components . Join those paths into a normal path string ."""
if isinstance ( product , str ) : return product if isinstance ( product , list ) : return os . path . join ( * product ) raise DataError ( "Unknown object (not str or list) specified as a component product" , product = product )
def sas_logical_jbods ( self ) : """Gets the SAS Logical JBODs API client . Returns : SasLogicalJbod :"""
if not self . __sas_logical_jbods : self . __sas_logical_jbods = SasLogicalJbods ( self . __connection ) return self . __sas_logical_jbods
def fromxml ( source , * args , ** kwargs ) : """Extract data from an XML file . E . g . : : > > > import petl as etl > > > # setup a file to demonstrate with . . . d = ' ' ' < table > . . . < tr > . . . < td > foo < / td > < td > bar < / td > . . . < / tr > . . . < tr > . . . < td > a < / td > < td...
source = read_source_from_arg ( source ) return XmlView ( source , * args , ** kwargs )
def make_cluster_vector ( rev_dict , n_src ) : """Converts the cluster membership dictionary to an array Parameters rev _ dict : dict ( int : int ) A single valued dictionary pointing from source index to cluster key for each source in a cluster . n _ src : int Number of source in the array Returns ...
out_array = - 1 * np . ones ( ( n_src ) , int ) for k , v in rev_dict . items ( ) : out_array [ k ] = v # We need this to make sure the see source points at itself out_array [ v ] = v return out_array
def jwk_wrap ( key , use = "" , kid = "" ) : """Instantiate a Key instance with the given key : param key : The keys to wrap : param use : What the key are expected to be use for : param kid : A key id : return : The Key instance"""
if isinstance ( key , rsa . RSAPublicKey ) or isinstance ( key , rsa . RSAPrivateKey ) : kspec = RSAKey ( use = use , kid = kid ) . load_key ( key ) elif isinstance ( key , str ) : kspec = SYMKey ( key = key , use = use , kid = kid ) elif isinstance ( key , ec . EllipticCurvePublicKey ) : kspec = ECKey ( us...
def read ( self , source , errors = 'strict' , clean_paragraphs = True ) : """source : A list of P objects ."""
reader = Rtf15Reader ( source , errors , clean_paragraphs ) return reader . go ( )
def within_miles ( self , key , point , max_distance , min_distance = None ) : """增加查询条件 , 限制返回结果指定字段值的位置在某点的一段距离之内 。 : param key : 查询条件字段名 : param point : 查询地理位置 : param max _ distance : 最大距离限定 ( 英里 ) : param min _ distance : 最小距离限定 ( 英里 ) : rtype : Query"""
if min_distance is not None : min_distance = min_distance / 3958.8 return self . within_radians ( key , point , max_distance / 3958.8 , min_distance )
def is_handler ( cls , name , value ) : """Detect an handler and return its wanted signal name ."""
signal_name = False config = None if callable ( value ) and hasattr ( value , SPEC_CONTAINER_MEMBER_NAME ) : spec = getattr ( value , SPEC_CONTAINER_MEMBER_NAME ) if spec [ 'kind' ] == 'handler' : signal_name = spec [ 'name' ] config = spec [ 'config' ] return signal_name , config
def save_data_files ( bs , prefix = None , directory = None ) : """Write the phonon band structure data files to disk . Args : bs ( : obj : ` ~ pymatgen . phonon . bandstructure . PhononBandStructureSymmLine ` ) : The phonon band structure . prefix ( : obj : ` str ` , optional ) : Prefix for data file . d...
filename = 'phonon_band.dat' filename = '{}_phonon_band.dat' . format ( prefix ) if prefix else filename directory = directory if directory else '.' filename = os . path . join ( directory , filename ) with open ( filename , 'w' ) as f : header = '#k-distance frequency[THz]\n' f . write ( header ) for band ...
def _alarms_present ( name , min_size_equals_max_size , alarms , alarms_from_pillar , region , key , keyid , profile ) : '''helper method for present . ensure that cloudwatch _ alarms are set'''
# load data from alarms _ from _ pillar tmp = copy . deepcopy ( __salt__ [ 'config.option' ] ( alarms_from_pillar , { } ) ) # merge with data from alarms if alarms : tmp = dictupdate . update ( tmp , alarms ) # set alarms , using boto _ cloudwatch _ alarm . present merged_return_value = { 'name' : name , 'result' :...
def failover_hdfs ( self , active_name , standby_name , force = False ) : """Initiate a failover of an HDFS NameNode HA pair . This will make the given stand - by NameNode active , and vice - versa . @ param active _ name : name of currently active NameNode . @ param standby _ name : name of NameNode currentl...
params = { "force" : "true" and force or "false" } args = { ApiList . LIST_KEY : [ active_name , standby_name ] } return self . _cmd ( 'hdfsFailover' , data = [ active_name , standby_name ] , params = { "force" : "true" and force or "false" } )
def _validate_params ( self ) : """method to sanitize model parameters Parameters None Returns None"""
self . distribution = GammaDist ( scale = self . scale ) super ( GammaGAM , self ) . _validate_params ( )
def parsebytes ( self , text , headersonly = False ) : """Create a message structure from a byte string . Returns the root of the message structure . Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not . The default is False , meaning it parses the entire content...
text = text . decode ( 'ASCII' , errors = 'surrogateescape' ) return self . parser . parsestr ( text , headersonly )
def unregister_iq_response ( self , from_ , id_ ) : """Unregister a registered callback or future for the IQ response identified by ` from _ ` and ` id _ ` . See : meth : ` register _ iq _ response _ future ` or : meth : ` register _ iq _ response _ callback ` for details on the arguments meanings and how t...
self . _iq_response_map . remove_listener ( ( from_ , id_ ) ) self . _logger . debug ( "iq response unregistered: from=%r, id=%r" , from_ , id_ )
def unpack ( self , buff = None , offset = 0 ) : """Unpack * buff * into this object . This method will convert a binary data into a readable value according to the attribute format . Args : buff ( bytes ) : Binary buffer . offset ( int ) : Where to begin unpacking . Raises : : exc : ` ~ . exceptions ...
property_type = UBInt16 ( enum_ref = TableFeaturePropType ) property_type . unpack ( buff , offset ) self . __class__ = TableFeaturePropType ( property_type . value ) . find_class ( ) length = UBInt16 ( ) length . unpack ( buff , offset = offset + 2 ) super ( ) . unpack ( buff [ : offset + length . value ] , offset = o...
def link_in ( self , other , preserve = False ) : """Link the * other * module into this one . The * other * module will be destroyed unless * preserve * is true ."""
if preserve : other = other . clone ( ) link_modules ( self , other )
def SetOption ( self , section , option , value , overwrite = True ) : """Set 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 set the value of . value : string , the value to set the option . overwrite : bool ,...
if not overwrite and self . config . has_option ( section , option ) : return if not self . config . has_section ( section ) : self . config . add_section ( section ) self . config . set ( section , option , str ( value ) )
def create ( model_config , model , vec_env , storage , takes , videoname , fps = 30 , sample_args = None ) : """Vel factory function"""
return RecordMovieCommand ( model_config = model_config , model_factory = model , env_factory = vec_env , storage = storage , videoname = videoname , takes = takes , fps = fps , sample_args = sample_args )
def _start_collective_solver ( self , state ) : '''Determines who from all the monitors monitoring this agent should resolve the issue .'''
own_address = state . agent . get_own_address ( ) monitors = [ IRecipient ( x ) for x in state . descriptor . partners if x . role == u'monitor' ] im_included = any ( [ x == own_address for x in monitors ] ) if not im_included : monitors . append ( own_address ) # this object is going to be stored in the state of C...
def NRMSE_sliding ( data , pred , windowSize ) : """Computing NRMSE in a sliding window : param data : : param pred : : param windowSize : : return : ( window _ center , NRMSE )"""
halfWindowSize = int ( round ( float ( windowSize ) / 2 ) ) window_center = range ( halfWindowSize , len ( data ) - halfWindowSize , int ( round ( float ( halfWindowSize ) / 5.0 ) ) ) nrmse = [ ] for wc in window_center : nrmse . append ( NRMSE ( data [ wc - halfWindowSize : wc + halfWindowSize ] , pred [ wc - half...