signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _base_repr_ ( self , html = False , show_name = True , ** kwargs ) :
"""Override the method in the astropy . Table class
to avoid displaying the description , and the format
of the columns""" | table_id = 'table{id}' . format ( id = id ( self ) )
data_lines , outs = self . formatter . _pformat_table ( self , tableid = table_id , html = html , max_width = ( - 1 if html else None ) , show_name = show_name , show_unit = None , show_dtype = False )
out = '\n' . join ( data_lines )
# if astropy . table . six . PY2... |
def tocimxmlstr ( self , indent = None , ignore_path = False ) :
"""Return the CIM - XML representation of this CIM instance ,
as a : term : ` unicode string ` .
* New in pywbem 0.9 . *
For the returned CIM - XML representation , see
: meth : ` ~ pywbem . CIMInstance . tocimxml ` .
Parameters :
indent (... | xml_elem = self . tocimxml ( ignore_path )
return tocimxmlstr ( xml_elem , indent ) |
def ModuleHelp ( self , module ) :
"""Describe the key flags of a module .
Args :
module : A module object or a module name ( a string ) .
Returns :
string describing the key flags of a module .""" | helplist = [ ]
self . __RenderOurModuleKeyFlags ( module , helplist )
return '\n' . join ( helplist ) |
def distance_between ( self , string , start , end ) :
"""Returns number of lines between start and end""" | count = 0
started = False
for line in string . split ( "\n" ) :
if self . scan_line ( line , start ) and not started :
started = True
if self . scan_line ( line , end ) :
return count
if started :
count += 1
return count |
def find ( self , header , list_type = None ) :
"""Find the first chunk with specified header and optional list type .""" | for chunk in self :
if chunk . header == header and ( list_type is None or ( header in list_headers and chunk . type == list_type ) ) :
return chunk
elif chunk . header in list_headers :
try :
result = chunk . find ( header , list_type )
return result
except chunk... |
def get_owned_subscriptions ( self , server_id ) :
"""Return the indication subscriptions in a WBEM server owned by this
subscription manager .
This function accesses only the local list of owned subscriptions ; it
does not contact the WBEM server . The local list of owned subscriptions
is discovered from t... | # Validate server _ id
self . _get_server ( server_id )
return list ( self . _owned_subscriptions [ server_id ] ) |
def p_InUseTraitDef ( p ) :
'''InUseTraitDef : Varible INSTEADOF NsContentName Terminator
| Varible AS AccessModifier Terminator
| Varible AS AccessModifier NsContentName Terminator''' | if p [ 2 ] == 'insteadof' :
p [ 0 ] = InUseTraitDef ( p [ 1 ] , p [ 2 ] , None , p [ 3 ] , p [ 4 ] )
elif len ( p ) <= 5 :
p [ 0 ] = InUseTraitDef ( p [ 1 ] , p [ 2 ] , p [ 3 ] , None , p [ 4 ] )
else :
p [ 0 ] = InUseTraitDef ( p [ 1 ] , p [ 2 ] , p [ 3 ] , p [ 4 ] , p [ 5 ] ) |
def _orbitNumberBreaks ( self ) :
"""Determine where orbital breaks in a dataset with orbit numbers occur .
Looks for changes in unique values .""" | if self . orbit_index is None :
raise ValueError ( 'Orbit properties must be defined at ' + 'pysat.Instrument object instantiation.' + 'See Instrument docs.' )
else :
try :
self . sat [ self . orbit_index ]
except ValueError :
raise ValueError ( 'Provided orbit index does not appear to ' + '... |
def acceleration ( self ) :
"""Return the acceleration in G ' s
: returns : Acceleration for every axis as a tuple
: Example :
> > > sensor = MPU6050I2C ( gw )
> > > sensor . wakeup ( )
> > > sensor . acceleration ( )
(0.6279296875 , 0.87890625 , 1.1298828125)""" | if not self . awake :
raise Exception ( "MPU6050 is in sleep mode, use wakeup()" )
raw = self . i2c_read_register ( 0x3B , 6 )
x , y , z = struct . unpack ( '>HHH' , raw )
scales = { self . RANGE_ACCEL_2G : 16384 , self . RANGE_ACCEL_4G : 8192 , self . RANGE_ACCEL_8G : 4096 , self . RANGE_ACCEL_16G : 2048 }
scale =... |
def preview ( src_path ) :
'''Generates a preview of src _ path in the requested format .
: returns : A list of preview paths , one for each page .''' | previews = [ ]
if sketch . is_sketchfile ( src_path ) :
previews = sketch . preview ( src_path )
if not previews :
previews = quicklook . preview ( src_path )
previews = [ safely_decode ( preview ) for preview in previews ]
return previews |
def filter ( self , result ) :
"""Filter the specified result based on query criteria .
@ param result : A potential result .
@ type result : L { sxbase . SchemaObject }
@ return : True if result should be excluded .
@ rtype : boolean""" | if result is None :
return True
reject = result in self . history
if reject :
log . debug ( 'result %s, rejected by\n%s' , Repr ( result ) , self )
return reject |
def register_channel_post_handler ( self , callback , * custom_filters , commands = None , regexp = None , content_types = None , state = None , run_task = None , ** kwargs ) :
"""Register handler for channel post
: param callback :
: param commands : list of commands
: param regexp : REGEXP
: param content... | filters_set = self . filters_factory . resolve ( self . channel_post_handlers , * custom_filters , commands = commands , regexp = regexp , content_types = content_types , state = state , ** kwargs )
self . channel_post_handlers . register ( self . _wrap_async_task ( callback , run_task ) , filters_set ) |
def info ( self ) :
"""return info about server as dict object""" | proc_info = { "name" : self . name , "params" : self . cfg , "alive" : self . is_alive , "optfile" : self . config_path }
if self . is_alive :
proc_info [ 'pid' ] = self . proc . pid
logger . debug ( "proc_info: {proc_info}" . format ( ** locals ( ) ) )
mongodb_uri = ''
server_info = { }
status_info = { }
if self .... |
def cli ( env , account_id , content_url ) :
"""Purge cached files from all edge nodes .
Examples :
slcli cdn purge 97794 http : / / example . com / cdn / file . txt
slcli cdn purge 97794 http : / / example . com / cdn / file . txt https : / / dal01 . example . softlayer . net / image . png""" | manager = SoftLayer . CDNManager ( env . client )
content_list = manager . purge_content ( account_id , content_url )
table = formatting . Table ( [ 'url' , 'status' ] )
for content in content_list :
table . add_row ( [ content [ 'url' ] , content [ 'statusCode' ] ] )
env . fout ( table ) |
def OnImport ( self , event ) :
"""File import event handler""" | # Get filepath from user
wildcards = get_filetypes2wildcards ( [ "csv" , "txt" ] ) . values ( )
wildcard = "|" . join ( wildcards )
message = _ ( "Choose file to import." )
style = wx . OPEN
filepath , filterindex = self . interfaces . get_filepath_findex_from_user ( wildcard , message , style )
if filepath is None :
... |
def checksum ( symbol , doc ) :
"""Checksum the passed in dictionary""" | sha = hashlib . sha1 ( )
sha . update ( symbol . encode ( 'ascii' ) )
for k in sorted ( iter ( doc . keys ( ) ) , reverse = True ) :
v = doc [ k ]
if isinstance ( v , six . binary_type ) :
sha . update ( doc [ k ] )
else :
sha . update ( str ( doc [ k ] ) . encode ( 'ascii' ) )
return Binary... |
def new ( self , user , name , description = None ) :
"""Creates a new Feed object
: param user : feed username
: param name : feed name
: param description : feed description
: return : dict""" | uri = self . client . remote + '/users/{0}/feeds' . format ( user )
data = { 'feed' : { 'name' : name , 'description' : description } }
resp = self . client . post ( uri , data )
return resp |
def access_func ( self , id_ , lineno , scope = None , default_type = None ) :
"""Since ZX BASIC allows access to undeclared functions , we must allow
and * implicitly * declare them if they are not declared already .
This function just checks if the id _ exists and returns its entry if so .
Otherwise , creat... | assert default_type is None or isinstance ( default_type , symbols . TYPEREF )
result = self . get_entry ( id_ , scope )
if result is None :
if default_type is None :
if global_ . DEFAULT_IMPLICIT_TYPE == TYPE . auto :
default_type = symbols . TYPEREF ( self . basic_types [ TYPE . auto ] , linen... |
def set_public_domain ( self , public_domain = None ) :
"""Sets the public domain flag .
: param public _ domain : the public domain status
: type public _ domain : ` ` boolean ` `
: raise : ` ` NoAccess ` ` - - ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` `
* compliance : mandatory - - This method must ... | if public_domain is None :
raise NullArgument ( )
metadata = Metadata ( ** settings . METADATA [ 'public_domain' ] )
if metadata . is_read_only ( ) :
raise NoAccess ( )
if self . _is_valid_input ( public_domain , metadata , array = False ) :
self . _my_map [ 'publicDomain' ] = public_domain
else :
raise... |
def add_color ( self , name , model , description ) :
r"""Add a color that can be used throughout the document .
Args
name : str
Name to set for the color
model : str
The color model to use when defining the color
description : str
The values to use to define the color""" | if self . color is False :
self . packages . append ( Package ( "color" ) )
self . color = True
self . preamble . append ( Command ( "definecolor" , arguments = [ name , model , description ] ) ) |
def to_table ( self ) :
"""Convert an ArrayWrapper with shape ( D1 , . . . , DN ) and attributes
T1 , . . . , TN which are list of tags of lenghts D1 , . . . DN into
a table with rows ( tag1 , . . . tagN , value ) of maximum length
D1 * . . . * DN . Zero values are discarded .
> > > from pprint import pprin... | shape = self . shape
# the tagnames are bytestrings so they must be decoded
tagnames = decode_array ( self . tagnames )
if len ( shape ) == len ( tagnames ) :
return [ tagnames + [ 'value' ] ] + self . _to_table ( )
elif len ( shape ) == len ( tagnames ) + 1 : # there is an extra field
tbl = [ tagnames + [ self... |
def get_hit_count_from_obj_variable ( context , obj_variable , tag_name ) :
"""Helper function to return a HitCount for a given template object variable .
Raises TemplateSyntaxError if the passed object variable cannot be parsed .""" | error_to_raise = template . TemplateSyntaxError ( "'%(a)s' requires a valid individual model variable " "in the form of '%(a)s for [model_obj]'.\n" "Got: %(b)s" % { 'a' : tag_name , 'b' : obj_variable } )
try :
obj = obj_variable . resolve ( context )
except template . VariableDoesNotExist :
raise error_to_rais... |
def print_javascript_error ( self ) :
"""Print to the info log the gathered javascript error
If no error is found then nothing is printed""" | errors = self . get_javascript_error ( return_type = 'list' )
if errors :
self . info_log ( "Javascript error:" )
for error in errors :
self . info_log ( error ) |
async def close ( self , code : int = 1000 , message : bytes = b'' ) -> None :
"""Close the websocket , sending the specified code and message .""" | if isinstance ( message , str ) :
message = message . encode ( 'utf-8' )
try :
await self . _send_frame ( PACK_CLOSE_CODE ( code ) + message , opcode = WSMsgType . CLOSE )
finally :
self . _closing = True |
def __logfile_error ( self , e ) :
"""Shows an error message to standard error
if the log file can ' t be written to .
Used internally .
@ type e : Exception
@ param e : Exception raised when trying to write to the log file .""" | from sys import stderr
msg = "Warning, error writing log file %s: %s\n"
msg = msg % ( self . logfile , str ( e ) )
stderr . write ( DebugLog . log_text ( msg ) )
self . logfile = None
self . fd = None |
def current_user ( self ) -> Any :
"""The authenticated user for this request .
This is set in one of two ways :
* A subclass may override ` get _ current _ user ( ) ` , which will be called
automatically the first time ` ` self . current _ user ` ` is accessed .
` get _ current _ user ( ) ` will only be ca... | if not hasattr ( self , "_current_user" ) :
self . _current_user = self . get_current_user ( )
return self . _current_user |
def get_context_data ( self , ** kwargs ) :
"""This add in the context of strain _ list _ alive ( which filters for all alive animals ) and cages which filters for the number of current cages .""" | context = super ( StrainList , self ) . get_context_data ( ** kwargs )
context [ 'strain_list_alive' ] = Strain . objects . filter ( animal__Alive = True ) . annotate ( alive = Count ( 'animal' ) )
context [ 'cages' ] = Animal . objects . filter ( Alive = True ) . values ( "Cage" )
return context |
def add_file_group ( self , fileGrp ) :
"""Add a new ` ` mets : fileGrp ` ` .
Arguments :
fileGrp ( string ) : ` ` USE ` ` attribute of the new filegroup .""" | el_fileSec = self . _tree . getroot ( ) . find ( 'mets:fileSec' , NS )
if el_fileSec is None :
el_fileSec = ET . SubElement ( self . _tree . getroot ( ) , TAG_METS_FILESEC )
el_fileGrp = el_fileSec . find ( 'mets:fileGrp[@USE="%s"]' % fileGrp , NS )
if el_fileGrp is None :
el_fileGrp = ET . SubElement ( el_file... |
def watch ( path : Union [ Path , str ] , ** kwargs ) :
"""Watch a directory and yield a set of changes whenever files change in that directory or its subdirectories .""" | loop = asyncio . new_event_loop ( )
try :
_awatch = awatch ( path , loop = loop , ** kwargs )
while True :
try :
yield loop . run_until_complete ( _awatch . __anext__ ( ) )
except StopAsyncIteration :
break
except KeyboardInterrupt :
logger . debug ( 'KeyboardInterrup... |
def __vector_to_string ( self , vector ) :
"""Returns string representation of vector .""" | return numpy . array_str ( numpy . round ( unitvec ( vector ) , decimals = 3 ) ) |
def miscellaneous_menu ( self , value ) :
"""Setter for * * self . _ _ miscellaneous _ menu * * attribute .
: param value : Attribute value .
: type value : QMenu""" | if value is not None :
assert type ( value ) is QMenu , "'{0}' attribute: '{1}' type is not 'QMenu'!" . format ( "miscellaneous_menu" , value )
self . __miscellaneous_menu = value |
def _count_righthand_zero_bits ( number , bits ) :
"""Count the number of zero bits on the right hand side .
Args :
number : an integer .
bits : maximum number of bits to count .
Returns :
The number of zero bits on the right hand side of the number .""" | if number == 0 :
return bits
for i in range ( bits ) :
if ( number >> i ) & 1 :
return i
# All bits of interest were zero , even if there are more in the number
return bits |
def build_mp ( b , stage , source_name , force ) :
"""Ingest a source , using only arguments that can be pickled , for multiprocessing access""" | source = b . source ( source_name )
with b . progress . start ( 'build_mp' , stage , message = "MP build" , source = source ) as ps :
ps . add ( message = 'Running source {}' . format ( source . name ) , source = source , state = 'running' )
r = b . build_source ( stage , source , ps , force )
return r |
def handle_log_entry ( self , m ) :
'''handling incoming log entry''' | if m . time_utc == 0 :
tstring = ''
else :
tstring = time . ctime ( m . time_utc )
self . entries [ m . id ] = m
print ( "Log %u numLogs %u lastLog %u size %u %s" % ( m . id , m . num_logs , m . last_log_num , m . size , tstring ) ) |
def put_secret ( self , secure_data_path , secret , merge = True ) :
"""Write secret ( s ) to a secure data path provided a dictionary of key / values
Keyword arguments :
secure _ data _ path - - full path in the safety deposit box that contains the key
secret - - A dictionary containing key / values to be wr... | # json encode the input . Cerberus is sensitive to double vs single quotes .
# an added bonus is that json encoding transforms python2 unicode strings
# into a compatible format .
data = json . encoder . JSONEncoder ( ) . encode ( secret )
if merge :
data = self . secret_merge ( secure_data_path , secret )
secret_r... |
def prompt ( message = '' , ** kwargs ) :
"""Get input from the user and return it .
This is a wrapper around a lot of ` ` prompt _ toolkit ` ` functionality and can
be a replacement for ` raw _ input ` . ( or GNU readline . )
If you want to keep your history across several calls , create one
: class : ` ~ ... | patch_stdout = kwargs . pop ( 'patch_stdout' , False )
return_asyncio_coroutine = kwargs . pop ( 'return_asyncio_coroutine' , False )
true_color = kwargs . pop ( 'true_color' , False )
refresh_interval = kwargs . pop ( 'refresh_interval' , 0 )
eventloop = kwargs . pop ( 'eventloop' , None )
application = create_prompt_... |
def del_node ( self , name , index = None ) :
"""Delete a node from the graph .
Given a node ' s name all node ( s ) with that same name
will be deleted if ' index ' is not specified or set
to None .
If there are several nodes with that same name and
' index ' is given , only the node in that position
w... | if isinstance ( name , Node ) :
name = name . get_name ( )
if name in self . obj_dict [ 'nodes' ] :
if ( index is not None and index < len ( self . obj_dict [ 'nodes' ] [ name ] ) ) :
del self . obj_dict [ 'nodes' ] [ name ] [ index ]
return True
else :
del self . obj_dict [ 'nodes' ... |
def HowDoI ( ) :
'''Make and show a window ( PySimpleGUI form ) that takes user input and sends to the HowDoI web oracle
Excellent example of 2 GUI concepts
1 . Output Element that will show text in a scrolled window
2 . Non - Window - Closing Buttons - These buttons will cause the form to return with the for... | # - - - - - Make a new Window - - - - - #
sg . ChangeLookAndFeel ( 'GreenTan' )
# give our form a spiffy set of colors
layout = [ [ sg . Text ( 'Ask and your answer will appear here....' , size = ( 40 , 1 ) ) ] , [ sg . Output ( size = ( 127 , 30 ) , font = ( 'Helvetica 10' ) ) ] , [ sg . Spin ( values = ( 1 , 2 , 3 , ... |
def get_variable_for_feature ( self , feature_key , variable_key ) :
"""Get the variable with the given variable key for the given feature .
Args :
feature _ key : The key of the feature for which we are getting the variable .
variable _ key : The key of the variable we are getting .
Returns :
Variable wi... | feature = self . feature_key_map . get ( feature_key )
if not feature :
self . logger . error ( 'Feature with key "%s" not found in the datafile.' % feature_key )
return None
if variable_key not in feature . variables :
self . logger . error ( 'Variable with key "%s" not found in the datafile.' % variable_k... |
def self_aware ( fn ) :
'''decorating a function with this allows it to
refer to itself as ' self ' inside the function
body .''' | if isgeneratorfunction ( fn ) :
@ wraps ( fn )
def wrapper ( * a , ** k ) :
generator = fn ( * a , ** k )
if hasattr ( generator , 'gi_frame' ) and hasattr ( generator . gi_frame , 'f_builtins' ) and hasattr ( generator . gi_frame . f_builtins , '__setitem__' ) :
generator . gi_frame... |
def _get_object_from_python_path ( python_path ) :
"""Method that will fetch a Marshmallow schema from a path to it .
Args :
python _ path ( str ) : The string path to the Marshmallow schema .
Returns :
marshmallow . Schema : The schema matching the provided path .
Raises :
TypeError : This is raised if... | # Dissect the path
python_path = python_path . split ( '.' )
module_path = python_path [ : - 1 ]
object_class = python_path [ - 1 ]
if isinstance ( module_path , list ) :
module_path = '.' . join ( module_path )
# Grab the object
module = import_module ( module_path )
schema = getattr ( module , object_class )
if i... |
def fromGeoCoordinateString ( self , sr , strings , conversionType , conversionMode = None ) :
"""The fromGeoCoordinateString operation is performed on a geometry
service resource . The operation converts an array of well - known
strings into xy - coordinates based on the conversion type and
spatial reference... | url = self . _url + "/fromGeoCoordinateString"
params = { "f" : "json" , "sr" : sr , "strings" : strings , "conversionType" : conversionType }
if not conversionMode is None :
params [ 'conversionMode' ] = conversionMode
return self . _post ( url = url , param_dict = params , securityHandler = self . _securityHandle... |
def _collect_fields ( self ) :
'''Collects all the attributes that are instance of
: class : ` incoming . datatypes . Types ` . These attributes are used for
defining rules of validation for every field / key in the incoming JSON
payload .
: returns : a tuple of attribute names from an instance of a sub - c... | fields = [ ]
for prop in dir ( self ) :
if isinstance ( getattr ( self , prop ) , Types ) :
fields . append ( prop )
if not len ( fields ) :
raise Exception ( 'No keys/fields defined in the validator class.' )
return tuple ( fields ) |
def _create_repo ( self , args ) :
'''Scan a directory and create an SPM - METADATA file which describes
all of the SPM files in that directory .''' | if len ( args ) < 2 :
raise SPMInvocationError ( 'A path to a directory must be specified' )
if args [ 1 ] == '.' :
repo_path = os . getcwdu ( )
else :
repo_path = args [ 1 ]
old_files = [ ]
repo_metadata = { }
for ( dirpath , dirnames , filenames ) in salt . utils . path . os_walk ( repo_path ) :
for s... |
def associar_assinatura ( self , sequencia_cnpj , assinatura_ac ) :
"""Sobrepõe : meth : ` ~ satcfe . base . FuncoesSAT . associar _ assinatura ` .
: return : Uma resposta SAT padrão .
: rtype : satcfe . resposta . padrao . RespostaSAT""" | retorno = super ( ClienteSATLocal , self ) . associar_assinatura ( sequencia_cnpj , assinatura_ac )
# ( ! ) resposta baseada na redação com efeitos até 31-12-2016
return RespostaSAT . associar_assinatura ( retorno ) |
def if_relationship ( parser , token ) :
"""Determine if a certain type of relationship exists between two users .
The ` ` status ` ` parameter must be a slug matching either the from _ slug ,
to _ slug or symmetrical _ slug of a RelationshipStatus .
Example : :
{ % if _ relationship from _ user to _ user "... | bits = list ( token . split_contents ( ) )
if len ( bits ) != 4 :
raise TemplateSyntaxError ( "%r takes 3 arguments:\n%s" % ( bits [ 0 ] , if_relationship . __doc__ ) )
end_tag = 'end' + bits [ 0 ]
nodelist_true = parser . parse ( ( 'else' , end_tag ) )
token = parser . next_token ( )
if token . contents == 'else' ... |
def center_at ( self , x , y ) :
"""Center the menu at x , y""" | self . x = x - ( self . width / 2 )
self . y = y - ( self . height / 2 ) |
def _set_vlanoper ( self , v , load = False ) :
"""Setter method for vlanoper , mapped from YANG variable / interface / ethernet / switchport / trunk / allowed / vlanoper ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ vlanoper is considered as a private
... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = vlanoper . vlanoper , is_container = 'container' , presence = False , yang_name = "vlanoper" , rest_name = "vlanoper" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = Tr... |
def load_optimizer_states ( self , fname ) :
"""Loads optimizer ( updater ) state from a file .
Parameters
fname : str
Path to input states file .""" | assert self . optimizer_initialized
if self . _update_on_kvstore :
self . _kvstore . load_optimizer_states ( fname )
else :
self . _updater . set_states ( open ( fname , 'rb' ) . read ( ) ) |
def inherit_set ( base , namespace , attr_name , inherit = lambda i : True ) :
"""Perform inheritance of sets . Returns a list of items that
were inherited , for post - processing .
: param base : The base class being considered ; see
` ` iter _ bases ( ) ` ` .
: param namespace : The dictionary of the new ... | items = [ ]
# Get the sets to compare
base_set = getattr ( base , attr_name , set ( ) )
new_set = namespace . setdefault ( attr_name , set ( ) )
for item in base_set : # Skip items that have been overridden or that we
# shouldn ' t inherit
if item in new_set or ( inherit and not inherit ( item ) ) :
continu... |
def main ( ) :
"""NAME
reorder _ samples . py
DESCRIPTION
takes specimen file and reorders sample file with selected orientation methods placed first
SYNTAX
reorder _ samples . py [ command line options ]
OPTIONS
- h prints help message and quits
- fsp : specimen input pmag _ specimens format file ,... | infile = 'pmag_specimens.txt'
sampfile = "er_samples.txt"
outfile = "er_samples.txt"
# get command line stuff
if "-h" in sys . argv :
print ( main . __doc__ )
sys . exit ( )
if '-fsp' in sys . argv :
ind = sys . argv . index ( "-fsp" )
infile = sys . argv [ ind + 1 ]
if '-fsm' in sys . argv :
ind = ... |
def import_controller ( string ) :
"""Imports the requested controller . Controllers are specified in a
URI - like manner ; the scheme is looked up using the entry point
group " appathy . loader " . Appathy supports the " call : " and " egg : "
schemes by default .""" | # Split out the scheme and the controller descriptor
scheme , sep , controller = string . partition ( ':' )
if sep != ':' :
raise ImportError ( "No loader scheme specified by %r" % string )
# Look up a loader for that scheme
for ep in pkg_resources . iter_entry_points ( 'appathy.loader' , scheme ) :
try :
... |
def fetchone ( self ) :
"""Fetch next row""" | self . _check_executed ( )
row = yield self . read_next ( )
if row is None :
raise gen . Return ( None )
self . rownumber += 1
raise gen . Return ( row ) |
def datadir ( * subdirs ) :
"""Get a path within the CASA data directory .
subdirs
Extra elements to append to the returned path .
This function locates the directory where CASA resource data files ( tables
of time offsets , calibrator models , etc . ) are stored . If called with no
arguments , it simply ... | import os . path
data = None
if 'CASAPATH' in os . environ :
data = os . path . join ( os . environ [ 'CASAPATH' ] . split ( ) [ 0 ] , 'data' )
if data is None : # The Conda CASA directory layout :
try :
import casadef
except ImportError :
pass
else :
data = os . path . join ( os... |
def read ( self , offset , length ) :
"""Read a string of bytes from the specified ` offset ` in bytes ,
relative to the base physical address of the MMIO region .
Args :
offset ( int , long ) : offset from base physical address , in bytes .
length ( int ) : number of bytes to read .
Returns :
bytes : b... | if not isinstance ( offset , ( int , long ) ) :
raise TypeError ( "Invalid offset type, should be integer." )
offset = self . _adjust_offset ( offset )
self . _validate_offset ( offset , length )
return bytes ( self . mapping [ offset : offset + length ] ) |
def _utf8_list_to_ascii_tuple ( utf8_list ) :
"""Convert unicode strings in a list of lists to ascii in a list of tuples .
: param utf8 _ list : A nested list of unicode strings .
: type utf8 _ list : list""" | for n , utf8 in enumerate ( utf8_list ) :
utf8_list [ n ] [ 0 ] = str ( utf8 [ 0 ] )
utf8_list [ n ] [ 1 ] = str ( utf8 [ 1 ] )
utf8_list [ n ] = tuple ( utf8 ) |
def restore ( self , time = None ) :
"""Undeletes the object . Returns True if undeleted , False if it was already not deleted""" | if self . deleted :
time = time if time else self . deleted_at
if time == self . deleted_at :
self . deleted = False
self . save ( )
return True
else :
return False
return False |
def grade ( adjective , suffix = COMPARATIVE ) :
"""Returns the comparative or superlative form of the given ( inflected ) adjective .""" | b = predicative ( adjective )
# groß = > großt , schön = > schönst
if suffix == SUPERLATIVE and b . endswith ( ( "s" , u"ß" ) ) :
suffix = suffix [ 1 : ]
# große = > großere , schönes = > schöneres
return adjective [ : len ( b ) ] + suffix + adjective [ len ( b ) : ] |
def _TypecheckFunction ( function , parent_type_check_dict , stack_location , self_name ) :
"""Decorator function to collect and execute type checks .""" | type_check_dict = _CollectTypeChecks ( function , parent_type_check_dict , stack_location + 1 , self_name )
if not type_check_dict :
return function
def TypecheckWrapper ( * args , ** kwargs ) :
arg_dict = _CollectArguments ( function , args , kwargs )
errors = _ValidateArguments ( arg_dict , type_check_dic... |
def run ( self ) :
'''Execute the salt call !''' | self . parse_args ( )
if self . options . file_root : # check if the argument is pointing to a file on disk
file_root = os . path . abspath ( self . options . file_root )
self . config [ 'file_roots' ] = { 'base' : _expand_glob_path ( [ file_root ] ) }
if self . options . pillar_root : # check if the argument i... |
def get_yaml_schema ( self ) :
"""GetYamlSchema .
[ Preview API ]
: rtype : object""" | response = self . _send ( http_method = 'GET' , location_id = '1f9990b9-1dba-441f-9c2e-6485888c42b6' , version = '5.1-preview.1' )
return self . _deserialize ( 'object' , response ) |
def update_kwargs ( self , request , ** kwargs ) :
"""Adds variables to the context that are expected by the
base cms templates .
* * * navigation * * - The side navigation for this bundle and user .
* * * dashboard * * - The list of dashboard links for this user .
* * * object _ header * * - If no ' object... | kwargs = super ( CMSRender , self ) . update_kwargs ( request , ** kwargs )
# Check if we need to to include a separate object
# bundle for the title
bundle = kwargs . get ( 'bundle' )
url_kwargs = kwargs . get ( 'url_params' )
view = None
if bundle :
view , name = bundle . get_object_header_view ( request , url_kw... |
def get_downsample_pct ( in_bam , target_counts , data ) :
"""Retrieve percentage of file to downsample to get to target counts .
Avoids minimal downsample which is not especially useful for
improving QC times ; 90 & or more of reads .""" | total = sum ( x . aligned for x in idxstats ( in_bam , data ) )
with pysam . Samfile ( in_bam , "rb" ) as work_bam :
n_rgs = max ( 1 , len ( work_bam . header . get ( "RG" , [ ] ) ) )
rg_target = n_rgs * target_counts
if total > rg_target :
pct = float ( rg_target ) / float ( total )
if pct < 0.9 :
... |
def parse_error ( self , tup_tree ) :
"""Parse the tuple for an ERROR element :
< ! ELEMENT ERROR ( INSTANCE * ) >
< ! ATTLIST ERROR
CODE CDATA # REQUIRED
DESCRIPTION CDATA # IMPLIED >""" | self . check_node ( tup_tree , 'ERROR' , ( 'CODE' , ) , ( 'DESCRIPTION' , ) , ( 'INSTANCE' , ) )
# self . list _ of _ various ( ) has the same effect as self . list _ of _ same ( )
# when used with a single allowed child element , but is a little
# faster .
instance_list = self . list_of_various ( tup_tree , ( 'INSTANC... |
def cache_path ( runas = None , env = None ) :
'''List path of the NPM cache directory .
runas
The user to run NPM with
env
Environment variables to set when invoking npm . Uses the same ` ` env ` `
format as the : py : func : ` cmd . run < salt . modules . cmdmod . run > ` execution
function .
CLI Ex... | env = env or { }
if runas :
uid = salt . utils . user . get_uid ( runas )
if uid :
env . update ( { 'SUDO_UID' : uid , 'SUDO_USER' : '' } )
cmd = 'npm config get cache'
result = __salt__ [ 'cmd.run_all' ] ( cmd , cwd = None , runas = runas , env = env , python_shell = True , ignore_retcode = True )
retu... |
def open ( self , options ) :
"""Open and import the refrenced schema .
@ param options : An options dictionary .
@ type options : L { options . Options }
@ return : The referenced schema .
@ rtype : L { Schema }""" | if self . opened :
return
self . opened = True
log . debug ( '%s, importing ns="%s", location="%s"' , self . id , self . ns [ 1 ] , self . location )
result = self . locate ( )
if result is None :
if self . location is None :
log . debug ( 'imported schema (%s) not-found' , self . ns [ 1 ] )
else :
... |
def run ( self ) :
"""Inserts data generated by rows ( ) into target table .
If the target table doesn ' t exist , self . create _ table will be called to attempt to create the table .
Normally you don ' t want to override this .""" | if not ( self . table and self . columns ) :
raise Exception ( "table and columns need to be specified" )
connection = self . output ( ) . connect ( )
# attempt to copy the data into mysql
# if it fails because the target table doesn ' t exist
# try to create it by running self . create _ table
for attempt in range... |
def name_parser ( name , ** kwargs ) :
'''Parse taxon names using the GBIF name parser
: param name : [ str ] A character vector of scientific names . ( required )
reference : http : / / www . gbif . org / developer / species # parser
Usage : :
from pygbif import species
species . name _ parser ( ' x Agro... | url = gbif_baseurl + 'parser/name'
if name . __class__ == str :
name = [ name ]
return gbif_POST ( url , name , ** kwargs ) |
def size ( self ) :
"""Total number of coefficients in the ScalarCoefs structure .
Example : :
> > > sz = c . size
> > > N = c . nmax + 1
> > > L = N + c . mmax * ( 2 * N - c . mmax - 1 ) ;
> > > assert sz = = L""" | N = self . nmax + 1 ;
NC = N + self . mmax * ( 2 * N - self . mmax - 1 ) ;
assert NC == len ( self . _vec )
return NC |
def make_url ( contents , domain = DEFAULT_DOMAIN , force_gist = False , size_for_gist = MAX_URL_LEN ) :
"""Returns the URL to open given the domain and contents .
If the file contents are large , an anonymous gist will be created .
Parameters
contents
* string - assumed to be GeoJSON
* an object that imp... | contents = make_geojson ( contents )
if len ( contents ) <= size_for_gist and not force_gist :
url = data_url ( contents , domain )
else :
gist = _make_gist ( contents )
url = gist_url ( gist . id , domain )
return url |
def _format_num ( self , value ) :
"""Return the number value for value , given this field ' s ` num _ type ` .""" | # ( value is True or value is False ) is ~ 5x faster than isinstance ( value , bool )
if value is True or value is False :
raise TypeError ( 'value must be a Number, not a boolean.' )
return self . num_type ( value ) |
def parse_arguments ( args = None ) :
"""Parse the program arguments .
: return : argparse . Namespace object with the parsed arguments""" | parser = get_argument_parser ( )
# Autocomplete arguments
autocomplete ( parser )
ns = parser . parse_args ( args = args )
return ArgumentSettings ( program = ArgumentProgramSettings ( log = ArgumentLogSettings ( path = None , level = ns . loglevel , ) , settings = ArgumentSettingsSettings ( path = ns . settings_path ,... |
async def sqsStats ( self , * args , ** kwargs ) :
"""Statistics on the sqs queues
This method is only for debugging the ec2 - manager
This method is ` ` experimental ` `""" | return await self . _makeApiCall ( self . funcinfo [ "sqsStats" ] , * args , ** kwargs ) |
def scores ( self , result , add_new_line = True ) :
"""Prints out the scores in a pretty format""" | if result . goalsHomeTeam > result . goalsAwayTeam :
homeColor , awayColor = ( self . colors . WIN , self . colors . LOSE )
elif result . goalsHomeTeam < result . goalsAwayTeam :
homeColor , awayColor = ( self . colors . LOSE , self . colors . WIN )
else :
homeColor = awayColor = self . colors . TIE
click .... |
def read_file ( fpath ) :
"""Reads a file within package directories .""" | with io . open ( os . path . join ( PATH_BASE , fpath ) ) as f :
return f . read ( ) |
def reinstantiate_endpoints ( self , endpoint = None ) :
"""This will re - instantiate the endpoints with the connection this time
: param endpoint : Endpoint object to instantiate the sub endpoint in .
: return : None""" | endpoint = endpoint or self
for k , v in endpoint . __class__ . __dict__ . items ( ) :
if isinstance ( v , Endpoint ) :
setattr ( endpoint , k , v . __class__ ( self ) )
elif inspect . isclass ( v ) and issubclass ( v , Endpoint ) :
setattr ( endpoint , k , v ( self ) ) |
def get_git_remote_url ( path = '.' , remote = 'origin' ) :
"""Get git remote url
: param path : path to repo
: param remote :
: return : remote url or exception""" | return dulwich . repo . Repo . discover ( path ) . get_config ( ) . get ( ( b'remote' , remote . encode ( 'utf-8' ) ) , b'url' ) . decode ( 'utf-8' ) |
def resolve_session ( self , subject_context ) :
"""This method attempts to resolve any associated session based on the
context and returns a context that represents this resolved Session to
ensure it may be referenced , if needed , by the invoked do _ create _ subject
that performs actual ` ` Subject ` ` con... | if ( subject_context . resolve_session ( ) is not None ) :
msg = ( "Context already contains a session. Returning." )
logger . debug ( msg )
return subject_context
try : # Context couldn ' t resolve it directly , let ' s see if we can
# since we have direct access to the session manager :
session = sel... |
def _getHeaders ( self , updateParams = None ) :
"""create headers list for flask wrapper""" | if not updateParams :
updateParams = { }
policies = self . defaultPolicies
if len ( updateParams ) > 0 :
for k , v in updateParams . items ( ) :
k = k . replace ( '-' , '_' )
c = globals ( ) [ k ] ( v )
try :
policies [ k ] = c . update_policy ( self . defaultPolicies [ k ] )... |
def create_exception_by_error_code ( errorCode , detailCode = '0' , description = '' , traceInformation = None , identifier = None , nodeId = None , ) :
"""Create a DataONE Exception object by errorCode .
See Also : For args , see : ` ` DataONEException ( ) ` `""" | try :
dataone_exception = ERROR_CODE_TO_EXCEPTION_DICT [ errorCode ]
except LookupError :
dataone_exception = ServiceFailure
return dataone_exception ( detailCode , description , traceInformation , identifier , nodeId ) |
def _workaround_no_stage_specific_variables ( project ) :
"""Make Stage - specific variables global ( move them to Project ) .""" | for ( name , var ) in project . stage . variables . items ( ) :
yield "variable %s" % name
for ( name , _list ) in project . stage . lists . items ( ) :
yield "list %s" % name
project . variables . update ( project . stage . variables )
project . lists . update ( project . stage . lists )
project . stage . vari... |
def as_rainbow ( self , offset = 35 , style = None , rgb_mode = False ) :
"""Wrap each frame in a Colr object , using ` Colr . rainbow ` .""" | return self . _as_rainbow ( ( 'wrapper' , ) , offset = offset , style = style , rgb_mode = rgb_mode , ) |
def get_share ( self , share_id ) :
"""Returns share information about known share
: param share _ id : id of the share to be checked
: returns : instance of ShareInfo class
: raises : ResponseError in case an HTTP error status was returned""" | if ( share_id is None ) or not ( isinstance ( share_id , int ) ) :
return None
res = self . _make_ocs_request ( 'GET' , self . OCS_SERVICE_SHARE , 'shares/' + str ( share_id ) )
if res . status_code == 200 :
tree = ET . fromstring ( res . content )
self . _check_ocs_status ( tree )
return self . _get_sh... |
def _pull ( self ) :
'''Helper function to pull from remote''' | pull = self . m ( 'pulling remote changes' , cmdd = dict ( cmd = 'git pull --tags' , cwd = self . local ) , critical = False )
if 'CONFLICT' in pull . get ( 'out' ) :
self . m ( 'Congratulations! You have merge conflicts in the repository!' , state = True , more = pull )
return pull |
def routers_updated ( self , context , routers ) :
"""Deal with routers modification and creation RPC message .""" | LOG . debug ( 'Got routers updated notification :%s' , routers )
if routers : # This is needed for backward compatibility
if isinstance ( routers [ 0 ] , dict ) :
routers = [ router [ 'id' ] for router in routers ]
self . _update_updated_routers_cache ( routers ) |
def parse_compound_file ( path , format ) :
"""Open and parse reaction file based on file extension or given format
Path can be given as a string or a context .""" | context = FilePathContext ( path )
# YAML files do not need to explicitly specify format
format = resolve_format ( format , context . filepath )
if format == 'yaml' :
logger . debug ( 'Parsing compound file {} as YAML' . format ( context . filepath ) )
with context . open ( 'r' ) as f :
for compound in ... |
def run_migrations_online ( ) :
"""Run migrations in ' online ' mode .
In this scenario we need to create an Engine
and associate a connection with the context .""" | alembic_config = config . get_section ( config . config_ini_section )
alembic_config [ 'sqlalchemy.url' ] = os . environ [ 'DATABASE_URI' ]
connectable = engine_from_config ( alembic_config , prefix = 'sqlalchemy.' , poolclass = pool . NullPool )
with connectable . connect ( ) as connection :
context . configure ( ... |
def _start_actions ( self ) :
"""Start all the actions for the recipes""" | Global . LOGGER . info ( "starting actions" )
for recipe in Global . CONFIG_MANAGER . recipes :
Global . CONFIG_MANAGER . read_recipe ( recipe )
list ( map ( lambda section : self . _start_action_for_section ( section ) , Global . CONFIG_MANAGER . sections ) ) |
def set_value ( self , subsystem , option , value ) :
"""Write the given value for the given subsystem .
Do not include the subsystem name in the option name .
Only call this method if the given subsystem is available .""" | assert subsystem in self
util . write_file ( str ( value ) , self . per_subsystem [ subsystem ] , subsystem + '.' + option ) |
def rename ( self ) :
"""Renames media file to formatted name .
After parsing data from initial media filename and searching
for additional data to using a data service , a formatted
filename will be generated and the media file will be renamed
to the generated name and optionally relocated .""" | renamer . execute ( self . original , self . out_location )
if cfg . CONF . move_files_enabled :
LOG . debug ( 'relocated: %s' , self )
else :
LOG . debug ( 'renamed: %s' , self ) |
def presenter ( self , presenter_name ) :
""": meth : ` . WWebPresenterCollectionProto . presenter ` method implementation""" | if presenter_name in self . __presenters . keys ( ) :
return self . __presenters [ presenter_name ] |
def strip_hidden ( key_tuples , visibilities ) :
"""Filter each tuple according to visibility .
Args :
key _ tuples : A sequence of tuples of equal length ( i . e . rectangular )
visibilities : A sequence of booleans equal in length to the tuples contained in key _ tuples .
Returns :
A sequence equal in l... | result = [ ]
for key_tuple in key_tuples :
if len ( key_tuple ) != len ( visibilities ) :
raise ValueError ( "length of key tuple {} is not equal to length of visibilities {}" . format ( key_tuple , visibilities ) )
filtered_tuple = tuple ( item for item , visible in zip ( key_tuple , visibilities ) if ... |
def get_max_levels_metadata ( self ) :
"""get the metadata for max levels""" | metadata = dict ( self . _max_levels_metadata )
metadata . update ( { 'existing_cardinal_values' : self . my_osid_object_form . _my_map [ 'maxLevels' ] } )
return Metadata ( ** metadata ) |
def choosers_columns_used ( self ) :
"""Columns from the choosers table that are used for filtering .""" | return list ( tz . unique ( tz . concatv ( util . columns_in_filters ( self . choosers_predict_filters ) , util . columns_in_filters ( self . choosers_fit_filters ) ) ) ) |
def at_css ( self , css , timeout = DEFAULT_AT_TIMEOUT , ** kw ) :
"""Returns the first node matching the given CSSv3 expression or ` ` None ` `
if a timeout occurs .""" | return self . wait_for_safe ( lambda : super ( WaitMixin , self ) . at_css ( css ) , timeout = timeout , ** kw ) |
def _related_items_changed ( self , ** kwargs ) :
"""Ensure that the given related item is actually for the model
this field applies to , and pass the instance to the real
` ` related _ items _ changed ` ` handler .""" | for_model = kwargs [ "instance" ] . content_type . model_class ( )
if for_model and issubclass ( for_model , self . model ) :
instance_id = kwargs [ "instance" ] . object_pk
try :
instance = for_model . objects . get ( id = instance_id )
except self . model . DoesNotExist : # Instance itself was del... |
def _retry ( self ) :
"""Deal with unacknowledged notifications .""" | notifications_to_delete = [ ]
for notification_id in self . notifications :
if datetime . datetime . utcnow ( ) > self . notifications [ notification_id ] [ 'ts' ] + self . _wait_period :
self . _notify_receiver ( self . notifications [ notification_id ] [ 'receiver' ] , self . notifications [ notification_... |
def set_mode ( iface , mode ) :
'''List networks on a wireless interface
CLI Example :
salt minion iwtools . set _ mode wlp3s0 Managed''' | if not _valid_iface ( iface ) :
raise SaltInvocationError ( 'The interface specified is not valid' )
valid_modes = ( 'Managed' , 'Ad-Hoc' , 'Master' , 'Repeater' , 'Secondary' , 'Monitor' , 'Auto' )
if mode not in valid_modes :
raise SaltInvocationError ( 'One of the following modes must be specified: {0}' . fo... |
def bk_magenta ( cls ) :
"Make the text background color magenta ." | wAttributes = cls . _get_text_attributes ( )
wAttributes &= ~ win32 . BACKGROUND_MASK
wAttributes |= win32 . BACKGROUND_MAGENTA
cls . _set_text_attributes ( wAttributes ) |
def _transform_attrs ( cls , these , auto_attribs , kw_only ) :
"""Transform all ` _ CountingAttr ` s on a class into ` Attribute ` s .
If * these * is passed , use that and don ' t look for them on the class .
Return an ` _ Attributes ` .""" | cd = cls . __dict__
anns = _get_annotations ( cls )
if these is not None :
ca_list = [ ( name , ca ) for name , ca in iteritems ( these ) ]
if not isinstance ( these , ordered_dict ) :
ca_list . sort ( key = _counter_getter )
elif auto_attribs is True :
ca_names = { name for name , attr in cd . item... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.