signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def load ( self , source : Source ) -> None :
"""Attempts to load all resources ( i . e . , bugs , tools , and blueprints )
provided by a given source . If the given source has already been
loaded , then that resources for that source are unloaded and
reloaded .""" | logger . info ( 'loading source %s at %s' , source . name , source . location )
if source . name in self . __sources :
self . unload ( source )
bugs = [ ]
blueprints = [ ]
tools = [ ]
# find and parse all bugzoo files
glob_pattern = '{}/**/*.bugzoo.y*ml' . format ( source . location )
for fn in glob . iglob ( glob_... |
def on_receive ( self , message = None , wire = None , event_origin = None ) :
"""event handler bound to the receive event of the
link the server is wired too .
Arguments :
- message ( message . Message ) : incoming message
Keyword arguments :
- event _ origin ( connection . Link )""" | self . trigger ( "before_call" , message )
fn_name = message . data
pmsg = self . prepare_message
try :
for handler in self . handlers :
handler . incoming ( message , self )
fn = self . get_function ( fn_name , message . path )
except Exception as inst :
wire . respond ( message , ErrorMessage ( st... |
def Hooper2K ( Di , Re , name = None , K1 = None , Kinfty = None ) :
r'''Returns loss coefficient for any various fittings , depending
on the name input . Alternatively , the Hooper constants K1 , Kinfty
may be provided and used instead . Source of data is [ 1 ] _ .
Reviews of this model are favorable less fa... | if name :
if name in Hooper :
d = Hooper [ name ]
K1 , Kinfty = d [ 'K1' ] , d [ 'Kinfty' ]
else :
raise Exception ( 'Name of fitting not in list' )
elif K1 and Kinfty :
pass
else :
raise Exception ( 'Name of fitting or constants are required' )
return K1 / Re + Kinfty * ( 1. + 1... |
def parse_lheading ( self , m ) :
"""Parse setext heading .""" | level = 1 if m . group ( 2 ) == '=' else 2
self . renderer . heading ( m . group ( 1 ) , level = level ) |
def _get_alignment_lines ( self ) :
'''This function parses the Clustal Omega alignment output and returns the aligned sequences in a dict : sequence _ id - > sequence _ string .
The special key - 1 is reserved for the match line ( e . g . ' . : * * * * * * ' ) .''' | # Strip the boilerplate lines
lines = self . alignment_output . split ( "\n" )
assert ( lines [ 0 ] . startswith ( 'CLUSTAL' ) )
lines = '\n' . join ( lines [ 1 : ] ) . lstrip ( ) . split ( '\n' )
# The sequence IDs should be unique . Reassert this here
assert ( len ( self . sequence_ids . values ( ) ) == len ( set ( s... |
def call_insert ( tup ) :
"""Importable helper for multi - proc calling of ArtifactCache . insert on an ArtifactCache instance .
See docstring on call _ use _ cached _ files explaining why this is useful .
: param tup : A 4 - tuple of an ArtifactCache and the 3 args passed to ArtifactCache . insert :
eg ( som... | try :
cache , key , files , overwrite = tup
return cache . insert ( key , files , overwrite )
except NonfatalArtifactCacheError as e :
logger . warn ( 'Error while inserting into artifact cache: {0}' . format ( e ) )
return False |
def create_iplist_with_data ( name , iplist ) :
"""Create an IPList with initial list contents .
: param str name : name of IPList
: param list iplist : list of IPList IP ' s , networks , etc
: return : href of list location""" | iplist = IPList . create ( name = name , iplist = iplist )
return iplist |
def _get_list_widget ( self , filters , actions = None , order_column = "" , order_direction = "" , page = None , page_size = None , widgets = None , ** args ) :
"""get joined base filter and current active filter for query""" | widgets = widgets or { }
actions = actions or self . actions
page_size = page_size or self . page_size
if not order_column and self . base_order :
order_column , order_direction = self . base_order
joined_filters = filters . get_joined_filters ( self . _base_filters )
count , lst = self . datamodel . query ( joined... |
def assert_independent ( package , * packages ) :
""": param package : Python name of a module / package
: param packages : Python names of modules / packages
Make sure the ` package ` does not depend from the ` packages ` .""" | assert packages , 'At least one package must be specified'
import_package = 'from openquake.baselib.general import import_all\n' 'print(import_all("%s"))' % package
imported_modules = run_in_process ( import_package )
for mod in imported_modules :
for pkg in packages :
if mod . startswith ( pkg ) :
... |
def allocate ( self , manager = None ) :
"""This function is called once we have completed the initialization
of the : class : ` Work ` . It sets the manager of each task ( if not already done )
and defines the working directories of the tasks .
Args :
manager : : class : ` TaskManager ` object or None""" | for i , task in enumerate ( self ) :
if not hasattr ( task , "manager" ) : # Set the manager
# Use the one provided in input else the one of the work / flow .
if manager is not None :
task . set_manager ( manager )
else : # Look first in work and then in the flow .
if has... |
def update ( self , text , revision = None ) :
"""Modifies the internal state based a change to the content and returns
the sets of words added and removed .
: Parameters :
text : str
The text content of a revision
revision : ` mixed `
Revision metadata
: Returns :
A triple of lists :
current _ to... | return self . _update ( text = text , revision = revision ) |
def get_tree_from_sha ( self , ref ) :
'''Return a pygit2 . Tree object matching a SHA''' | try :
return self . repo . revparse_single ( ref ) . tree
except ( KeyError , TypeError , ValueError , AttributeError ) :
return None |
def logical_cores ( self ) :
"""Return the number of cpu cores as reported to the os .
May be different from physical _ cores if , ie , intel ' s hyperthreading is
enabled .""" | try :
return self . _logical_cores ( )
except Exception as e :
from rez . utils . logging_ import print_error
print_error ( "Error detecting logical core count, defaulting to 1: %s" % str ( e ) )
return 1 |
def ape ( self , ape_path = None ) :
'''Open in ApE if ` ApE ` is in your command line path .''' | # TODO : simplify - make ApE look in PATH only
cmd = 'ApE'
if ape_path is None : # Check for ApE in PATH
ape_executables = [ ]
for path in os . environ [ 'PATH' ] . split ( os . pathsep ) :
exepath = os . path . join ( path , cmd )
ape_executables . append ( os . access ( exepath , os . X_OK ) )... |
def sub_notes ( docs ) :
"""Substitutes the special controls for notes , warnings , todos , and bugs with
the corresponding div .""" | def substitute ( match ) :
ret = "</p><div class=\"alert alert-{}\" role=\"alert\"><h4>{}</h4>" "<p>{}</p></div>" . format ( NOTE_TYPE [ match . group ( 1 ) . lower ( ) ] , match . group ( 1 ) . capitalize ( ) , match . group ( 2 ) )
if len ( match . groups ( ) ) >= 4 and not match . group ( 4 ) :
ret +... |
def context_processor ( self , fn ) :
"""Registers a template context processor function .""" | self . _defer ( lambda app : app . context_processor ( fn ) )
return fn |
def _encode_config ( conf_dict ) :
"""Encode ` conf _ dict ` to string .""" | out = [ ]
# get variables in order defined in settings . _ ALLOWED _ MERGES
for var in settings . _ALLOWED_MERGES :
out . append ( conf_dict [ var ] )
# convert bools to chars
out = map ( lambda x : "t" if x else "f" , out )
return "" . join ( out ) |
def network_create_func ( self , net ) :
"""Create network in database and dcnm
: param net : network dictionary""" | net_id = net [ 'id' ]
net_name = net . get ( 'name' )
network_db_elem = self . get_network ( net_id )
# Check if the source of network creation is FW and if yes , skip
# this event .
# Check if there ' s a way to read the DB from service class
# TODO ( padkrish )
if self . fw_api . is_network_source_fw ( network_db_ele... |
def account_overview ( object ) :
"""Create layout for user profile""" | return Layout ( Container ( Row ( Column2 ( Panel ( 'Avatar' , Img ( src = "{}{}" . format ( settings . MEDIA_URL , object . avatar ) ) , collapse = True , ) , ) , Column10 ( Panel ( 'Account information' , DescriptionList ( 'email' , 'first_name' , 'last_name' , ) , ) ) , ) ) ) |
def _update_from_pb ( self , instance_pb ) :
"""Refresh self from the server - provided protobuf .
Helper for : meth : ` from _ pb ` and : meth : ` reload ` .""" | if not instance_pb . display_name : # Simple field ( string )
raise ValueError ( "Instance protobuf does not contain display_name" )
self . display_name = instance_pb . display_name
self . type_ = instance_pb . type
self . labels = dict ( instance_pb . labels )
self . _state = instance_pb . state |
def from_url ( url , ** options ) :
"""Downloads the contents of a given URL and loads it
into a new TableFu instance""" | resp = urllib2 . urlopen ( url )
return TableFu ( resp , ** options ) |
def toString ( self ) :
"""Returns time as string .""" | slist = self . toList ( )
string = angle . slistStr ( slist )
return string if slist [ 0 ] == '-' else string [ 1 : ] |
def sample_t ( self , n ) :
"""NAME :
sample _ t
PURPOSE :
generate a stripping time ( time since stripping ) ; simple implementation could be replaced by more complicated distributions in sub - classes of streamdf
INPUT :
n - number of points to return
OUTPUT :
array of n stripping times
HISTORY : ... | return numpy . random . uniform ( size = n ) * self . _tdisrupt |
def process_experiences ( self , current_info : AllBrainInfo , next_info : AllBrainInfo ) :
"""Checks agent histories for processing condition , and processes them as necessary .
Processing involves calculating value and advantage targets for model updating step .
: param current _ info : Current AllBrainInfo
... | info_student = next_info [ self . brain_name ]
for l in range ( len ( info_student . agents ) ) :
if info_student . local_done [ l ] :
agent_id = info_student . agents [ l ]
self . stats [ 'Environment/Cumulative Reward' ] . append ( self . cumulative_rewards . get ( agent_id , 0 ) )
self . ... |
def _StatusUpdateThreadMain ( self ) :
"""Main function of the status update thread .""" | while self . _status_update_active : # Make a local copy of the PIDs in case the dict is changed by
# the main thread .
for pid in list ( self . _process_information_per_pid . keys ( ) ) :
self . _CheckStatusWorkerProcess ( pid )
self . _UpdateForemanProcessStatus ( )
tasks_status = self . _task_man... |
def lint ( ctx , scenario_name ) : # pragma : no cover
"""Lint the role .""" | args = ctx . obj . get ( 'args' )
subcommand = base . _get_subcommand ( __name__ )
command_args = { 'subcommand' : subcommand , }
base . execute_cmdline_scenarios ( scenario_name , args , command_args ) |
def find_index ( model_meta , weights = None , verbosity = 0 ) :
"""Return a tuple of index metadata for the model metadata dict provided
return value format is :
field _ name ,
' primary _ key ' : boolean representing whether it ' s the primary key ,
' unique ' : boolean representing whether it ' s a uniqu... | weights = weights or find_index . default_weights
N = model_meta [ 'Meta' ] . get ( 'count' , 0 )
for field_name , field_meta in model_meta . iteritems ( ) :
if field_name == 'Meta' :
continue
pkfield = field_meta . get ( 'primary_key' )
if pkfield :
if verbosity > 1 :
print pkfi... |
def kbtype ( self , value ) :
"""Set kbtype .""" | if value is None : # set the default value
return
# or set one of the available values
kbtype = value [ 0 ] if len ( value ) > 0 else 'w'
if kbtype not in [ 't' , 'd' , 'w' ] :
raise ValueError ( 'unknown type "{value}", please use one of \
following values: "taxonomy", "dynamic" or... |
def initialize_ray ( ) :
"""Initializes ray based on environment variables and internal defaults .""" | if threading . current_thread ( ) . name == "MainThread" :
plasma_directory = None
object_store_memory = os . environ . get ( "MODIN_MEMORY" , None )
if os . environ . get ( "MODIN_OUT_OF_CORE" , "False" ) . title ( ) == "True" :
from tempfile import gettempdir
plasma_directory = gettempdir ... |
def data_kva_compare ( db_data , user_data ) :
"""Validate key / value data in KeyValueArray .
Args :
db _ data ( list ) : The data store in Redis .
user _ data ( dict ) : The user provided data .
Returns :
bool : True if the data passed validation .""" | for kv_data in db_data :
if kv_data . get ( 'key' ) == user_data . get ( 'key' ) :
if kv_data . get ( 'value' ) == user_data . get ( 'value' ) :
return True
return False |
def init_with_context ( self , context ) :
"""Please refer to
: meth : ` ~ admin _ tools . menu . items . MenuItem . init _ with _ context `
documentation from : class : ` ~ admin _ tools . menu . items . MenuItem ` class .""" | from admin_tools . menu . models import Bookmark
for b in Bookmark . objects . filter ( user = context [ 'request' ] . user ) :
self . children . append ( MenuItem ( mark_safe ( b . title ) , b . url ) )
if not len ( self . children ) :
self . enabled = False |
def is_dtype_equal ( source , target ) :
"""Check if two dtypes are equal .
Parameters
source : The first dtype to compare
target : The second dtype to compare
Returns
boolean
Whether or not the two dtypes are equal .
Examples
> > > is _ dtype _ equal ( int , float )
False
> > > is _ dtype _ equ... | try :
source = _get_dtype ( source )
target = _get_dtype ( target )
return source == target
except ( TypeError , AttributeError ) : # invalid comparison
# object = = category will hit this
return False |
def add_threat_list ( self , threat_list ) :
"""Add threat list entry if it does not exist .""" | q = '''INSERT OR IGNORE INTO threat_list
(threat_type, platform_type, threat_entry_type, timestamp)
VALUES
(?, ?, ?, current_timestamp)
'''
params = [ threat_list . threat_type , threat_list . platform_type , threat_list . threat_entry_type ]
with self . g... |
def interface ( cls ) :
'''Marks the decorated class as an abstract interface .
Injects following classmethods :
. . py : method : : . all ( context )
Returns a list of instances of each component in the ` ` context ` ` implementing this ` ` @ interface ` `
: param context : context to look in
: type cont... | if not cls :
return None
cls . implementations = [ ]
# Inject methods
def _all ( cls , context , ignore_exceptions = False ) :
return list ( context . get_components ( cls , ignore_exceptions = ignore_exceptions ) )
cls . all = _all . __get__ ( cls )
def _any ( cls , context ) :
instances = cls . all ( cont... |
def filter_channels_by_status ( channel_states : List [ NettingChannelState ] , exclude_states : Optional [ List [ str ] ] = None , ) -> List [ NettingChannelState ] :
"""Filter the list of channels by excluding ones
for which the state exists in ` exclude _ states ` .""" | if exclude_states is None :
exclude_states = [ ]
states = [ ]
for channel_state in channel_states :
if channel . get_status ( channel_state ) not in exclude_states :
states . append ( channel_state )
return states |
def translate_changes ( initial_change ) :
"""Translate rope . base . change . Change instances to dictionaries .
See Refactor . get _ changes for an explanation of the resulting
dictionary .""" | agenda = [ initial_change ]
result = [ ]
while agenda :
change = agenda . pop ( 0 )
if isinstance ( change , rope_change . ChangeSet ) :
agenda . extend ( change . changes )
elif isinstance ( change , rope_change . ChangeContents ) :
result . append ( { 'action' : 'change' , 'file' : change ... |
def delete_prefix ( self , name ) : # noqa : D302
r"""Delete hierarchy levels from all nodes in the tree .
: param nodes : Prefix to delete
: type nodes : : ref : ` NodeName `
: raises :
* RuntimeError ( Argument \ ` name \ ` is not a valid prefix )
* RuntimeError ( Argument \ ` name \ ` is not valid )
... | if self . _validate_node_name ( name ) :
raise RuntimeError ( "Argument `name` is not valid" )
if ( not self . root_name . startswith ( name ) ) or ( self . root_name == name ) :
raise RuntimeError ( "Argument `name` is not a valid prefix" )
self . _delete_prefix ( name ) |
def rotate_quat ( attitude , roll , pitch , yaw ) :
'''Returns rotated quaternion
: param attitude : quaternion [ w , x , y , z ]
: param roll : rotation in rad
: param pitch : rotation in rad
: param yaw : rotation in rad
: returns : quaternion [ w , x , y , z ]''' | quat = Quaternion ( attitude )
rotation = Quaternion ( [ roll , pitch , yaw ] )
res = rotation * quat
return res . q |
def is_waiting_for_input ( self ) :
"""could make one step further
: return :""" | return self . waiting_for and not isinstance ( self . waiting_for , forking . SwitchOnValue ) and not is_base_type ( self . waiting_for ) |
def get_correction ( self , entry ) :
"""Gets the BandFilling correction for a defect entry""" | eigenvalues = entry . parameters [ "eigenvalues" ]
kpoint_weights = entry . parameters [ "kpoint_weights" ]
potalign = entry . parameters [ "potalign" ]
vbm = entry . parameters [ "vbm" ]
cbm = entry . parameters [ "cbm" ]
bf_corr = self . perform_bandfill_corr ( eigenvalues , kpoint_weights , potalign , vbm , cbm )
en... |
def transform ( self , X , y = None , copy = None ) :
"""Perform standardization by centering and scaling using the parameters .
: param X : Data matrix to scale .
: type X : numpy . ndarray , shape [ n _ samples , n _ features ]
: param y : Passthrough for scikit - learn ` ` Pipeline ` ` compatibility .
: ... | check_is_fitted ( self , 'scale_' )
copy = copy if copy is not None else self . copy
X = check_array ( X , accept_sparse = 'csr' , copy = copy , warn_on_dtype = True , estimator = self , dtype = FLOAT_DTYPES )
if sparse . issparse ( X ) :
if self . with_mean :
raise ValueError ( "Cannot center sparse matric... |
def add_rna_args ( parser , min_mapping_quality_default = MIN_READ_MAPPING_QUALITY ) :
"""Extends an ArgumentParser instance with the following commandline arguments :
- - bam
- - min - reads
- - min - mapping - quality
- - use - duplicate - reads
- - drop - secondary - alignments""" | rna_group = parser . add_argument_group ( "RNA" )
rna_group . add_argument ( "--bam" , required = True , help = "BAM file containing RNAseq reads" )
rna_group . add_argument ( "--min-mapping-quality" , type = int , default = min_mapping_quality_default , help = "Minimum MAPQ value to allow for a read (default %(default... |
def compiled_quil ( self ) :
"""If the Quil program associated with the Job was compiled ( e . g . , to translate it to the
QPU ' s natural gateset ) return this compiled program .
: rtype : Optional [ Program ]""" | prog = self . _raw . get ( "program" , { } ) . get ( "compiled-quil" , None )
if prog is not None :
return parse_program ( prog )
else : # if we failed too early to even get a " compiled - quil " field ,
# then alert the user to that problem instead
if self . _raw [ 'status' ] == 'ERROR' :
return self .... |
def update_room ( self , stream_id , room_definition ) :
'''update a room definition''' | req_hook = 'pod/v2/room/' + str ( stream_id ) + '/update'
req_args = json . dumps ( room_definition )
status_code , response = self . __rest__ . POST_query ( req_hook , req_args )
self . logger . debug ( '%s: %s' % ( status_code , response ) )
return status_code , response |
def do_signal ( self , signame : str ) -> None :
"""Send a Unix signal""" | if hasattr ( signal , signame ) :
os . kill ( os . getpid ( ) , getattr ( signal , signame ) )
else :
self . _sout . write ( 'Unknown signal %s\n' % signame ) |
def dump_registers_peek ( registers , data , separator = ' ' , width = 16 ) :
"""Dump data pointed to by the given registers , if any .
@ type registers : dict ( str S { - > } int )
@ param registers : Dictionary mapping register names to their values .
This value is returned by L { Thread . get _ context } .... | if None in ( registers , data ) :
return ''
names = compat . keys ( data )
names . sort ( )
result = ''
for reg_name in names :
tag = reg_name . lower ( )
dumped = HexDump . hexline ( data [ reg_name ] , separator , width )
result += '%s -> %s\n' % ( tag , dumped )
return result |
def sendSomeData ( self , howMany ) :
"""Send some DATA commands to my peer ( s ) to relay some data .
@ param howMany : an int , the number of chunks to send out .""" | # print ' sending some data ' , howMany
if self . transport is None :
return
peer = self . transport . getQ2QPeer ( )
while howMany > 0 : # sort transloads so that the least - frequently - serviced ones will
# come first
tloads = [ ( findin ( tl . name , self . sentTransloads ) , tl ) for tl in self . nexus . t... |
def tuple_to_schema ( tuple_ ) :
"""Convert a tuple representing an XML data structure into a schema tuple
that can be used in the ` ` . schema ` ` property of a sub - class of
PREMISElement .""" | schema = [ ]
for element in tuple_ :
if isinstance ( element , ( tuple , list ) ) :
try :
if isinstance ( element [ 1 ] , six . string_types ) :
schema . append ( ( element [ 0 ] , ) )
else :
schema . append ( tuple_to_schema ( element ) )
exce... |
def calc_qa_v1 ( self ) :
"""Calculate outflow .
The working equation is the analytical solution of the linear storage
equation under the assumption of constant change in inflow during
the simulation time step .
Required flux sequence :
| RK |
Required state sequence :
| QZ |
Updated state sequence ... | flu = self . sequences . fluxes . fastaccess
old = self . sequences . states . fastaccess_old
new = self . sequences . states . fastaccess_new
aid = self . sequences . aides . fastaccess
if flu . rk <= 0. :
new . qa = new . qz
elif flu . rk > 1e200 :
new . qa = old . qa + new . qz - old . qz
else :
aid . te... |
def add_path ( self , path ) : # type : ( _ BaseSourcePaths , str ) - > None
"""Add a local path
: param _ BaseSourcePaths self : this
: param str path : path to add""" | if isinstance ( path , pathlib . Path ) :
self . _paths . append ( path )
else :
self . _paths . append ( pathlib . Path ( path ) ) |
def resolve_alias ( self , name ) :
"""Resolve a calendar alias for retrieval .
Parameters
name : str
The name of the requested calendar .
Returns
canonical _ name : str
The real name of the calendar to create / return .""" | seen = [ ]
while name in self . _aliases :
seen . append ( name )
name = self . _aliases [ name ]
# This is O ( N * * 2 ) , but if there ' s an alias chain longer than 2,
# something strange has happened .
if name in seen :
seen . append ( name )
raise CyclicCalendarAlias ( cycle = "... |
def append_styles ( self , tag , attrs ) :
"""Append classes found in HTML elements to the list of styles used .
Because we haven ' t built the tree , we aren ' t using the ` tag ` parameter
for now .
@ param < string > tag
The HTML tag we ' re parsing
@ param < tuple > attrs
A tuple of HTML element att... | dattrs = dict ( attrs )
if 'class' in dattrs : # print " Found classes ' % s ' " % dattrs [ ' class ' ]
class_names = dattrs [ 'class' ] . split ( )
dotted_names = map ( prepend_dot , class_names )
dotted_names . sort ( )
self . used_classes . extend ( ' ' . join ( dotted_names ) )
self . unchained_... |
def resolve_variables ( self , provided_variables ) :
"""Resolve the values of the blueprint variables .
This will resolve the values of the template parameters with values
from the env file , the config , and any lookups resolved . The
resolution is run twice , in case the blueprint is jinja2 templated
and... | # Pass 1 to set resolved _ variables to provided variables
self . resolved_variables = { }
variable_dict = dict ( ( var . name , var ) for var in provided_variables )
for var_name , _var_def in variable_dict . items ( ) :
value = resolve_variable ( variable_dict . get ( var_name ) , self . name )
if value is no... |
def sum_layout_dimensions ( dimensions ) :
"""Sum a list of : class : ` . LayoutDimension ` instances .""" | min = sum ( [ d . min for d in dimensions if d . min is not None ] )
max = sum ( [ d . max for d in dimensions if d . max is not None ] )
preferred = sum ( [ d . preferred for d in dimensions ] )
return LayoutDimension ( min = min , max = max , preferred = preferred ) |
def check ( self , results_id ) :
"""Check for results of a membership request .
: param str results _ id : the ID of a membership request
: return : successfully created memberships
: rtype : : class : ` list `
: raises groupy . exceptions . ResultsNotReady : if the results are not ready
: raises groupy ... | path = 'results/{}' . format ( results_id )
url = utils . urljoin ( self . url , path )
response = self . session . get ( url )
if response . status_code == 503 :
raise exceptions . ResultsNotReady ( response )
if response . status_code == 404 :
raise exceptions . ResultsExpired ( response )
return response . d... |
def get_vnetwork_vms_input_last_rcvd_instance ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vnetwork_vms = ET . Element ( "get_vnetwork_vms" )
config = get_vnetwork_vms
input = ET . SubElement ( get_vnetwork_vms , "input" )
last_rcvd_instance = ET . SubElement ( input , "last-rcvd-instance" )
last_rcvd_instance . text = kwargs . pop ( 'last_rcvd_instance' )
callback = kw... |
def full_route ( self ) :
'''The full : attr : ` route ` for this : class : ` . Router ` .
It includes the : attr : ` parent ` portion of the route if a parent
router is available .''' | if self . _parent :
return self . _parent . full_route + self . _route
else :
return self . _route |
def on_connect ( client ) :
"""Default on - connect actions .""" | client . nick ( client . user . nick )
client . userinfo ( client . user . username , client . user . realname ) |
def atmos ( ctx , atmo , contrast , bias , jobs , out_dtype , src_path , dst_path , creation_options , as_color , ) :
"""Atmospheric correction""" | if as_color :
click . echo ( "rio color {} {} {}" . format ( src_path , dst_path , simple_atmo_opstring ( atmo , contrast , bias ) ) )
exit ( 0 )
with rasterio . open ( src_path ) as src :
opts = src . profile . copy ( )
windows = [ ( window , ij ) for ij , window in src . block_windows ( ) ]
opts . upd... |
def createContactItem ( self , person , label , number ) :
"""Create a L { PhoneNumber } item for C { number } , associated with C { person } .
@ type person : L { Person }
@ param label : The value to use for the I { label } attribute of the new
L { PhoneNumber } item .
@ type label : C { unicode }
@ par... | if number :
return PhoneNumber ( store = person . store , person = person , label = label , number = number ) |
def list_contrib ( name = None , ret = False , _debug = False ) :
"""Show the list of all existing contribs .
Params :
- name : filter to search the contribs
- ret : whether the function should return a dict instead of printing it""" | # _ debug : checks that all contrib modules have correctly defined :
# # scapy . contrib . description = [ . . . ]
# # scapy . contrib . status = [ . . . ]
# # scapy . contrib . name = [ . . . ] ( optional )
# or set the flag :
# # scapy . contrib . description = skip
# to skip the file
if name is None :
name = "*.... |
def safeRef ( target , onDelete = None ) :
"""Return a * safe * weak reference to a callable target
target - - the object to be weakly referenced , if it ' s a
bound method reference , will create a BoundMethodWeakref ,
otherwise creates a simple weakref .
onDelete - - if provided , will have a hard referen... | if hasattr ( target , im_self ) :
if getattr ( target , im_self ) is not None : # Turn a bound method into a BoundMethodWeakref instance .
# Keep track of these instances for lookup by disconnect ( ) .
assert hasattr ( target , im_func ) , """safeRef target %r has %s, but no %s, don't know how to create... |
def or_list ( items : Sequence [ str ] ) -> Optional [ str ] :
"""Given [ A , B , C ] return ' A , B , or C ' .""" | if not items :
raise ValueError
if len ( items ) == 1 :
return items [ 0 ]
if len ( items ) == 2 :
return items [ 0 ] + " or " + items [ 1 ]
* selected , last_item = items [ : MAX_LENGTH ]
return ", " . join ( selected ) + " or " + last_item |
def extract_helices_dssp ( in_pdb ) :
"""Uses DSSP to find alpha - helices and extracts helices from a pdb file .
Returns a length 3 list with a helix id , the chain id and a dict
containing the coordinates of each residues CA .
Parameters
in _ pdb : string
Path to a PDB file .""" | from ampal . pdb_parser import split_pdb_lines
dssp_out = subprocess . check_output ( [ global_settings [ 'dssp' ] [ 'path' ] , in_pdb ] )
helix = 0
helices = [ ]
h_on = False
for line in dssp_out . splitlines ( ) :
dssp_line = line . split ( )
try :
if dssp_line [ 4 ] == 'H' :
if helix not ... |
def _is_exception_rule ( self , element ) :
"""Check for " exception rule " .
Address elements will be appended onto a new line on the lable except
for when the penultimate lable line fulfils certain criteria , in which
case the element will be concatenated onto the penultimate line . This
method checks for... | if element [ 0 ] . isdigit ( ) and element [ - 1 ] . isdigit ( ) :
return True
if len ( element ) > 1 and element [ 0 ] . isdigit ( ) and element [ - 2 ] . isdigit ( ) and element [ - 1 ] . isalpha ( ) :
return True
if len ( element ) == 1 and element . isalpha ( ) :
return True
return False |
def delete ( self , key ) :
'''Removes the object named by ` key ` .
Writes to both ` ` cache _ datastore ` ` and ` ` child _ datastore ` ` .''' | self . cache_datastore . delete ( key )
self . child_datastore . delete ( key ) |
def _do_analysis_cross_validation ( self ) :
"""Find the best model ( fit ) based on cross - valiation ( leave one out )""" | assert len ( self . df ) < 15 , "Cross-validation is not implemented if your sample contains more than 15 datapoints"
# initialization : first model is the mean , but compute cv correctly .
errors = [ ]
response_term = [ Term ( [ LookupFactor ( self . y ) ] ) ]
model_terms = [ Term ( [ ] ) ]
# empty term is the interce... |
def require_scalar ( self , * args : Type ) -> None :
"""Require the node to be a scalar .
If additional arguments are passed , these are taken as a list of valid types ; if the node matches one of these , then it is accepted .
Example :
# Match either an int or a string
node . require _ scalar ( int , str ... | node = Node ( self . yaml_node )
if len ( args ) == 0 :
if not node . is_scalar ( ) :
raise RecognitionError ( ( '{}{}A scalar is required' ) . format ( self . yaml_node . start_mark , os . linesep ) )
else :
for typ in args :
if node . is_scalar ( typ ) :
return
raise Recognitio... |
def load_unicode ( self , resource_path ) :
"""Gets the content of a resource""" | resource_content = pkg_resources . resource_string ( self . module_name , resource_path )
return resource_content . decode ( 'utf-8' ) |
def matches ( self , properties ) :
"""Tests if the given criterion matches this LDAP criterion
: param properties : A dictionary of properties
: return : True if the properties matches this criterion , else False""" | try : # Use the comparator
return self . comparator ( self . value , properties [ self . name ] )
except KeyError : # Criterion key is not in the properties
return False |
def done ( self ) :
"""Returns True if the call was successfully cancelled or finished
running , False otherwise . This function updates the executionQueue
so it receives all the awaiting message .""" | # Flush the current future in the local buffer ( potential deadlock
# otherwise )
try :
scoop . _control . execQueue . remove ( self )
scoop . _control . execQueue . socket . sendFuture ( self )
except ValueError as e : # Future was not in the local queue , everything is fine
pass
# Process buffers
scoop . ... |
def _add_two_way_unqualified_edge ( self , u : BaseEntity , v : BaseEntity , relation : str ) -> str :
"""Add an unqualified edge both ways .""" | self . add_unqualified_edge ( v , u , relation )
return self . add_unqualified_edge ( u , v , relation ) |
def print_errors ( function ) :
"""Prints the exceptions raised by the decorated function
without interfering . For debugging purpose .""" | def wrapper ( * args , ** kwargs ) :
try :
return function ( * args , ** kwargs )
except BaseException as e :
print ( "Exception raise calling %s: %s" % ( reflect . canonical_name ( function ) , get_exception_message ( e ) ) )
raise
return wrapper |
def getInfoMutator ( self ) :
"""Returns a info mutator""" | if self . _infoMutator :
return self . _infoMutator
infoItems = [ ]
for sourceDescriptor in self . sources :
if sourceDescriptor . layerName is not None :
continue
loc = Location ( sourceDescriptor . location )
sourceFont = self . fonts [ sourceDescriptor . name ]
if sourceFont is None :
... |
def _delete ( self , obj , ** kwargs ) :
"""Delete the object directly .
. . code - block : : python
DBSession . sacrud ( Users ) . _ delete ( UserObj )
If you no needed commit session
. . code - block : : python
DBSession . sacrud ( Users , commit = False ) . _ delete ( UserObj )""" | if isinstance ( obj , sqlalchemy . orm . query . Query ) :
obj = obj . one ( )
obj = self . preprocessing ( obj = obj ) . delete ( )
self . session . delete ( obj )
if kwargs . get ( 'commit' , self . commit ) is True :
try :
self . session . commit ( )
except AssertionError :
transaction . ... |
def setup_logfile_raw ( self , logfile , mode = 'w' ) :
'''start logging raw bytes to the given logfile , without timestamps''' | self . logfile_raw = open ( logfile , mode = mode ) |
def state_view_for_block ( block_wrapper , state_view_factory ) :
"""Returns the state view for an arbitrary block .
Args :
block _ wrapper ( BlockWrapper ) : The block for which a state
view is to be returned
state _ view _ factory ( StateViewFactory ) : The state view factory
used to create the StateVie... | state_root_hash = block_wrapper . state_root_hash if block_wrapper is not None else None
return state_view_factory . create_view ( state_root_hash ) |
def create_host_only_network_interface ( self ) :
"""Creates a new adapter for Host Only Networking .
out host _ interface of type : class : ` IHostNetworkInterface `
Created host interface object .
return progress of type : class : ` IProgress `
Progress object to track the operation completion .
raises ... | ( progress , host_interface ) = self . _call ( "createHostOnlyNetworkInterface" )
progress = IProgress ( progress )
host_interface = IHostNetworkInterface ( host_interface )
return ( progress , host_interface ) |
def _paste_using_mouse_button_2 ( self ) :
"""Paste using the mouse : Press the second mouse button , then release it again .""" | focus = self . localDisplay . get_input_focus ( ) . focus
xtest . fake_input ( focus , X . ButtonPress , X . Button2 )
xtest . fake_input ( focus , X . ButtonRelease , X . Button2 )
logger . debug ( "Mouse Button2 event sent." ) |
def colorize_errors ( event , colored ) :
"""Highlights some commonly known Lambda error cases in red :
- Nodejs process crashes
- Lambda function timeouts""" | nodejs_crash_msg = "Process exited before completing request"
timeout_msg = "Task timed out"
if nodejs_crash_msg in event . message or timeout_msg in event . message :
event . message = colored . red ( event . message )
return event |
def is_socket_closed ( sock ) : # pragma nocover
"""Check if socket ` ` sock ` ` is closed .""" | if not sock :
return True
try :
if not poll : # pragma nocover
if not select :
return False
try :
return bool ( select ( [ sock ] , [ ] , [ ] , 0.0 ) [ 0 ] )
except socket . error :
return True
# This version is better on platforms that support it ... |
def recursive_file_count ( files , item = None , checksum = False ) :
"""Given a filepath or list of filepaths , return the total number of files .""" | if not isinstance ( files , ( list , set ) ) :
files = [ files ]
total_files = 0
if checksum is True :
md5s = [ f . get ( 'md5' ) for f in item . files ]
else :
md5s = list ( )
if isinstance ( files , dict ) : # make sure to use local filenames .
_files = files . values ( )
else :
if isinstance ( fi... |
def parse_all_arguments ( func ) :
"""determine all positional and named arguments as a dict""" | args = dict ( )
if sys . version_info < ( 3 , 0 ) :
func_args = inspect . getargspec ( func )
if func_args . defaults is not None :
val = len ( func_args . defaults )
for i , itm in enumerate ( func_args . args [ - val : ] ) :
args [ itm ] = func_args . defaults [ i ]
else :
func... |
def to_dict ( self , val = UNSET ) :
"""Creates dict object from dict2 object
Args :
val ( : obj : ` dict2 ` ) : Value to create from
Returns :
Equivalent dict object .""" | if val is UNSET :
val = self
if isinstance ( val , dict2 ) or isinstance ( val , dict ) :
res = dict ( )
for k , v in val . items ( ) :
res [ k ] = self . to_dict ( v )
return res
elif isinstance ( val , list ) :
res = [ ]
for item in val :
res . append ( self . to_dict ( item ) ... |
def _maybe_log_technical_terms ( global_options , tool_options ) :
"""Log technical terms as appropriate if the user requested it .
As a side effect , if - - log - technical - terms - to is passed to the linter
then open up the file specified ( or create it ) and then merge the set
of technical words that we ... | log_technical_terms_to_path = global_options . get ( "log_technical_terms_to" , None )
log_technical_terms_to_queue = tool_options . get ( "log_technical_terms_to" , None )
if log_technical_terms_to_path :
assert log_technical_terms_to_queue is not None
try :
os . makedirs ( os . path . dirname ( log_te... |
def _folder_item_method ( self , analysis_brain , item ) :
"""Fills the analysis ' method to the item passed in .
: param analysis _ brain : Brain that represents an analysis
: param item : analysis ' dictionary counterpart that represents a row""" | is_editable = self . is_analysis_edition_allowed ( analysis_brain )
method_title = analysis_brain . getMethodTitle
item [ 'Method' ] = method_title or ''
if is_editable :
method_vocabulary = self . get_methods_vocabulary ( analysis_brain )
if method_vocabulary :
item [ 'Method' ] = analysis_brain . getM... |
def upload_numpy_to_s3_shards ( num_shards , s3 , bucket , key_prefix , array , labels = None ) :
"""Upload the training ` ` array ` ` and ` ` labels ` ` arrays to ` ` num _ shards ` ` s3 objects ,
stored in " s3 : / / ` ` bucket ` ` / ` ` key _ prefix ` ` / " .""" | shards = _build_shards ( num_shards , array )
if labels is not None :
label_shards = _build_shards ( num_shards , labels )
uploaded_files = [ ]
if key_prefix [ - 1 ] != '/' :
key_prefix = key_prefix + '/'
try :
for shard_index , shard in enumerate ( shards ) :
with tempfile . TemporaryFile ( ) as fi... |
def Initialize ( config = None , external_hostname = None , admin_password = None , redownload_templates = False , repack_templates = True , token = None ) :
"""Initialize or update a GRR configuration .""" | print ( "Checking write access on config %s" % config [ "Config.writeback" ] )
if not os . access ( config . parser . filename , os . W_OK ) :
raise IOError ( "Config not writeable (need sudo?)" )
print ( "\nStep 0: Importing Configuration from previous installation." )
options_imported = 0
prev_config_file = confi... |
def mousePressEvent ( self , event ) :
"""Handle file link clicks .""" | super ( OutputWindow , self ) . mousePressEvent ( event )
if self . _link_match :
path = self . _link_match . group ( 'url' )
line = self . _link_match . group ( 'line' )
if line is not None :
line = int ( line ) - 1
else :
line = 0
self . open_file_requested . emit ( path , line ) |
def process_alias_export_namespace ( namespace ) :
"""Validate input arguments when the user invokes ' az alias export ' .
Args :
namespace : argparse namespace object .""" | namespace . export_path = os . path . abspath ( namespace . export_path )
if os . path . isfile ( namespace . export_path ) :
raise CLIError ( FILE_ALREADY_EXISTS_ERROR . format ( namespace . export_path ) )
export_path_dir = os . path . dirname ( namespace . export_path )
if not os . path . isdir ( export_path_dir... |
def strxor ( s1 , s2 ) :
"""Returns the binary XOR of the 2 provided strings s1 and s2 . s1 and s2
must be of same length .""" | return b"" . join ( map ( lambda x , y : chb ( orb ( x ) ^ orb ( y ) ) , s1 , s2 ) ) |
def MergeData ( self , merge_data , raw_data = None ) :
"""Merges data read from a config file into the current config .""" | self . FlushCache ( )
if raw_data is None :
raw_data = self . raw_data
for k , v in iteritems ( merge_data ) : # A context clause .
if isinstance ( v , dict ) and k not in self . type_infos :
if k not in self . valid_contexts :
raise InvalidContextError ( "Invalid context specified: %s" % k ... |
def add_lat_lon ( self , lat , lon , precision = 1e7 ) :
"""Add lat , lon to gps ( lat , lon in float ) .""" | self . _ef [ "GPS" ] [ piexif . GPSIFD . GPSLatitudeRef ] = "N" if lat > 0 else "S"
self . _ef [ "GPS" ] [ piexif . GPSIFD . GPSLongitudeRef ] = "E" if lon > 0 else "W"
self . _ef [ "GPS" ] [ piexif . GPSIFD . GPSLongitude ] = decimal_to_dms ( abs ( lon ) , int ( precision ) )
self . _ef [ "GPS" ] [ piexif . GPSIFD . G... |
def _refine_enc ( enc ) :
'''Return the properly formatted ssh value for the authorized encryption key
type . ecdsa defaults to 256 bits , must give full ecdsa enc schema string
if using higher enc . If the type is not found , raise CommandExecutionError .''' | rsa = [ 'r' , 'rsa' , 'ssh-rsa' ]
dss = [ 'd' , 'dsa' , 'dss' , 'ssh-dss' ]
ecdsa = [ 'e' , 'ecdsa' , 'ecdsa-sha2-nistp521' , 'ecdsa-sha2-nistp384' , 'ecdsa-sha2-nistp256' ]
ed25519 = [ 'ed25519' , 'ssh-ed25519' ]
if enc in rsa :
return 'ssh-rsa'
elif enc in dss :
return 'ssh-dss'
elif enc in ecdsa : # ecdsa de... |
def _set_get_vnetwork_portgroups ( self , v , load = False ) :
"""Setter method for get _ vnetwork _ portgroups , mapped from YANG variable / brocade _ vswitch _ rpc / get _ vnetwork _ portgroups ( rpc )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ get _ vnetwork _ p... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = get_vnetwork_portgroups . get_vnetwork_portgroups , is_leaf = True , yang_name = "get-vnetwork-portgroups" , rest_name = "get-vnetwork-portgroups" , parent = self , path_helper = self . _path_helper , extmethods = self . _ext... |
def remove ( self ) :
"""Remove this node from the list of children of its current parent ,
if the current parent is not ` ` None ` ` , otherwise do nothing .
. . versionadded : : 1.7.0""" | if self . parent is not None :
for i , child in enumerate ( self . parent . children ) :
if id ( child ) == id ( self ) :
self . parent . remove_child ( i )
self . parent = None
break |
def dynamics_bs ( times , masses , smas , eccs , incls , per0s , long_ans , mean_anoms , t0 = 0.0 , vgamma = 0.0 , stepsize = 0.01 , orbiterror = 1e-16 , ltte = False , return_roche_euler = False ) :
"""Burlisch - Stoer integration of orbits to give positions and velocities
of any given number of stars in hierarc... | if not _can_bs :
raise ImportError ( "photodynam is not installed (http://github.com/phoebe-project/photodynam)" )
times = _ensure_tuple ( times )
masses = _ensure_tuple ( masses )
smas = _ensure_tuple ( smas )
eccs = _ensure_tuple ( eccs )
incls = _ensure_tuple ( incls )
per0s = _ensure_tuple ( per0s )
long_ans = ... |
def send_feature_report ( self , data , report_id = 0x00 ) :
"""Send a Feature report to a HID device .
Feature reports are sent over the Control endpoint as a Set _ Report
transfer .
Parameters :
data The data to send
Returns :
This function returns the actual number of bytes written""" | if not self . _is_open :
raise HIDException ( "HIDDevice not open" )
report = bytearray ( [ report_id ] ) + bytearray ( data )
cdata = ffi . new ( "const unsigned char[]" , bytes ( report ) )
bytes_written = hidapi . hid_send_feature_report ( self . _device , cdata , len ( report ) )
if bytes_written == - 1 :
r... |
def binaryTree_nodeNames ( binaryTree ) :
"""creates names for the leave and internal nodes
of the newick tree from the leaf labels""" | def fn ( binaryTree , labels ) :
if binaryTree . internal :
fn ( binaryTree . left , labels )
fn ( binaryTree . right , labels )
labels [ binaryTree . traversalID . mid ] = labels [ binaryTree . left . traversalID . mid ] + "_" + labels [ binaryTree . right . traversalID . mid ]
retu... |
def done ( self ) :
"""Return True the future is done , False otherwise .
This still returns True in failure cases ; checking : meth : ` result ` or
: meth : ` exception ` is the canonical way to assess success or failure .""" | return self . _exception != self . _SENTINEL or self . _result != self . _SENTINEL |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.