signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def _insert_one ( self , doc , ordered , check_keys , manipulate , write_concern , op_id , bypass_doc_val , session ) : """Internal helper for inserting a single document ."""
if manipulate : doc = self . __database . _apply_incoming_manipulators ( doc , self ) if not isinstance ( doc , RawBSONDocument ) and '_id' not in doc : doc [ '_id' ] = ObjectId ( ) doc = self . __database . _apply_incoming_copying_manipulators ( doc , self ) write_concern = write_concern or self . ...
def remove_key ( pki_dir , id_ ) : '''This method removes a specified key from the accepted keys dir'''
key = os . path . join ( pki_dir , 'minions' , id_ ) if os . path . isfile ( key ) : os . remove ( key ) log . debug ( 'Deleted \'%s\'' , key )
def load_combo_catalog ( ) : """Load a union of the user and global catalogs for convenience"""
user_dir = user_data_dir ( ) global_dir = global_data_dir ( ) desc = 'Generated from data packages found on your intake search path' cat_dirs = [ ] if os . path . isdir ( user_dir ) : cat_dirs . append ( user_dir + '/*.yaml' ) cat_dirs . append ( user_dir + '/*.yml' ) if os . path . isdir ( global_dir ) : c...
async def await_rpc ( self , address , rpc_id , * args , ** kwargs ) : """Send an RPC from inside the EmulationLoop . This is the primary method by which tasks running inside the EmulationLoop dispatch RPCs . The RPC is added to the queue of waiting RPCs to be drained by the RPC dispatch task and this corouti...
self . verify_calling_thread ( True , "await_rpc must be called from **inside** the event loop" ) if isinstance ( rpc_id , RPCDeclaration ) : arg_format = rpc_id . arg_format resp_format = rpc_id . resp_format rpc_id = rpc_id . rpc_id else : arg_format = kwargs . get ( 'arg_format' , None ) resp_for...
def create_table ( table , data ) : """Create table with defined name and fields : return : None"""
fields = data [ 'fields' ] query = '(' indexed_fields = '' for key , value in fields . items ( ) : non_case_field = value [ 0 ] [ 0 : value [ 0 ] . find ( '(' ) ] if non_case_field == 'int' : sign = value [ 0 ] [ value [ 0 ] . find ( ',' ) + 1 : - 1 : ] . strip ( ) if sign == 'signed' : ...
def get_objective_bank_hierarchy_design_session ( self ) : """Gets the session designing objective bank hierarchies . return : ( osid . learning . ObjectiveBankHierarchyDesignSession ) - an ObjectiveBankHierarchyDesignSession raise : OperationFailed - unable to complete request raise : Unimplemented - sup...
if not self . supports_objective_bank_hierarchy_design ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise OperationFailed ( ) try : session = sessions . ObjectiveBankHierarchyDesignSession ( runtime = self . _runtime ) except AttributeError : raise OperationFailed ...
def show ( self , user , identity ) : """Show the specified identity for the specified user . : param user : user id or User object : param identity : identity id object : return : Identity"""
url = self . _build_url ( self . endpoint . show ( user , identity ) ) return self . _get ( url )
def user_list ( self , userid , cur_p = '' ) : '''List the entities of the user .'''
current_page_number = int ( cur_p ) if cur_p else 1 current_page_number = 1 if current_page_number < 1 else current_page_number kwd = { 'current_page' : current_page_number } recs = MEntity2User . get_all_pager_by_username ( userid , current_page_num = current_page_number ) . objects ( ) self . render ( 'misc/entity/en...
def err ( msg , level = - 1 , prefix = True ) : """Prints the specified message as an error ; prepends " ERROR " to the message , so that can be left off ."""
if will_print ( level ) or verbosity is None : printer ( ( "ERROR: " if prefix else "" ) + msg , "red" )
def on_click ( self , event ) : """Click events - left click & scroll up / down : switch between rotations - right click : apply selected rotation"""
button = event [ "button" ] if button in [ 1 , 4 , 5 ] : self . scrolling = True self . _switch_selection ( ) elif button == 3 : self . _apply ( )
def all_modules_subpattern ( ) : u"""Builds a pattern for all toplevel names ( urllib , http , etc )"""
names_dot_attrs = [ mod . split ( u"." ) for mod in MAPPING ] ret = u"( " + u" | " . join ( [ dotted_name % ( simple_name % ( mod [ 0 ] ) , simple_attr % ( mod [ 1 ] ) ) for mod in names_dot_attrs ] ) ret += u" | " ret += u" | " . join ( [ simple_name % ( mod [ 0 ] ) for mod in names_dot_attrs if mod [ 1 ] == u"__init_...
def log ( obj1 , obj2 , sym , cname = None , aname = None , result = None ) : # pylint : disable = R0913 """Log the objects being compared and the result . When no result object is specified , subsequence calls will have an increased indentation level . The indentation level is decreased once a result object ...
fmt = "{o1} {sym} {o2} : {r}" if cname or aname : assert cname and aname # both must be specified fmt = "{c}.{a}: " + fmt if result is None : result = '...' fmt = _Indent . indent ( fmt ) _Indent . more ( ) else : _Indent . less ( ) fmt = _Indent . indent ( fmt ) msg = fmt . format ( o1 ...
def set_column_si_format ( tree_column , model_column_index , cell_renderer = None , digits = 2 ) : '''Set the text of a numeric cell according to [ SI prefixes ] [ 1] For example , ` 1000 - > ' 1.00k ' ` . [1 ] : https : / / en . wikipedia . org / wiki / Metric _ prefix # List _ of _ SI _ prefixes Args : t...
def set_property ( column , cell_renderer , list_store , iter , store_i ) : cell_renderer . set_property ( 'text' , si_format ( list_store [ iter ] [ store_i ] , digits ) ) if cell_renderer is None : cells = tree_column . get_cells ( ) else : cells = [ cell_renderer ] for cell_renderer_i in cells : tree...
def integrate_to_file ( what , filename , start_line , end_line ) : """WARNING this is working every second run . . so serious bug Integrate content into a file withing " line marks " """
try : with open ( filename ) as f : lines = f . readlines ( ) except IOError : lines = [ ] tmp_file = tempfile . NamedTemporaryFile ( delete = False ) lines . reverse ( ) # first copy before start line while lines : line = lines . pop ( ) if line == start_line : break tmp_file . writ...
def _lookup_drill ( name , rdtype , timeout = None , servers = None , secure = None ) : '''Use drill to lookup addresses : param name : Name of record to search : param rdtype : DNS record type : param timeout : command return timeout : param servers : [ ] of servers to use : return : [ ] of records or Fa...
cmd = 'drill ' if secure : cmd += '-D -o ad ' cmd += '{0} {1} ' . format ( rdtype , name ) if servers : cmd += '' . join ( [ '@{0} ' . format ( srv ) for srv in servers ] ) cmd = __salt__ [ 'cmd.run_all' ] ( cmd , timeout = timeout , python_shell = False , output_loglevel = 'quiet' ) if cmd [ 'retcode' ] != 0 :...
def trigger_info ( self , trigger = None , dump = False ) : """Get information about a trigger . Pass in a raw trigger to find out what file name and line number it appeared at . This is useful for e . g . tracking down the location of the trigger last matched by the user via ` ` last _ match ( ) ` ` . Return...
if dump : return self . _syntax response = None # Search the syntax tree for the trigger . for category in self . _syntax : for topic in self . _syntax [ category ] : if trigger in self . _syntax [ category ] [ topic ] : # We got a match ! if response is None : response = lis...
def load_progress ( self , resume_step ) : """load _ progress : loads progress from restoration file Args : resume _ step ( str ) : step at which to resume session Returns : manager with progress from step"""
resume_step = Status [ resume_step ] progress_path = self . get_restore_path ( resume_step ) # If progress is corrupted , revert to step before while not self . check_for_session ( resume_step ) : config . LOGGER . error ( "Ricecooker has not reached {0} status. Reverting to earlier step..." . format ( resume_step ...
def bn2float ( module : nn . Module ) -> nn . Module : "If ` module ` is batchnorm don ' t use half precision ."
if isinstance ( module , torch . nn . modules . batchnorm . _BatchNorm ) : module . float ( ) for child in module . children ( ) : bn2float ( child ) return module
def urlopen ( self , url , ** kwargs ) : """GET a file - like object for a URL using HTTP . This is a thin wrapper around : meth : ` requests . Session . get ` that returns a file - like object wrapped around the resulting content . Parameters url : str The URL to request kwargs : arbitrary keyword argu...
return BytesIO ( self . create_session ( ) . get ( url , ** kwargs ) . content )
def _from_engine ( cls , data , alias_list ) : """Return an alias for the engine . The data is dict provided when calling engine . alias _ resolving ( ) . The alias list is the list of aliases pre - fetched from Alias . objects . all ( ) . This will return an Alias element by taking the alias _ ref and find...
for alias in alias_list : href = data . get ( 'alias_ref' ) if alias . href == href : _alias = Alias ( alias . name , href = href ) _alias . resolved_value = data . get ( 'resolved_value' ) _alias . typeof = alias . _meta . type return _alias
def _find_cgroup_mounts ( ) : """Return the information which subsystems are mounted where . @ return a generator of tuples ( subsystem , mountpoint )"""
try : with open ( '/proc/mounts' , 'rt' ) as mountsFile : for mount in mountsFile : mount = mount . split ( ' ' ) if mount [ 2 ] == 'cgroup' : mountpoint = mount [ 1 ] options = mount [ 3 ] for option in options . split ( ',' ) : ...
def getVerificators ( self ) : """Returns the user ids of the users that verified this analysis"""
verifiers = list ( ) actions = [ "verify" , "multi_verify" ] for event in wf . getReviewHistory ( self ) : if event [ 'action' ] in actions : verifiers . append ( event [ 'actor' ] ) sorted ( verifiers , reverse = True ) return verifiers
def cycle_slice ( sliceable , start , end ) : """Given a list , return right hand cycle direction slice from start to end . Usage : : > > > array = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9] > > > cycle _ slice ( array , 4 , 7 ) # from array [ 4 ] to array [ 7] [4 , 5 , 6 , 7] > > > cycle _ slice ( array , ...
if type ( sliceable ) != list : sliceable = list ( sliceable ) if end >= start : return sliceable [ start : end + 1 ] else : return sliceable [ start : ] + sliceable [ : end + 1 ]
def _generate_examples ( self , archive ) : """Yields examples ."""
prefix_len = len ( "SUN397" ) with tf . Graph ( ) . as_default ( ) : with utils . nogpu_session ( ) as sess : for filepath , fobj in archive : if ( filepath . endswith ( ".jpg" ) and filepath not in _SUN397_IGNORE_IMAGES ) : # Note : all files in the tar . gz are in SUN397 / . . . ...
def fetch_data_detailled_energy_use ( self , start_date = None , end_date = None ) : """Get detailled energy use from a specific contract ."""
if start_date is None : start_date = datetime . datetime . now ( HQ_TIMEZONE ) - datetime . timedelta ( days = 1 ) if end_date is None : end_date = datetime . datetime . now ( HQ_TIMEZONE ) # Get http session yield from self . _get_httpsession ( ) # Get login page login_url = yield from self . _get_login_page (...
def tree2hdf5 ( tree , hfile , group = None , entries = - 1 , show_progress = False , ** kwargs ) : """Convert a TTree into a HDF5 table . Parameters tree : ROOT . TTree A ROOT TTree . hfile : string or PyTables HDF5 File A PyTables HDF5 File handle or string path to an existing HDF5 file . group : stri...
show_progress = show_progress and check_tty ( sys . stdout ) if show_progress : widgets = [ Percentage ( ) , ' ' , Bar ( ) , ' ' , ETA ( ) ] own_h5file = False if isinstance ( hfile , string_types ) : hfile = tables_open ( filename = hfile , mode = "w" , title = "Data" ) own_h5file = True log . info ( "Conv...
def convert_elementwise_add ( net , node , module , builder ) : """Convert an elementwise add layer from mxnet to coreml . Parameters network : net A mxnet network object . layer : node Node to convert . module : module An module for MXNet builder : NeuralNetworkBuilder A neural network builder ob...
input_names , output_name = _get_input_output_name ( net , node , [ 0 , 1 ] ) name = node [ 'name' ] builder . add_elementwise ( name , input_names , output_name , 'ADD' )
def app1 ( self ) : """First APP1 marker in image markers ."""
for m in self . _markers : if m . marker_code == JPEG_MARKER_CODE . APP1 : return m raise KeyError ( 'no APP1 marker in image' )
def ui ( root_url , path ) : """Generate URL for a path in the Taskcluster ui . The purpose of the function is to switch on rootUrl : " The driver for having a ui method is so we can just call ui with a path and any root url , and the returned url should work for both our current deployment ( with root URL = ...
root_url = root_url . rstrip ( '/' ) path = path . lstrip ( '/' ) if root_url == OLD_ROOT_URL : return 'https://tools.taskcluster.net/{}' . format ( path ) else : return '{}/{}' . format ( root_url , path )
def performAction ( self , action ) : """Execute one action ."""
# print " ACTION : " , action self . t += 1 Task . performAction ( self , action ) # self . addReward ( ) self . samples += 1
def _paginate ( url , topkey , * args , ** kwargs ) : '''Wrapper to assist with paginated responses from Digicert ' s REST API .'''
ret = salt . utils . http . query ( url , ** kwargs ) if 'errors' in ret [ 'dict' ] : return ret [ 'dict' ] lim = int ( ret [ 'dict' ] [ 'page' ] [ 'limit' ] ) total = int ( ret [ 'dict' ] [ 'page' ] [ 'total' ] ) if total == 0 : return { } numpages = ( total / lim ) + 1 # If the count returned is less than the...
def score ( self , X , y ) : """Force use of accuracy score since we don ' t inherit from ClassifierMixin"""
from sklearn . metrics import accuracy_score return accuracy_score ( y , self . predict ( X ) )
def list_all_states ( cls , ** kwargs ) : """List States Return a list of States This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async = True > > > thread = api . list _ all _ states ( async = True ) > > > result = thread . get ( ) : param asy...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async' ) : return cls . _list_all_states_with_http_info ( ** kwargs ) else : ( data ) = cls . _list_all_states_with_http_info ( ** kwargs ) return data
def get ( self , key , default = None , type_ = None ) : """Return the last data value for the passed key . If key doesn ' t exist or value is an empty list , return ` default ` ."""
try : rv = self [ key ] except KeyError : return default if type_ is not None : try : rv = type_ ( rv ) except ValueError : rv = default return rv
def task_start_time ( self ) : """Return the time the task starts . Time is set according to iso8601."""
return datetime . time ( self . task_start_parameters [ ATTR_SMART_TASK_TRIGGER_TIME_START_HOUR ] , self . task_start_parameters [ ATTR_SMART_TASK_TRIGGER_TIME_START_MIN ] )
def search ( self , base_dn , search_filter , attributes = ( ) ) : """Perform an AD search : param str base _ dn : The base DN to search within : param str search _ filter : The search filter to apply , such as : * objectClass = person * : param list attributes : Object attributes to populate , defaults to ...
results = [ ] page = 0 while page == 0 or self . sprc . cookie : page += 1 # pylint : disable = no - member message_id = self . ldap . search_ext ( base_dn , ldap . SCOPE_SUBTREE , search_filter , attributes , serverctrls = [ self . sprc ] ) # pylint : enable = no - member data , server_controls = s...
def decode_mysql_literal ( text ) : """Attempts to decode given MySQL literal into Python value . : param text : Value to be decoded , as MySQL literal . : type text : str : return : Python version of the given MySQL literal . : rtype : any"""
if MYSQL_NULL_PATTERN . match ( text ) : return None if MYSQL_BOOLEAN_PATTERN . match ( text ) : return text . lower ( ) == "true" if MYSQL_FLOAT_PATTERN . match ( text ) : return float ( text ) if MYSQL_INT_PATTERN . match ( text ) : return int ( text ) if MYSQL_STRING_PATTERN . match ( text ) : re...
def _adjust_rate ( self , real_wave_mfcc , algo_parameters ) : """RATE"""
self . log ( u"Called _adjust_rate" ) self . _apply_rate ( max_rate = algo_parameters [ 0 ] , aggressive = False )
def citation_director ( ** kwargs ) : """Direct the citation elements based on their qualifier ."""
qualifier = kwargs . get ( 'qualifier' , '' ) content = kwargs . get ( 'content' , '' ) if qualifier == 'publicationTitle' : return CitationJournalTitle ( content = content ) elif qualifier == 'volume' : return CitationVolume ( content = content ) elif qualifier == 'issue' : return CitationIssue ( content =...
def purge_duplicates ( list_in ) : """Remove duplicates from list while preserving order . Parameters list _ in : Iterable Returns list List of first occurences in order"""
_list = [ ] for item in list_in : if item not in _list : _list . append ( item ) return _list
def display_image_file ( fn , width = 'auto' , height = 'auto' , preserve_aspect_ratio = None ) : """Display an image in the terminal . A newline is not printed . width and height are strings , following the format N : N character cells . Npx : N pixels . N % : N percent of the session ' s width or height...
with open ( os . path . realpath ( os . path . expanduser ( fn ) ) , 'rb' ) as f : sys . stdout . buffer . write ( image_bytes ( f . read ( ) , filename = fn , width = width , height = height , preserve_aspect_ratio = preserve_aspect_ratio ) )
def set_pwm ( self , values ) : """Set pwm values on the controlled pins . : param values : Values to set ( 0.0-1.0 ) . : return :"""
if len ( values ) != len ( self . _pins ) : raise ValueError ( 'Number of values has to be identical with ' 'the number of pins.' ) if not all ( 0 <= v <= 1 for v in values ) : raise ValueError ( 'Values must be between 0 and 1.' ) for tries in range ( self . IO_TRIES ) : try : self . _set_pwm ( sel...
def cumulative_value ( self , slip_moment , mmax , mag_value , bbar , dbar ) : '''Returns the rate of events with M > mag _ value : param float slip _ moment : : param float slip _ moment : Product of slip ( cm / yr ) * Area ( cm ^ 2 ) * shear _ modulus ( dyne - cm ) : param float mmax : Maximum magnitude...
delta_m = mmax - mag_value a_1 = self . _get_a1 ( bbar , dbar , slip_moment , mmax ) return a_1 * np . exp ( bbar * ( delta_m ) ) * ( delta_m > 0.0 )
def parse_time ( t ) : """Parse string time format to microsecond"""
if isinstance ( t , ( str , unicode ) ) : b = re_time . match ( t ) if b : v , unit = int ( b . group ( 1 ) ) , b . group ( 2 ) if unit == 's' : return v * 1000 elif unit == 'm' : return v * 60 * 1000 elif unit == 'h' : return v * 60 * 60 * 100...
def Poisson ( mu : vertex_constructor_param_types , label : Optional [ str ] = None ) -> Vertex : """One to one constructor for mapping some shape of mu to a matching shaped Poisson . : param mu : mu with same shape as desired Poisson tensor or scalar"""
return Integer ( context . jvm_view ( ) . PoissonVertex , label , cast_to_double_vertex ( mu ) )
def validate_unwrap ( self , value ) : '''Expects a list of dictionaries with ` ` k ` ` and ` ` v ` ` set to the keys and values that will be unwrapped into the output python dictionary should have'''
if not isinstance ( value , list ) : self . _fail_validation_type ( value , list ) for value_dict in value : if not isinstance ( value_dict , dict ) : cause = BadValueException ( '' , value_dict , 'Values in a KVField list must be dicts' ) self . _fail_validation ( value , 'Values in a KVField l...
def email_list_to_email_dict ( email_list ) : """Convert a list of email to a dict of email ."""
if email_list is None : return { } result = { } for value in email_list : realname , address = email . utils . parseaddr ( value ) result [ address ] = realname if realname and address else address return result
def postorder ( self ) : """Return the nodes in the binary tree using post - order _ traversal . A post - order _ traversal visits left subtree , right subtree , then root . . . _ post - order : https : / / en . wikipedia . org / wiki / Tree _ traversal : return : List of nodes . : rtype : [ binarytree . No...
node_stack = [ ] result = [ ] node = self while True : while node is not None : if node . right is not None : node_stack . append ( node . right ) node_stack . append ( node ) node = node . left node = node_stack . pop ( ) if ( node . right is not None and len ( node_stac...
async def get ( self , * , encoding = None , decoder = None ) : """Wait for and return pub / sub message from one of channels . Return value is either : * tuple of two elements : channel & message ; * tuple of three elements : pattern channel , ( target channel & message ) ; * or None in case Receiver is no...
# TODO : add note about raised exception and end marker . # Flow before ClosableQueue : # - ch . get ( ) - > message # - ch . close ( ) - > ch . put ( None ) # - ch . get ( ) - > None # - ch . get ( ) - > ChannelClosedError # Current flow : # - ch . get ( ) - > message # - ch . close ( ) - > ch . _ closed = True # - ch...
def copy_headers ( self , source_databox ) : """Loops over the hkeys of the source _ databox , updating this databoxes ' header ."""
for k in source_databox . hkeys : self . insert_header ( k , source_databox . h ( k ) ) return self
def _on_msg ( self , msg ) : """Handle messages from the front - end"""
data = msg [ 'content' ] [ 'data' ] # If the message is a call invoke , run the function and send # the results . if 'callback' in data : guid = data [ 'callback' ] callback = callback_registry [ guid ] args = data [ 'arguments' ] args = [ self . deserialize ( a ) for a in args ] index = data [ 'ind...
def _to_dict ( self ) : """Return a json dictionary representing this model ."""
_dict = { } if hasattr ( self , 'duration' ) and self . duration is not None : _dict [ 'duration' ] = self . duration if hasattr ( self , 'name' ) and self . name is not None : _dict [ 'name' ] = self . name if hasattr ( self , 'details' ) and self . details is not None : _dict [ 'details' ] = self . detail...
def _handle_offset_response ( self , response ) : """Handle responses to both OffsetRequest and OffsetFetchRequest , since they are similar enough . : param response : A tuple of a single OffsetFetchResponse or OffsetResponse"""
# Got a response , clear our outstanding request deferred self . _request_d = None # Successful request , reset our retry delay , count , etc self . retry_delay = self . retry_init_delay self . _fetch_attempt_count = 1 response = response [ 0 ] if hasattr ( response , 'offsets' ) : # It ' s a response to an OffsetReque...
def removc ( item , inset ) : """Remove an item from a character set . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / removc _ c . html : param item : Item to be removed . : type item : str : param inset : Set to be updated . : type inset : spiceypy . utils . support _ typ...
assert isinstance ( inset , stypes . SpiceCell ) assert inset . dtype == 0 item = stypes . stringToCharP ( item ) libspice . removc_c ( item , ctypes . byref ( inset ) )
def service ( self ) : """Service the root socket Read from the root socket and forward one datagram to a connection . The call will return without forwarding data if any of the following occurs : * An error is encountered while reading from the root socket * Reading from the root socket times out * The...
self . payload , self . payload_peer_address = self . datagram_socket . recvfrom ( UDP_MAX_DGRAM_LENGTH ) _logger . debug ( "Received datagram from peer: %s" , self . payload_peer_address ) if not self . payload : self . payload_peer_address = None return if self . connections . has_key ( self . payload_peer_ad...
def create_permissions_from_tuples ( model , codename_tpls ) : """Creates custom permissions on model " model " ."""
if codename_tpls : model_cls = django_apps . get_model ( model ) content_type = ContentType . objects . get_for_model ( model_cls ) for codename_tpl in codename_tpls : app_label , codename , name = get_from_codename_tuple ( codename_tpl , model_cls . _meta . app_label ) try : Per...
def temp ( dev , target ) : """Gets or sets the target temperature ."""
click . echo ( "Current target temp: %s" % dev . target_temperature ) if target : click . echo ( "Setting target temp: %s" % target ) dev . target_temperature = target
def protect ( self , password = None , read_protect = False , protect_from = 0 ) : """Set password protection or permanent lock bits . If the * password * argument is None , all memory pages will be protected by setting the relevant lock bits ( note that lock bits can not be reset ) . If valid NDEF management...
args = ( password , read_protect , protect_from ) return super ( NTAG21x , self ) . protect ( * args )
def set_head_middle_tail ( self , head_length = None , middle_length = None , tail_length = None ) : """Set the HEAD , MIDDLE , TAIL explicitly . If a parameter is ` ` None ` ` , it will be ignored . If both ` ` middle _ length ` ` and ` ` tail _ length ` ` are specified , only ` ` middle _ length ` ` will be...
for variable , name in [ ( head_length , "head_length" ) , ( middle_length , "middle_length" ) , ( tail_length , "tail_length" ) ] : if ( variable is not None ) and ( not isinstance ( variable , TimeValue ) ) : raise TypeError ( u"%s is not None or TimeValue" % name ) if ( variable is not None ) and ( v...
def get_size ( self , bucket : str , key : str ) -> int : """Retrieves the filesize : param bucket : the bucket the object resides in . : param key : the key of the object for which size is being retrieved . : return : integer equal to filesize in bytes"""
blob_obj = self . _get_blob_obj ( bucket , key ) return blob_obj . size
def search ( self , dstpath , ** params ) : """For compatibility with generic image catalog search ."""
self . logger . debug ( "search params=%s" % ( str ( params ) ) ) ra , dec = params [ 'ra' ] , params [ 'dec' ] if not ( ':' in ra ) : # Assume RA and DEC are in degrees ra_deg = float ( ra ) dec_deg = float ( dec ) else : # Assume RA and DEC are in standard string notation ra_deg = wcs . hmsStrToDeg ( ra )...
def result ( self ) : """Return the value at an address , optionally waiting until it is set from the context _ manager , or set based on the pre - fetch mechanism . Returns : ( bytes ) : The opaque value for an address ."""
if self . _read_only : return self . _result with self . _condition : if self . _wait_for_tree and not self . _result_set_in_context : self . _condition . wait_for ( lambda : self . _tree_has_set or self . _result_set_in_context ) return self . _result
def has_table ( table_name , con , schema = None ) : """Check if DataBase has named table . Parameters table _ name : string Name of SQL table . con : SQLAlchemy connectable ( engine / connection ) or sqlite3 DBAPI2 connection Using SQLAlchemy makes it possible to use any DB supported by that library . ...
pandas_sql = pandasSQL_builder ( con , schema = schema ) return pandas_sql . has_table ( table_name )
def is_group_name_exists ( self , group_name ) : """check if group with given name is already exists"""
groups = self . m [ "groups" ] for g in groups : if ( g [ "group_name" ] == group_name ) : return True return False
def cleanup ( self ) : """Do the final clean up before shutting down ."""
size = settings . get ( 'history_size' ) self . _save_history_to_file ( self . commandprompthistory , self . _cmd_hist_file , size = size ) self . _save_history_to_file ( self . senderhistory , self . _sender_hist_file , size = size ) self . _save_history_to_file ( self . recipienthistory , self . _recipients_hist_file...
def get_history ( self , exp , rep , tags ) : """returns the whole history for one experiment and one repetition . tags can be a string or a list of strings . if tags is a string , the history is returned as list of values , if tags is a list of strings or ' all ' , history is returned as a dictionary of list...
params = self . get_params ( exp ) if params == None : raise SystemExit ( 'experiment %s not found.' % exp ) # make list of tags , even if it is only one if tags != 'all' and not hasattr ( tags , '__iter__' ) : tags = [ tags ] results = { } logfile = os . path . join ( exp , '%i.log' % rep ) try : f = open ...
def write_head ( self , title , css_path , default_css ) : """Writes the head part for the generated document , with the given title and CSS"""
self . title = title self . write ( '''<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>{title}</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link id="style" href="{rel_css}/docs.dark.css" rel="stylesheet"> <sc...
def compute_taxes ( self , precision = None ) : '''Returns the total amount of taxes for this group . @ param precision : int Number of decimal places @ return : Decimal'''
return sum ( [ group . compute_taxes ( precision ) for group in self . __groups ] )
def psiblast_n_neighbors ( seqs , n = 100 , blast_db = None , core_threshold = 1e-50 , extra_threshold = 1e-10 , lower_threshold = 1e-6 , step = 100 , method = "two-step" , blast_mat_root = None , params = { } , add_seq_names = False , WorkingDir = None , SuppressStderr = None , SuppressStdout = None , input_handler = ...
if blast_db : params [ "-d" ] = blast_db ih = input_handler or guess_input_handler ( seqs , add_seq_names ) recs = seqs_to_stream ( seqs , ih ) # checkpointing can only handle one seq . . . # set up the parameters for the core and additional runs max_iterations = params [ '-j' ] params [ '-j' ] = 2 # won ' t checkp...
def _monitoring_resource_types_list ( args , _ ) : """Lists the resource descriptors in the project ."""
project_id = args [ 'project' ] pattern = args [ 'type' ] or '*' descriptors = gcm . ResourceDescriptors ( context = _make_context ( project_id ) ) dataframe = descriptors . as_dataframe ( pattern = pattern ) return _render_dataframe ( dataframe )
def do_version ( ) : """Return version details of the running server api"""
v = ApiPool . ping . model . Version ( name = ApiPool ( ) . current_server_name , version = ApiPool ( ) . current_server_api . get_version ( ) , container = get_container_version ( ) , ) log . info ( "/version: " + pprint . pformat ( v ) ) return v
def create ( cls , pid , idle_ttl = DEFAULT_IDLE_TTL , max_size = DEFAULT_MAX_SIZE , time_method = None ) : """Create a new pool , with the ability to pass in values to override the default idle TTL and the default maximum size . A pool ' s idle TTL defines the amount of time that a pool can be open without a...
if pid in cls . _pools : raise KeyError ( 'Pool %s already exists' % pid ) with cls . _lock : LOGGER . debug ( "Creating Pool: %s (%i/%i)" , pid , idle_ttl , max_size ) cls . _pools [ pid ] = Pool ( pid , idle_ttl , max_size , time_method )
def register_model ( cls , model ) : """Register a model class according to its remote name Args : model : the model to register"""
rest_name = model . rest_name resource_name = model . resource_name if rest_name not in cls . _model_rest_name_registry : cls . _model_rest_name_registry [ rest_name ] = [ model ] cls . _model_resource_name_registry [ resource_name ] = [ model ] elif model not in cls . _model_rest_name_registry [ rest_name ] : ...
def set_children_padding ( widget , types , height = None , width = None ) : """Sets given Widget children padding . : param widget : Widget to sets the children padding . : type widget : QWidget : param types : Children types . : type types : tuple or list : param height : Height padding . : type heigh...
for type in types : for child in widget . findChildren ( type ) : child . setStyleSheet ( "{0}{{height: {1}px; width: {2}px;}}" . format ( type . __name__ , child . fontMetrics ( ) . height ( ) + ( height if height is not None else 0 ) * 2 , child . fontMetrics ( ) . width ( child . text ( ) ) + ( width if ...
def start ( self ) : """Find the first data entry and prepare to parse ."""
while not self . is_start ( self . current_tag ) : self . next ( ) self . new_entry ( )
def key ( state , host , key = None , keyserver = None , keyid = None ) : '''Add apt gpg keys with ` ` apt - key ` ` . + key : filename or URL + keyserver : URL of keyserver to fetch key from + keyid : key identifier when using keyserver Note : Always returns an add command , not state checking . keyser...
if key : # If URL , wget the key to stdout and pipe into apt - key , because the " adv " # apt - key passes to gpg which doesn ' t always support https ! if urlparse ( key ) . scheme : yield 'wget -O- {0} | apt-key add -' . format ( key ) else : yield 'apt-key add {0}' . format ( key ) if keyser...
def connect ( self , pin = None ) : """Opens the port and initializes the modem and SIM card : param pin : The SIM card PIN code , if any : type pin : str : raise PinRequiredError : if the SIM card requires a PIN but none was provided : raise IncorrectPinError : if the specified PIN is incorrect"""
self . log . info ( 'Connecting to modem on port %s at %dbps' , self . port , self . baudrate ) super ( GsmModem , self ) . connect ( ) # Send some initialization commands to the modem try : self . write ( 'ATZ' ) # reset configuration except CommandError : # Some modems require a SIM PIN at this stage already ...
def is_possible_hour ( self , hour ) : """Check if a float hour is a possible hour for this analysis period ."""
if hour > 23 and self . is_possible_hour ( 0 ) : hour = int ( hour ) if not self . _is_overnight : return self . st_time . hour <= hour <= self . end_time . hour else : return self . st_time . hour <= hour <= 23 or 0 <= hour <= self . end_time . hour
def handle_query_error ( msg , query , session , payload = None ) : """Local method handling error while processing the SQL"""
payload = payload or { } troubleshooting_link = config [ 'TROUBLESHOOTING_LINK' ] query . error_message = msg query . status = QueryStatus . FAILED query . tmp_table_name = None session . commit ( ) payload . update ( { 'status' : query . status , 'error' : msg , } ) if troubleshooting_link : payload [ 'link' ] = t...
def profiles ( self ) : """A list of all profiles on this web property . You may select a specific profile using its name , its id or an index . ` ` ` python property . profiles [ 0] property . profiles [ ' 9234823 ' ] property . profiles [ ' marketing profile ' ]"""
raw_profiles = self . account . service . management ( ) . profiles ( ) . list ( accountId = self . account . id , webPropertyId = self . id ) . execute ( ) [ 'items' ] profiles = [ Profile ( raw , self ) for raw in raw_profiles ] return addressable . List ( profiles , indices = [ 'id' , 'name' ] , insensitive = True )
def items ( self ) : """Iterator over the words in the dictionary Yields : str : The next word in the dictionary int : The number of instances in the dictionary Note : This is the same as ` dict . items ( ) `"""
for word in self . _dictionary . keys ( ) : yield word , self . _dictionary [ word ]
def get_channel_by_channel_id ( self , channel_id ) : """Get a channel by channel id"""
self . _validate_uuid ( channel_id ) url = "/notification/v1/channel/{}" . format ( channel_id ) response = NWS_DAO ( ) . getURL ( url , self . _read_headers ) if response . status != 200 : raise DataFailureException ( url , response . status , response . data ) data = json . loads ( response . data ) return self ....
def calc_factors_grid ( self , spatial_reference , zone_array = None , minpts_interp = 1 , maxpts_interp = 20 , search_radius = 1.0e+10 , verbose = False , var_filename = None , forgive = False ) : """calculate kriging factors ( weights ) for a structured grid . Parameters spatial _ reference : ( flopy . utils ...
self . spatial_reference = spatial_reference self . interp_data = None # assert isinstance ( spatial _ reference , SpatialReference ) try : x = self . spatial_reference . xcentergrid . copy ( ) y = self . spatial_reference . ycentergrid . copy ( ) except Exception as e : raise Exception ( "spatial_reference...
def glob7s ( p , Input , flags ) : '''/ * VERSION OF GLOBE FOR LOWER ATMOSPHERE 10/26/99'''
pset = 2.0 t = [ 0.0 ] * 14 dr = 1.72142E-2 ; dgtr = 1.74533E-2 ; # / * confirm parameter set * / if ( p [ 99 ] == 0 ) : # pragma : no cover p [ 99 ] = pset ; # for j in range ( 14 ) : # Already taken care of # t [ j ] = 0.0; cd32 = cos ( dr * ( Input . doy - p [ 31 ] ) ) ; cd18 = cos ( 2.0 * dr * ( Input . doy - p...
def _start_recording ( self , * args , ** kwargs ) : """Starts recording Parameters * args : any Ordinary args used for calling the specified data sampler method * * kwargs : any Keyword args used for calling the specified data sampler method"""
while not self . _cmds_q . empty ( ) : self . _cmds_q . get_nowait ( ) while not self . _data_qs [ self . _cur_data_segment ] . empty ( ) : self . _data_qs [ self . _cur_data_segment ] . get_nowait ( ) self . _args = args self . _kwargs = kwargs self . _recording = True self . start ( )
def cleanup ( self , sched , coro ) : """Remove this coro from the waiting for signal queue ."""
try : sched . sigwait [ self . name ] . remove ( ( self , coro ) ) except ValueError : pass return True
def delete_object ( self , id ) : """Deletes the object with the given ID from the graph ."""
# x = self . request ( id , post _ args = { " method " : " delete " } ) params = urllib . parse . urlencode ( { "method" : "delete" , 'access_token' : str ( id ) } ) u = requests . get ( "https://graph.facebook.com/" + str ( id ) + "?" + params ) groups = u . json ( ) return groups
def send_attachment_url ( self , recipient_id , attachment_type , attachment_url , notification_type = NotificationType . regular ) : """Send an attachment to the specified recipient using URL . Input : recipient _ id : recipient id to send to attachment _ type : type of attachment ( image , video , audio , f...
return self . send_message ( recipient_id , { 'attachment' : { 'type' : attachment_type , 'payload' : { 'url' : attachment_url } } } , notification_type )
def _finalise_figure ( fig , ** kwargs ) : # pragma : no cover """Internal function to wrap up a figure . Possible arguments : : type title : str : type show : bool : type save : bool : type savefile : str : type return _ figure : bool"""
title = kwargs . get ( "title" ) or None show = kwargs . get ( "show" ) or False save = kwargs . get ( "save" ) or False savefile = kwargs . get ( "savefile" ) or "EQcorrscan_figure.png" return_fig = kwargs . get ( "return_figure" ) or False if title : fig . suptitle ( title ) if show : fig . show ( ) if save :...
def set_mark ( self ) : """Mark the current location and return its id so that the buffer can return later ."""
self . _bookmarks . append ( self . _offset ) return len ( self . _bookmarks ) - 1
def tag ( request , tag_id = None ) : """The view used to render a tag after the page has loaded ."""
html = get_tag_html ( tag_id ) t = template . Template ( html ) c = template . RequestContext ( request ) return HttpResponse ( t . render ( c ) )
def worker ( workers ) : """Starts a Superset worker for async SQL query execution ."""
logging . info ( "The 'superset worker' command is deprecated. Please use the 'celery " "worker' command instead." ) if workers : celery_app . conf . update ( CELERYD_CONCURRENCY = workers ) elif config . get ( 'SUPERSET_CELERY_WORKERS' ) : celery_app . conf . update ( CELERYD_CONCURRENCY = config . get ( 'SUPE...
def html_format ( data , out , opts = None , ** kwargs ) : '''Return the formatted string as HTML .'''
ansi_escaped_string = string_format ( data , out , opts , ** kwargs ) return ansi_escaped_string . replace ( ' ' , '&nbsp;' ) . replace ( '\n' , '<br />' )
def preprocessing ( aws_config , ip_ranges = [ ] , ip_ranges_name_key = None ) : """Tweak the AWS config to match cross - service resources and clean any fetching artifacts : param aws _ config : : return :"""
map_all_sgs ( aws_config ) map_all_subnets ( aws_config ) set_emr_vpc_ids ( aws_config ) # parse _ elb _ policies ( aws _ config ) # Various data processing calls add_security_group_name_to_ec2_grants ( aws_config [ 'services' ] [ 'ec2' ] , aws_config [ 'aws_account_id' ] ) process_cloudtrail_trails ( aws_config [ 'ser...
def save ( self , path , key , format , data ) : """Save a newly generated thumbnail . path : path of the source image key : key of the thumbnail format : thumbnail ' s file extension data : thumbnail ' s binary data"""
thumbpath = self . get_thumbpath ( path , key , format ) fullpath = os . path . join ( self . out_path , thumbpath ) self . save_thumb ( fullpath , data ) url = self . get_url ( thumbpath ) thumb = Thumb ( url , key , fullpath ) return thumb
def selectAll ( self ) : """Selects all the items in the scene ."""
currLayer = self . _currentLayer for item in self . items ( ) : layer = item . layer ( ) if ( layer == currLayer or not layer ) : item . setSelected ( True )
def visitStartActions ( self , ctx : ShExDocParser . StartActionsContext ) : """startActions : codeDecl +"""
self . context . schema . startActs = [ ] for cd in ctx . codeDecl ( ) : cdparser = ShexAnnotationAndSemactsParser ( self . context ) cdparser . visit ( cd ) self . context . schema . startActs += cdparser . semacts
def register_list_auth_roles_command ( self , list_auth_roles_func ) : """Add ' list _ auth _ roles ' command to list project authorization roles that can be used with add _ user . : param list _ auth _ roles _ func : function : run when user choses this option ."""
description = "List authorization roles for use with add_user command." list_auth_roles_parser = self . subparsers . add_parser ( 'list-auth-roles' , description = description ) list_auth_roles_parser . set_defaults ( func = list_auth_roles_func )
def parse_encoding ( value = None ) : """Parse a value to a valid encoding . This function accepts either a member of : py : class : ` ~ cg : cryptography . hazmat . primitives . serialization . Encoding ` or a string describing a member . If no value is passed , it will assume ` ` PEM ` ` as a default value ...
if value is None : return ca_settings . CA_DEFAULT_ENCODING elif isinstance ( value , Encoding ) : return value elif isinstance ( value , six . string_types ) : if value == 'ASN1' : value = 'DER' try : return getattr ( Encoding , value ) except AttributeError : raise ValueErr...
def stats ( self , symbol ) : """curl https : / / api . bitfinex . com / v1 / stats / btcusd { " period " : 1 , " volume " : " 7410.27250155 " } , { " period " : 7 , " volume " : " 52251.37118006 " } , { " period " : 30 , " volume " : " 464505.07753251 " }"""
data = self . _get ( self . url_for ( PATH_STATS , ( symbol ) ) ) for period in data : for key , value in period . items ( ) : if key == 'period' : new_value = int ( value ) elif key == 'volume' : new_value = float ( value ) period [ key ] = new_value return data