signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def removeActor ( self , a ) :
"""Remove ` ` vtkActor ` ` or actor index from current renderer .""" | if not self . initializedPlotter :
save_int = self . interactive
self . show ( interactive = 0 )
self . interactive = save_int
return
if self . renderer :
self . renderer . RemoveActor ( a )
if hasattr ( a , 'renderedAt' ) :
ir = self . renderers . index ( self . renderer )
a . r... |
def remove_column ( self , column_name , inplace = False ) :
"""Removes the column with the given name from the SFrame .
If inplace = = False ( default ) this operation does not modify the
current SFrame , returning a new SFrame .
If inplace = = True , this operation modifies the current
SFrame , returning ... | if column_name not in self . column_names ( ) :
raise KeyError ( 'Cannot find column %s' % column_name )
if inplace :
self . __is_dirty__ = True
try :
with cython_context ( ) :
if self . _is_vertex_frame ( ) :
assert column_name != '__id' , 'Cannot remove \"__id\" column'... |
def _sanitize_url ( url , max_length ) :
"""Sanitize and shorten url to fit in max _ length .
Function is stable : same input MUST ALWAYS give same result , accros changes
in code as well . Different URLs might give same result .
As much as possible , the extension should be kept .
Heuristics are applied to... | url = urllib . parse . urlparse ( url )
netloc = url . netloc
for prefix in _NETLOC_COMMON_PREFIXES :
if netloc . startswith ( prefix ) :
netloc = netloc [ len ( prefix ) : ]
for suffix in _NETLOC_COMMON_SUFFIXES :
if netloc . endswith ( suffix ) :
netloc = netloc [ : - len ( suffix ) ]
url = '%... |
def find_name ( tagtype : str , name : str , language : { str , 'Language' , None } = None ) :
"""Find the subtag of a particular ` tagtype ` that has the given ` name ` .
The default language , " und " , will allow matching names in any language ,
so you can get the code ' fr ' by looking up " French " , " Fra... | # No matter what form of language we got , normalize it to a single
# language subtag
if isinstance ( language , Language ) :
language = language . language
elif isinstance ( language , str ) :
language = get ( language ) . language
if language is None :
language = 'und'
code = name_to_code ( tagtype , name... |
def main ( ) :
"Send some test strings" | actions = """
{LWIN}
{PAUSE .25}
r
{PAUSE .25}
Notepad.exe{ENTER}
{PAUSE 1}
Hello{SPACE}World!
{PAUSE 1}
%{F4}
{PAUSE .25}
n
"""
SendKeys ( actions , pause = .1 )
keys = parse_keys ( actions )
for k in keys :
print ( k )... |
def disconnect ( self , receipt = None , headers = None , ** keyword_headers ) :
""": param str receipt :
: param dict headers :
: param keyword _ headers :""" | Protocol12 . disconnect ( self , receipt , headers , ** keyword_headers )
self . transport . stop ( ) |
def resolve_model ( self , model ) :
'''Resolve a model given a name or dict with ` class ` entry .
: raises ValueError : model specification is wrong or does not exists''' | if not model :
raise ValueError ( 'Unsupported model specifications' )
if isinstance ( model , basestring ) :
classname = model
elif isinstance ( model , dict ) and 'class' in model :
classname = model [ 'class' ]
else :
raise ValueError ( 'Unsupported model specifications' )
try :
return get_docume... |
def _serialize_to_jvm ( self , data , serializer , reader_func , createRDDServer ) :
"""Using py4j to send a large dataset to the jvm is really slow , so we use either a file
or a socket if we have encryption enabled .
: param data :
: param serializer :
: param reader _ func : A function which takes a file... | if self . _encryption_enabled : # with encryption , we open a server in java and send the data directly
server = createRDDServer ( )
( sock_file , _ ) = local_connect_and_auth ( server . port ( ) , server . secret ( ) )
chunked_out = ChunkedStream ( sock_file , 8192 )
serializer . dump_stream ( data , c... |
def install ( which = None , mirror_url = None , destination = None , skip_top_level = False , resources_yaml = 'resources.yaml' ) :
"""Install one or more resources .
The resource ( s ) will be fetched , if necessary , and different resource
types are handled appropriately ( e . g . , PyPI resources are instal... | resources = _load ( resources_yaml , None )
return _install ( resources , which , mirror_url , destination , skip_top_level ) |
def _load_raw_data ( self , resource_name ) :
"""Extract raw data from resource
: param resource _ name :""" | # Instantiating the resource again as a simple ` Resource ` ensures that
# ` ` data ` ` will be returned as bytes .
upcast_resource = datapackage . Resource ( self . __resources [ resource_name ] . descriptor , default_base_path = self . __base_path )
return upcast_resource . data |
def get_void_volume_surfarea ( structure , rad_dict = None , chan_rad = 0.3 , probe_rad = 0.1 ) :
"""Computes the volume and surface area of isolated void using Zeo + + .
Useful to compute the volume and surface area of vacant site .
Args :
structure : pymatgen Structure containing vacancy
rad _ dict ( opti... | with ScratchDir ( '.' ) :
name = "temp_zeo"
zeo_inp_filename = name + ".cssr"
ZeoCssr ( structure ) . write_file ( zeo_inp_filename )
rad_file = None
if rad_dict :
rad_file = name + ".rad"
with open ( rad_file , 'w' ) as fp :
for el in rad_dict . keys ( ) :
... |
def get_mixed_type_key ( obj ) :
"""Return a key suitable for sorting between networks and addresses .
Address and Network objects are not sortable by default ; they ' re
fundamentally different so the expression
IPv4Address ( ' 192.0.2.0 ' ) < = IPv4Network ( ' 192.0.2.0/24 ' )
doesn ' t make any sense . T... | if isinstance ( obj , _BaseNetwork ) :
return obj . _get_networks_key ( )
elif isinstance ( obj , _BaseAddress ) :
return obj . _get_address_key ( )
return NotImplemented |
def rpc ( self , address , rpc_id , * args , ** kwargs ) :
"""Immediately dispatch an RPC inside this EmulatedDevice .
This function is meant to be used for testing purposes as well as by
tiles inside a complex EmulatedDevice subclass that need to
communicate with each other . It should only be called from th... | 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_format = kwargs . get ( 'resp_format' , None )
arg_payload = b''
if arg_format is not None :
arg_... |
def type ( self ) :
"""Returns a ` ` string ` ` constant to indicate whether the game was played
during the regular season or in the post season .""" | if self . _type . lower ( ) == 'reg' :
return REGULAR_SEASON
if self . _type . lower ( ) == 'ctourn' :
return CONFERENCE_TOURNAMENT
if self . _type . lower ( ) == 'ncaa' :
return NCAA_TOURNAMENT
if self . _type . lower ( ) == 'nit' :
return NIT_TOURNAMENT
if self . _type . lower ( ) == 'cbi' :
retur... |
def ancestor ( self , index ) :
"""Return the ` ` index ` ` - th ancestor .
The 0 - th ancestor is the node itself ,
the 1 - th ancestor is its parent node ,
etc .
: param int index : the number of levels to go up
: rtype : : class : ` ~ aeneas . tree . Tree `
: raises : TypeError if ` ` index ` ` is no... | if not isinstance ( index , int ) :
self . log_exc ( u"index is not an integer" , None , True , TypeError )
if index < 0 :
self . log_exc ( u"index cannot be negative" , None , True , ValueError )
parent_node = self
for i in range ( index ) :
if parent_node is None :
break
parent_node = parent_n... |
def _make_request_data ( self , teststep_dict , entry_json ) :
"""parse HAR entry request data , and make teststep request data
Args :
entry _ json ( dict ) :
" request " : {
" method " : " POST " ,
" postData " : {
" mimeType " : " application / x - www - form - urlencoded ; charset = utf - 8 " ,
" p... | method = entry_json [ "request" ] . get ( "method" )
if method in [ "POST" , "PUT" , "PATCH" ] :
postData = entry_json [ "request" ] . get ( "postData" , { } )
mimeType = postData . get ( "mimeType" )
# Note that text and params fields are mutually exclusive .
if "text" in postData :
post_data =... |
def _read_para_transaction_id ( self , code , cbit , clen , * , desc , length , version ) :
"""Read HIP TRANSACTION _ ID parameter .
Structure of HIP TRANSACTION _ ID parameter [ RFC 6078 ] :
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
| Type | Length |
| Identifier /
/ | Pad... | _tsid = self . _read_unpack ( clen )
transaction_id = dict ( type = desc , critical = cbit , length = clen , id = _tsid , )
_plen = length - clen
if _plen :
self . _read_fileng ( _plen )
return transaction_id |
def local_timezone ( value ) :
"""Add the local timezone to ` value ` to make it aware .""" | if hasattr ( value , "tzinfo" ) and value . tzinfo is None :
return value . replace ( tzinfo = dateutil . tz . tzlocal ( ) )
return value |
def parse_usearch61_failures ( seq_path , failures , output_fasta_fp ) :
"""Parses seq IDs from failures list , writes to output _ fasta _ fp
seq _ path : filepath of original input fasta file .
failures : list / set of failure seq IDs
output _ fasta _ fp : path to write parsed sequences""" | parsed_out = open ( output_fasta_fp , "w" )
for label , seq in parse_fasta ( open ( seq_path ) , "U" ) :
curr_label = label . split ( ) [ 0 ]
if curr_label in failures :
parsed_out . write ( ">%s\n%s\n" % ( label , seq ) )
parsed_out . close ( )
return output_fasta_fp |
def save ( self , wf_state ) :
"""write wf state to DB through MQ > > Worker > > _ zops _ sync _ wf _ cache
Args :
wf _ state dict : wf state""" | self . wf_state = wf_state
self . wf_state [ 'role_id' ] = self . current . role_id
self . set ( self . wf_state )
if self . wf_state [ 'name' ] not in settings . EPHEMERAL_WORKFLOWS :
self . publish ( job = '_zops_sync_wf_cache' , token = self . db_key ) |
def typelogged_func ( func ) :
"""Works like typelogged , but is only applicable to functions ,
methods and properties .""" | if not pytypes . typelogging_enabled :
return func
if hasattr ( func , 'do_logging' ) :
func . do_logging = True
return func
elif hasattr ( func , 'do_typecheck' ) : # actually shouldn ' t happen
return _typeinspect_func ( func , func . do_typecheck , True )
else :
return _typeinspect_func ( func , ... |
def search ( self , q , resolve = True , result_type = None , account_id = None , offset = None , min_id = None , max_id = None ) :
"""Fetch matching hashtags , accounts and statuses . Will perform webfinger
lookups if resolve is True . Full - text search is only enabled if
the instance supports it , and is res... | return self . search_v2 ( q , resolve = resolve , result_type = result_type , account_id = account_id , offset = offset , min_id = min_id , max_id = max_id ) |
def recursive_pattern_delete ( root , file_patterns , directory_patterns , dry_run = False ) :
"""Recursively deletes files matching a list of patterns . Same for directories""" | for root , dirs , files in os . walk ( root ) :
for pattern in file_patterns :
for file_name in fnmatch . filter ( files , pattern ) :
file_path = os . path . join ( root , file_name )
if dry_run :
print_ ( 'Removing {}' . format ( file_path ) )
contin... |
def lineincols ( inlist , colsize ) :
"""Returns a string composed of elements in inlist , with each element
right - aligned in columns of ( fixed ) colsize .
Usage : lineincols ( inlist , colsize ) where colsize is an integer""" | outstr = ''
for item in inlist :
if type ( item ) != StringType :
item = str ( item )
size = len ( item )
if size <= colsize :
for i in range ( colsize - size ) :
outstr = outstr + ' '
outstr = outstr + item
else :
outstr = outstr + item [ 0 : colsize + 1 ]
re... |
def _to_dot_key ( cls , section , key = None ) :
"""Return the section and key in dot notation format .""" | if key :
return ( NON_ALPHA_NUM . sub ( '_' , section . lower ( ) ) , NON_ALPHA_NUM . sub ( '_' , key . lower ( ) ) )
else :
return NON_ALPHA_NUM . sub ( '_' , section . lower ( ) ) |
def get_shipping_cost ( settings , country_code = None , name = None ) :
"""Return the shipping cost for a given country code and shipping option ( shipping rate name )""" | shipping_rate = None
if settings . default_shipping_enabled :
shipping_rate = { "rate" : settings . default_shipping_rate , "description" : "Standard shipping to rest of world" , "carrier" : settings . default_shipping_carrier }
elif not country_code :
raise InvalidShippingCountry
if country_code :
qrs = mo... |
def disableTemperature ( self ) :
"""Specifies the device should NOT write temperature values to the FIFO , is not applied until enableFIFO is called .
: return :""" | logger . debug ( "Disabling temperature sensor" )
self . fifoSensorMask &= ~ self . enableTemperatureMask
self . _setSampleSizeBytes ( ) |
def _GetPurgeMessage ( most_recent_step , most_recent_wall_time , event_step , event_wall_time , num_expired ) :
"""Return the string message associated with TensorBoard purges .""" | return ( 'Detected out of order event.step likely caused by a TensorFlow ' 'restart. Purging {} expired tensor events from Tensorboard display ' 'between the previous step: {} (timestamp: {}) and current step: {} ' '(timestamp: {}).' ) . format ( num_expired , most_recent_step , most_recent_wall_time , event_step , eve... |
def get_stream_action_type ( stream_arn ) :
"""Returns the awacs Action for a stream type given an arn
Args :
stream _ arn ( str ) : The Arn of the stream .
Returns :
: class : ` awacs . aws . Action ` : The appropriate stream type awacs Action
class
Raises :
ValueError : If the stream type doesn ' t ... | stream_type_map = { "kinesis" : awacs . kinesis . Action , "dynamodb" : awacs . dynamodb . Action , }
stream_type = stream_arn . split ( ":" ) [ 2 ]
try :
return stream_type_map [ stream_type ]
except KeyError :
raise ValueError ( "Invalid stream type '%s' in arn '%s'" % ( stream_type , stream_arn ) ) |
def get_connection ( self ) :
"""Return a connection from the pool using the ` ConnectionSelector `
instance .
It tries to resurrect eligible connections , forces a resurrection when
no connections are availible and passes the list of live connections to
the selector instance to choose from .
Returns a co... | self . resurrect ( )
connections = self . connections [ : ]
# no live nodes , resurrect one by force and return it
if not connections :
return self . resurrect ( True )
# only call selector if we have a selection
if len ( connections ) > 1 :
return self . selector . select ( connections )
# only one connection ... |
def get_vmpolicy_macaddr_input_datacenter ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vmpolicy_macaddr = ET . Element ( "get_vmpolicy_macaddr" )
config = get_vmpolicy_macaddr
input = ET . SubElement ( get_vmpolicy_macaddr , "input" )
datacenter = ET . SubElement ( input , "datacenter" )
datacenter . text = kwargs . pop ( 'datacenter' )
callback = kwargs . pop ( 'ca... |
def send_and_receive_raw ( self , target , lun , netfn , raw_bytes ) :
"""Interface function to send and receive raw message .
target : IPMI target
lun : logical unit number
netfn : network function
raw _ bytes : RAW bytes as bytestring
Returns the IPMI message response bytestring .""" | return self . _send_and_receive ( target = target , lun = lun , netfn = netfn , cmdid = array ( 'B' , raw_bytes ) [ 0 ] , payload = raw_bytes [ 1 : ] ) |
def eth_getBlockHeaderByNumber ( self , number ) :
"""Get block header by block number .
: param number :
: return :""" | block_hash = self . reader . _get_block_hash ( number )
block_number = _format_block_number ( number )
return self . reader . _get_block_header ( block_hash , block_number ) |
def construct_xblock_from_class ( self , cls , scope_ids , field_data = None , * args , ** kwargs ) :
"""Construct a new xblock of type cls , mixing in the mixins
defined for this application .""" | return self . mixologist . mix ( cls ) ( runtime = self , field_data = field_data , scope_ids = scope_ids , * args , ** kwargs ) |
def compile_link_import_strings ( codes , build_dir = None , ** kwargs ) :
"""Creates a temporary directory and dumps , compiles and links
provided source code .
Parameters
codes : iterable of name / source pair tuples
build _ dir : string ( default : None )
path to cache _ dir . None implies use a tempor... | build_dir = build_dir or tempfile . mkdtemp ( )
if not os . path . isdir ( build_dir ) :
raise OSError ( "Non-existent directory: " , build_dir )
source_files = [ ]
if kwargs . get ( 'logger' , False ) is True :
import logging
logging . basicConfig ( level = logging . DEBUG )
kwargs [ 'logger' ] = loggi... |
def clone_and_update ( self , ** kwargs ) :
"""Clones the object and updates the clone with the args
@ param kwargs : Keyword arguments to set
@ return : The cloned copy with updated values""" | cloned = self . clone ( )
cloned . update ( ** kwargs )
return cloned |
def is_valid ( container , path ) :
"""Checks if a container exists and is unpacked .
Args :
path : The location where the container is expected .
Returns :
True if the container is valid , False if the container needs to
unpacked or if the path does not exist yet .""" | try :
tmp_hash_path = container . filename + ".hash"
with open ( tmp_hash_path , 'r' ) as tmp_file :
tmp_hash = tmp_file . readline ( )
except IOError :
LOG . info ( "No .hash-file in the tmp-directory." )
container_hash_path = local . path ( path ) / "gentoo.tar.bz2.hash"
if container_hash_path . e... |
def _load ( module , globals_dict = None , symb_list = None ) :
"""Loads a Python module to make variables , objects and functions
available globally .
The idea is to load the module using importlib , then copy the
symbols to the global symbol table .""" | if globals_dict is None :
globals_dict = six . moves . builtins . __dict__
try :
mod = importlib . import_module ( module )
if '__all__' in mod . __dict__ : # import listed symbols
for name in mod . __dict__ [ '__all__' ] :
if symb_list is not None :
symb_list . append ( ... |
def read_10xgenomics ( cls , tarball_fpath : str , prefix : str , use_ensembl_ids : bool = False ) :
"""Read a 10X genomics compressed tarball containing expression data .
Note : common prefix patterns :
- " filtered _ gene _ bc _ matrices / [ annotations ] / "
- " filtered _ matrices _ mex / [ annotations ] ... | _LOGGER . info ( 'Reading file: %s' , tarball_fpath )
with tarfile . open ( tarball_fpath , mode = 'r:gz' ) as tf :
ti = tf . getmember ( '%smatrix.mtx' % prefix )
with tf . extractfile ( ti ) as fh :
mtx = scipy . io . mmread ( fh )
ti = tf . getmember ( '%sgenes.tsv' % prefix )
with tf . extra... |
def getMultiSeriesRegistrations ( self , q_filter = Q ( ) , name_series = False , ** kwargs ) :
'''Use the getSeriesRegistered method above to get a list of each series the
person has registered for . The return only indicates whether they are
registered more than once for the same series ( e . g . for keeping ... | series_registered = self . getSeriesRegistered ( q_filter , distinct = False , counter = False , ** kwargs )
counter_items = Counter ( series_registered ) . items ( )
multireg_list = [ x for x in counter_items if x [ 1 ] > 1 ]
if name_series and multireg_list :
if 'year' in kwargs or 'month' in kwargs :
ret... |
def acp_account ( ) :
"""Manage the user account of currently - logged - in users .
This does NOT accept admin - specific options .""" | if request . args . get ( 'status' ) == 'pwdchange' :
alert = 'You must change your password before proceeding.'
alert_status = 'danger'
pwdchange_skip = True
else :
alert = ''
alert_status = ''
pwdchange_skip = False
if db is None :
form = PwdHashForm ( )
return render ( 'coil_account_s... |
def retrieve_last_elements ( sublists ) :
"""A Python function which returns the final element from each sublist within a provided list .
Examples :
> > > retrieve _ last _ elements ( [ [ 1 , 2 , 3 ] , [ 4 , 5 ] , [ 6 , 7 , 8 , 9 ] ] )
[3 , 5 , 9]
> > > retrieve _ last _ elements ( [ [ ' x ' , ' y ' , ' z '... | return [ sublist [ - 1 ] for sublist in sublists ] |
def currentpath ( self ) -> str :
"""Absolute path of the current working directory .
> > > from hydpy . core . filetools import FileManager
> > > filemanager = FileManager ( )
> > > filemanager . BASEDIR = ' basename '
> > > filemanager . projectdir = ' projectname '
> > > from hydpy import repr _ , Test... | return os . path . join ( self . basepath , self . currentdir ) |
def popitem ( self ) :
"""Remove oldest key from dict and return item .""" | if self . _keys :
k = self . _keys [ 0 ]
v = self [ k ]
del self [ k ]
return ( k , v )
raise KeyError ( "popitem() on empty dictionary" ) |
def deserialize ( doc_xml , pyxb_binding = None ) :
"""Deserialize DataONE XML types to PyXB .
Args :
doc _ xml : UTF - 8 encoded ` ` bytes ` `
pyxb _ binding : PyXB binding object . If not specified , the correct one should be
selected automatically .
Returns :
PyXB object
See Also :
` ` deserializ... | pyxb_binding = pyxb_binding or d1_common . types . dataoneTypes
try :
return pyxb_binding . CreateFromDocument ( doc_xml )
except pyxb . ValidationError as e :
raise ValueError ( 'Unable to deserialize XML to PyXB. error="{}" xml="{}"' . format ( e . details ( ) , doc_xml ) )
except ( pyxb . PyXBException , xml... |
def url ( self , value ) :
"""Setter for * * self . _ _ url * * attribute .
: param value : Attribute value .
: type value : unicode""" | if value is not None :
assert type ( value ) is unicode , "'{0}' attribute: '{1}' type is not 'unicode'!" . format ( "url" , value )
self . __url = value |
def try_it_n_times ( operation , expected_error_codes , custom_error = 'operation failed' , n = 10 ) :
"""Try a given operation ( API call ) n times .
Raises if the API call fails with an error _ code that is not expected .
Raises if the API call has not succeeded within n attempts .
Waits 3 seconds betwee ea... | for i in itertools . count ( ) :
try :
operation ( )
break
except UpCloudAPIError as e :
if e . error_code not in expected_error_codes :
raise e
sleep ( 3 )
if i >= n - 1 :
raise UpCloudClientError ( custom_error ) |
def dad_status_output_dad_status_entries_index ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
dad_status = ET . Element ( "dad_status" )
config = dad_status
output = ET . SubElement ( dad_status , "output" )
dad_status_entries = ET . SubElement ( output , "dad-status-entries" )
index = ET . SubElement ( dad_status_entries , "index" )
index . text = kwargs . pop ( 'index' )
cal... |
def _check_signal ( self , s ) :
r"""Check if signal is valid .""" | s = np . asanyarray ( s )
if s . shape [ 0 ] != self . n_vertices :
raise ValueError ( 'First dimension must be the number of vertices ' 'G.N = {}, got {}.' . format ( self . N , s . shape ) )
return s |
def underlying_variable_ref ( t ) :
"""Find the underlying variable ref .
Traverses through Identity , ReadVariableOp , and Enter ops .
Stops when op type has Variable or VarHandle in name .
Args :
t : a Tensor
Returns :
a Tensor that is a variable ref , or None on error .""" | while t . op . type in [ "Identity" , "ReadVariableOp" , "Enter" ] :
t = t . op . inputs [ 0 ]
op_type = t . op . type
if "Variable" in op_type or "VarHandle" in op_type :
return t
else :
return None |
def page_exists_on_disk ( self , slug ) :
'''Return true if post directory and post file both exist .''' | r = False
page_dir = os . path . join ( self . dirs [ 'source' ] , slug )
page_file_name = os . path . join ( page_dir , slug + '.md' )
if os . path . isdir ( page_dir ) :
if os . path . isfile ( page_file_name ) :
r = True
return r |
def render_attrs ( attrs ) :
"""Render HTML attributes , or return ' ' if no attributes needs to be rendered .""" | if attrs is not None :
def parts ( ) :
for key , value in sorted ( attrs . items ( ) ) :
if value is None :
continue
if value is True :
yield '%s' % ( key , )
continue
if key == 'class' and isinstance ( value , dict ) :
... |
def _task_complete ( self , ** kwargs ) :
"""Performs cleanup tasks and notifies Job that the Task finished .""" | logger . debug ( 'Running _task_complete for task {0}' . format ( self . name ) )
with self . parent_job . completion_lock :
self . completed_at = datetime . utcnow ( )
self . successful = kwargs . get ( 'success' , None )
self . parent_job . _complete_task ( self . name , ** kwargs ) |
def get_item ( self , item_type , id ) :
'''Get the an item response for the given item _ type and id
: param item _ type str : A valid item - type
: param id str : The id of the item
: returns : : py : Class : ` planet . api . models . JSON `
: raises planet . api . exceptions . APIException : On API error... | url = 'data/v1/item-types/%s/items/%s' % ( item_type , id )
return self . _get ( url ) . get_body ( ) |
def _validate_isvalid_history ( self , isvalid_history , field , value ) :
"""Checks that the given time history is properly formatted .
Args :
isvalid _ history ( ` bool ` ) : flag from schema indicating units to be checked .
field ( ` str ` ) : property associated with history in question .
value ( ` dict... | # Check the type has appropriate units
history_type = value [ 'type' ]
if history_type . endswith ( 'emission' ) :
history_type = 'emission'
elif history_type . endswith ( 'absorption' ) :
history_type = 'absorption'
quantity = 1.0 * ( units ( value [ 'quantity' ] [ 'units' ] ) )
try :
quantity . to ( prope... |
def get_raw_exception_record_list ( self ) :
"""Traverses the exception record linked list and builds a Python list .
Nested exception records are received for nested exceptions . This
happens when an exception is raised in the debugee while trying to
handle a previous exception .
@ rtype : list ( L { win32... | # The first EXCEPTION _ RECORD is contained in EXCEPTION _ DEBUG _ INFO .
# The remaining EXCEPTION _ RECORD structures are linked by pointers .
nested = list ( )
record = self . raw . u . Exception
while True :
record = record . ExceptionRecord
if not record :
break
nested . append ( record )
retur... |
def add_dependent_work_units ( self , work_unit , depends_on , hard = True ) :
"""Add work units , where one prevents execution of the other .
The two work units may be attached to different work specs ,
but both must be in this task master ' s namespace . ` work _ unit `
and ` depends _ on ` are both tuples ... | # There ' s no good , not - confusing terminology here .
# I ' ll call work _ unit " later " and depends _ on " earlier "
# consistently , because that at least makes the time flow
# correct .
later_spec , later_unit , later_unitdef = work_unit
earlier_spec , earlier_unit , earlier_unitdef = depends_on
with self . regi... |
def check_lt ( self ) :
"""Check is the POSTed LoginTicket is valid , if yes invalide it
: return : ` ` True ` ` if the LoginTicket is valid , ` ` False ` ` otherwise
: rtype : bool""" | # save LT for later check
lt_valid = self . request . session . get ( 'lt' , [ ] )
lt_send = self . request . POST . get ( 'lt' )
# generate a new LT ( by posting the LT has been consumed )
self . gen_lt ( )
# check if send LT is valid
if lt_send not in lt_valid :
return False
else :
self . request . session [ ... |
def nodes ( self ) :
"""A | Nodes | collection of all required nodes .
> > > from hydpy import RiverBasinNumbers2Selection
> > > rbns2s = RiverBasinNumbers2Selection (
. . . ( 111 , 113 , 1129 , 11269 , 1125 , 11261,
. . . 11262 , 1123 , 1124 , 1122 , 1121 ) )
Note that the required outlet node is added :... | return ( devicetools . Nodes ( self . node_prefix + routers for routers in self . _router_numbers ) + devicetools . Node ( self . last_node ) ) |
def get_display_label ( choices , status ) :
"""Get a display label for resource status .
This method is used in places where a resource ' s status or
admin state labels need to assigned before they are sent to the
view template .""" | for ( value , label ) in choices :
if value == ( status or '' ) . lower ( ) :
display_label = label
break
else :
display_label = status
return display_label |
def get_super_assignment ( pyname ) :
""": type pyname : rope . base . pynamesdef . AssignedName
: type : rope . base . pynamesdef . AssignedName""" | try :
pyclass , attr_name = get_class_with_attr_name ( pyname )
except TypeError :
return
else :
for super_pyclass in get_mro ( pyclass ) [ 1 : ] :
if attr_name in super_pyclass :
return super_pyclass [ attr_name ] |
def _write ( self , session , openFile , replaceParamFile = None ) :
"""ProjectFileEvent Write to File Method""" | openFile . write ( text ( yaml . dump ( [ evt . as_yml ( ) for evt in self . events . order_by ( ProjectFileEvent . name , ProjectFileEvent . subfolder ) ] ) ) ) |
def stream_gzip_decompress_lines ( stream ) :
"""Uncompress a gzip stream into lines of text .
Parameters
Generator of chunks of gzip compressed text .
Returns
Generator of uncompressed lines .""" | dec = zlib . decompressobj ( zlib . MAX_WBITS | 16 )
previous = ""
for compressed_chunk in stream :
chunk = dec . decompress ( compressed_chunk ) . decode ( )
if chunk :
lines = ( previous + chunk ) . split ( "\n" )
previous = lines . pop ( )
for line in lines :
yield line
yi... |
def generate_transpose ( node_name , in_name , out_name , axes , base_name , func_counter ) :
"""Generate a Transpose operator to transpose the specified buffer .""" | trans = nnabla_pb2 . Function ( )
trans . type = "Transpose"
set_function_name ( trans , node_name , base_name , func_counter )
trans . input . extend ( [ in_name ] )
trans . output . extend ( [ out_name ] )
tp = trans . transpose_param
tp . axes . extend ( axes )
return trans |
def calculate_rate ( country_code , exception_name ) :
"""Calculates the VAT rate for a customer based on their declared country
and any declared exception information .
: param country _ code :
The two - character country code where the user resides
: param exception _ name :
The name of an exception for... | if not country_code or not isinstance ( country_code , str_cls ) or len ( country_code ) != 2 :
raise ValueError ( 'Invalidly formatted country code' )
if exception_name and not isinstance ( exception_name , str_cls ) :
raise ValueError ( 'Exception name is not None or a string' )
country_code = country_code . ... |
def table_lookup ( image , table , border_value , iterations = None ) :
'''Perform a morphological transform on an image , directed by its neighbors
image - a binary image
table - a 512 - element table giving the transform of each pixel given
the values of that pixel and its 8 - connected neighbors .
border... | # Test for a table that never transforms a zero into a one :
center_is_zero = np . array ( [ ( x & 2 ** 4 ) == 0 for x in range ( 2 ** 9 ) ] )
use_index_trick = False
if ( not np . any ( table [ center_is_zero ] ) and ( np . issubdtype ( image . dtype , bool ) or np . issubdtype ( image . dtype , int ) ) ) : # Use the ... |
def resolve_compound_variable_fields ( dbg , thread_id , frame_id , scope , attrs ) :
"""Resolve compound variable in debugger scopes by its name and attributes
: param thread _ id : id of the variable ' s thread
: param frame _ id : id of the variable ' s frame
: param scope : can be BY _ ID , EXPRESSION , G... | var = getVariable ( dbg , thread_id , frame_id , scope , attrs )
try :
_type , _typeName , resolver = get_type ( var )
return _typeName , resolver . get_dictionary ( var )
except :
pydev_log . exception ( 'Error evaluating: thread_id: %s\nframe_id: %s\nscope: %s\nattrs: %s.' , thread_id , frame_id , scope ,... |
def Authenticate ( self , app_id , challenge_data , print_callback = sys . stderr . write ) :
"""See base class .""" | # Ensure environment variable is present
plugin_cmd = os . environ . get ( SK_SIGNING_PLUGIN_ENV_VAR )
if plugin_cmd is None :
raise errors . PluginError ( '{} env var is not set' . format ( SK_SIGNING_PLUGIN_ENV_VAR ) )
# Prepare input to signer
client_data_map , signing_input = self . _BuildPluginRequest ( app_id... |
def by_col ( cls , df , events , populations , w = None , inplace = False , pvalue = 'sim' , outvals = None , swapname = '' , ** stat_kws ) :
"""Function to compute a Moran _ Rate statistic on a dataframe
Arguments
df : pandas . DataFrame
a pandas dataframe with a geometry column
events : string or list of ... | if not inplace :
new = df . copy ( )
cls . by_col ( new , events , populations , w = w , inplace = True , pvalue = pvalue , outvals = outvals , swapname = swapname , ** stat_kws )
return new
if isinstance ( events , str ) :
events = [ events ]
if isinstance ( populations , str ) :
populations = [ po... |
def processLedger ( self ) -> None :
"""Checks ledger config txns and perfomes recent one
: return :""" | logger . debug ( '{} processing config ledger for any POOL_CONFIGs' . format ( self ) , extra = { "tags" : [ "pool-config" ] } )
for _ , txn in self . ledger . getAllTxn ( ) :
if get_type ( txn ) == POOL_CONFIG :
self . handleConfigTxn ( txn ) |
def env_get ( context ) :
"""Get $ ENVs into the pypyr context .
Context is a dictionary or dictionary - like . context is mandatory .
context [ ' env ' ] [ ' get ' ] must exist . It ' s a dictionary .
Values are the names of the $ ENVs to write to the pypyr context .
Keys are the pypyr context item to whic... | get = context [ 'env' ] . get ( 'get' , None )
exists = False
if get :
logger . debug ( "start" )
for k , v in get . items ( ) :
logger . debug ( f"setting context {k} to $ENV {v}" )
context [ k ] = os . environ [ v ]
logger . info ( f"saved {len(get)} $ENVs to context." )
exists = True
... |
def build_model_classes ( metadata ) :
"""Generate a model class for any models contained in the specified spec file .""" | i = importlib . import_module ( metadata )
env = get_jinja_env ( )
model_template = env . get_template ( 'model.py.jinja2' )
for model in i . models :
with open ( model_path ( model . name . lower ( ) ) , 'w' ) as t :
t . write ( model_template . render ( model_md = model ) ) |
def forward ( self , layer_input : torch . Tensor , layer_output : torch . Tensor , layer_index : int = None , total_layers : int = None ) -> torch . Tensor : # pylint : disable = arguments - differ
"""Apply dropout to this layer , for this whole mini - batch .
dropout _ prob = layer _ index / total _ layers * un... | if layer_index is not None and total_layers is not None :
dropout_prob = 1.0 * self . undecayed_dropout_prob * layer_index / total_layers
else :
dropout_prob = 1.0 * self . undecayed_dropout_prob
if self . training :
if torch . rand ( 1 ) < dropout_prob :
return layer_input
else :
return... |
def clone ( self ) : # TODO : check docstring
"""Returns a deep copy of self
Function clones :
* allocation
* nodes
Returns
type
Deep copy of self""" | new_node = self . __class__ ( self . _name , self . _demand )
return new_node |
def enable ( app_id , enabled = True ) :
'''Enable or disable an existing assistive access application .
app _ id
The bundle ID or command to set assistive access status .
enabled
Sets enabled or disabled status . Default is ` ` True ` ` .
CLI Example :
. . code - block : : bash
salt ' * ' assistive .... | enable_str = '1' if enabled else '0'
for a in _get_assistive_access ( ) :
if app_id == a [ 0 ] :
cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' '"UPDATE access SET allowed=\'{0}\' WHERE client=\'{1}\'"' . format ( enable_str , app_id )
call = __salt__ [ 'cmd.run_all' ] ( cmd , ... |
def get_serializer_in ( self , * args , ** kwargs ) :
"""Return the serializer instance that should be used for validating and
deserializing input , and for serializing output .""" | serializer_class = self . get_serializer_class_in ( )
kwargs [ 'context' ] = self . get_serializer_context ( )
return serializer_class ( * args , ** kwargs ) |
def get_password_data ( name = None , kwargs = None , instance_id = None , call = None , ) :
'''Return password data for a Windows instance .
By default only the encrypted password data will be returned . However , if a
key _ file is passed in , then a decrypted password will also be returned .
Note that the ... | if call != 'action' :
raise SaltCloudSystemExit ( 'The get_password_data action must be called with ' '-a or --action.' )
if not instance_id :
instance_id = _get_node ( name ) [ 'instanceId' ]
if kwargs is None :
kwargs = { }
if instance_id is None :
if 'instance_id' in kwargs :
instance_id = kw... |
def add_values_to_run_set_xml ( self , runSet , cputime , walltime , energy ) :
"""This function adds the result values to the XML representation of a runSet .""" | self . add_column_to_xml ( runSet . xml , 'cputime' , cputime )
self . add_column_to_xml ( runSet . xml , 'walltime' , walltime )
energy = intel_cpu_energy . format_energy_results ( energy )
for energy_key , energy_value in energy . items ( ) :
self . add_column_to_xml ( runSet . xml , energy_key , energy_value ) |
def register_bool_option ( cls , name , description = None ) :
"""Register a Boolean switch as state option .
This is equivalent to cls . register _ option ( name , set ( [ bool ] ) , description = description )
: param str name : Name of the state option .
: param str description : The description of this st... | cls . register_option ( name , { bool } , default = False , description = description ) |
def value_nth_person ( self , n , array , default = 0 ) :
"""Get the value of array for the person whose position in the entity is n .
Note that this position is arbitrary , and that members are not sorted .
If the nth person does not exist , return ` ` default ` ` instead .
The result is a vector which dimen... | self . members . check_array_compatible_with_entity ( array )
positions = self . members_position
nb_persons_per_entity = self . nb_persons ( )
members_map = self . ordered_members_map
result = self . filled_array ( default , dtype = array . dtype )
# For households that have at least n persons , set the result as the ... |
def _find_elements ( self , result , elements ) :
"""Find interesting elements from XML .
This function tries to only look for specified elements
without parsing the entire XML . The specified elements is better
located near the beginning .
Args :
result : response XML .
elements : a set of interesting ... | element_mapping = { }
result = StringIO . StringIO ( result )
for _ , e in ET . iterparse ( result , events = ( 'end' , ) ) :
if not elements :
break
if e . tag in elements :
element_mapping [ e . tag ] = e . text
elements . remove ( e . tag )
return element_mapping |
def on ( self ) :
"""Send ON command to device .""" | on_command = StandardSend ( self . _address , COMMAND_LIGHT_ON_0X11_NONE , 0xff )
self . _send_method ( on_command , self . _on_message_received ) |
def get_child_ids ( self , parent_alias ) :
"""Returns child IDs of the given parent category
: param str parent _ alias : Parent category alias
: rtype : list
: return : a list of child IDs""" | self . _cache_init ( )
return self . _cache_get_entry ( self . CACHE_NAME_PARENTS , parent_alias , [ ] ) |
def do_get ( self , params ) :
"""\x1b [1mNAME \x1b [0m
get - Gets the znode ' s value
\x1b [1mSYNOPSIS \x1b [0m
get < path > [ watch ]
\x1b [1mOPTIONS \x1b [0m
* watch : set a ( data ) watch on the path ( default : false )
\x1b [1mEXAMPLES \x1b [0m
> get / foo
bar
# sets a watch
> get / foo tru... | watcher = lambda evt : self . show_output ( str ( evt ) )
kwargs = { "watch" : watcher } if params . watch else { }
value , _ = self . _zk . get ( params . path , ** kwargs )
# maybe it ' s compressed ?
if value is not None :
try :
value = zlib . decompress ( value )
except :
pass
self . show_ou... |
def component_for_entity ( self , entity : int , component_type : Type [ C ] ) -> C :
"""Retrieve a Component instance for a specific Entity .
Retrieve a Component instance for a specific Entity . In some cases ,
it may be necessary to access a specific Component instance .
For example : directly modifying a ... | return self . _entities [ entity ] [ component_type ] |
def seq_dup_levels_plot ( self ) :
"""Create the HTML for the Sequence Duplication Levels plot""" | data = dict ( )
max_dupval = 0
for s_name in self . fastqc_data :
try :
thisdata = { }
for d in self . fastqc_data [ s_name ] [ 'sequence_duplication_levels' ] :
thisdata [ d [ 'duplication_level' ] ] = d [ 'percentage_of_total' ]
max_dupval = max ( max_dupval , d [ 'percenta... |
def edit_dataset_metadata ( request , dataset_id = None ) :
"""Renders a template to upload or edit a Dataset .
Most of the heavy lifting is done by add _ dataset ( . . . ) .""" | if request . method == 'POST' :
return add_dataset ( request , dataset_id )
elif request . method == 'GET' : # create a blank form
# Edit
if dataset_id :
metadata_form = DatasetUploadForm ( instance = get_object_or_404 ( Dataset , pk = dataset_id ) )
# Upload
else :
metadata_form = Datas... |
def user_segment ( self ) :
"""| Comment : The id of the user segment to which this section belongs""" | if self . api and self . user_segment_id :
return self . api . _get_user_segment ( self . user_segment_id ) |
def decorator_handle ( tokens ) :
"""Process decorators .""" | defs = [ ]
decorates = [ ]
for i , tok in enumerate ( tokens ) :
if "simple" in tok and len ( tok ) == 1 :
decorates . append ( "@" + tok [ 0 ] )
elif "test" in tok and len ( tok ) == 1 :
varname = decorator_var + "_" + str ( i )
defs . append ( varname + " = " + tok [ 0 ] )
deco... |
def terminal ( self , out = None , border = None ) :
"""Serializes the sequence of QR Codes as ANSI escape code .
See : py : meth : ` QRCode . terminal ( ) ` for details .""" | for qrcode in self :
qrcode . terminal ( out = out , border = border ) |
def is_topic_head ( self ) :
"""Returns ` ` True ` ` if the post is the first post of the topic .""" | return self . topic . first_post . id == self . id if self . topic . first_post else False |
def set_timer ( self , duration ) :
"""Setup the next alarm to fire and then wait for it to fire .
: param int duration : How long to sleep""" | # Make sure that the application is not shutting down before sleeping
if self . is_shutting_down :
LOGGER . debug ( 'Not sleeping, application is trying to shutdown' )
return
# Set the signal timer
signal . setitimer ( signal . ITIMER_REAL , duration , 0 ) |
def purge_stale_services ( argv = None ) :
"""Command - line utility to periodically purge stale entries from the " services " table .
It is designed to be used in conjunction with cron .""" | argv = argv or sys . argv
arg_parser = argparse . ArgumentParser ( prog = os . path . basename ( argv [ 0 ] ) , description = ( 'doublethink-purge-stale-services: utility to periodically ' 'purge stale entries from the "services" table.' ) )
arg_parser . add_argument ( "-d" , "--rethinkdb-db" , required = True , dest =... |
def fillna ( self , value ) :
"""Returns Index with missing values replaced with value .
Parameters
value : { int , float , bytes , bool }
Scalar value to replace missing values with .
Returns
Index
With missing values replaced .""" | if not is_scalar ( value ) :
raise TypeError ( 'Value to replace with is not a valid scalar' )
return Index ( weld_replace ( self . weld_expr , self . weld_type , default_missing_data_literal ( self . weld_type ) , value ) , self . dtype , self . name ) |
def value_or_default ( self , value ) :
'''Returns the given value or the specified default value for this
field''' | if value is None :
if callable ( self . default ) :
return self . default ( )
else :
return self . default
return value |
def _create_html_tasklist ( self , taskpaperDocPath ) :
"""* create an html version of the single taskpaper index task list *
* * Key Arguments : * *
- ` ` taskpaperDocPath ` ` - - path to the task index taskpaper doc
* * Return : * *
- ` ` htmlFilePath ` ` - - the path to the output HTML file""" | self . log . info ( 'starting the ``_create_html_tasklist`` method' )
if self . editorialRootPath :
return
title = self . workspaceName
content = "<h1>%(title)s tasks</h1><ul>\n" % locals ( )
# OPEN TASKPAPER FILE
doc = document ( taskpaperDocPath )
docTasks = doc . tasks
for task in docTasks :
tagString = " " ... |
def get_value ( self , variable = None ) :
"""Gets given environment variable value .
: param variable : Variable to retrieve value .
: type variable : unicode
: return : Variable value .
: rtype : unicode
: note : If the * * variable * * argument is not given the first * * self . _ _ variables * * attrib... | if variable :
self . get_values ( variable )
return self . __variables [ variable ]
else :
self . get_values ( )
return foundations . common . get_first_item ( self . __variables . values ( ) ) |
def pause_point ( self , msg = 'SHUTIT PAUSE POINT' , print_input = True , resize = True , color = '32' , default_msg = None , interact = False , wait = - 1 ) :
"""Inserts a pause in the build session , which allows the user to try
things out before continuing . Ignored if we are not in an interactive
mode .
... | shutit = self . shutit
# Try and stop user being ' clever ' if we are in an exam and not in debug
if shutit . build [ 'exam' ] and shutit . loglevel not in ( 'DEBUG' , ) :
self . send ( ShutItSendSpec ( self , send = ' command alias exit=/bin/true && command alias logout=/bin/true && command alias kill=/bin/true &&... |
def _set_collector ( self , v , load = False ) :
"""Setter method for collector , mapped from YANG variable / telemetry / collector ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ collector is considered as a private
method . Backends looking to populate this... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "collector_name" , collector . collector , yang_name = "collector" , rest_name = "collector" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'col... |
def setup_step_out ( self , frame ) :
"""Setup debugger for a " stepOut " """ | self . frame_calling = None
self . frame_stop = None
self . frame_return = frame . f_back
self . frame_suspend = False
self . pending_stop = True
return |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.