signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _prune ( self ) :
"""Primitive way to keep dict in sync with RB .""" | delkeys = [ k for k in self . keys ( ) if k not in self . __ringbuffer ]
for k in delkeys : # necessary because dict is changed during iterations
super ( KRingbuffer , self ) . __delitem__ ( k ) |
def IsDirectory ( self ) :
"""Determines if the file entry is a directory .
Returns :
bool : True if the file entry is a directory .""" | if self . _stat_object is None :
self . _stat_object = self . _GetStat ( )
if self . _stat_object is not None :
self . entry_type = self . _stat_object . type
return self . entry_type == definitions . FILE_ENTRY_TYPE_DIRECTORY |
def _get_vispy_font_filename ( face , bold , italic ) :
"""Fetch a remote vispy font""" | name = face + '-'
name += 'Regular' if not bold and not italic else ''
name += 'Bold' if bold else ''
name += 'Italic' if italic else ''
name += '.ttf'
return load_data_file ( 'fonts/%s' % name ) |
def _do_perform_delete_on_model ( self ) :
"""Perform the actual delete query on this model instance .""" | if self . _force_deleting :
return self . with_trashed ( ) . where ( self . get_key_name ( ) , self . get_key ( ) ) . force_delete ( )
return self . _run_soft_delete ( ) |
def remove_from_group ( self , group , user ) :
"""Remove a user from a group
: type user : str
: param user : User ' s email
: type group : str
: param group : Group name
: rtype : dict
: return : an empty dictionary""" | data = { 'group' : group , 'user' : user }
return self . post ( 'removeUserFromGroup' , data ) |
def get_source_name ( self , src_id ) :
"""Returns the name of the given source .""" | len_out = _ffi . new ( 'unsigned int *' )
rv = rustcall ( _lib . lsm_view_get_source_name , self . _get_ptr ( ) , src_id , len_out )
if rv :
return decode_rust_str ( rv , len_out [ 0 ] ) |
def overlap ( listA , listB ) :
"""Return list of objects shared by listA , listB .""" | if ( listA is None ) or ( listB is None ) :
return [ ]
else :
return list ( set ( listA ) & set ( listB ) ) |
def debounce ( self , wait , immediate = None ) :
"""Returns a function , that , as long as it continues to be invoked ,
will not be triggered . The function will be called after it stops
being called for N milliseconds . If ` immediate ` is passed , trigger
the function on the leading edge , instead of the t... | wait = ( float ( wait ) / float ( 1000 ) )
def debounced ( * args , ** kwargs ) :
def call_it ( ) :
self . obj ( * args , ** kwargs )
try :
debounced . t . cancel ( )
except ( AttributeError ) :
pass
debounced . t = Timer ( wait , call_it )
debounced . t . start ( )
return se... |
def _t_run_reactive ( self , x ) :
"""Repeatedly updates transient ' A ' , ' b ' , and the solution guess within
each time step according to the applied source term then calls ' _ solve '
to solve the resulting system of linear equations . Stops when the
residual falls below ' r _ tolerance ' .
Parameters
... | if x is None :
x = np . zeros ( shape = [ self . Np , ] , dtype = float )
self [ self . settings [ 'quantity' ] ] = x
relax = self . settings [ 'relaxation_quantity' ]
res = 1e+06
for itr in range ( int ( self . settings [ 'max_iter' ] ) ) :
if res >= self . settings [ 'r_tolerance' ] :
logger . info ( ... |
def plot_cumulative_returns_by_quantile ( quantile_returns , period , freq , ax = None ) :
"""Plots the cumulative returns of various factor quantiles .
Parameters
quantile _ returns : pd . DataFrame
Returns by factor quantile
period : pandas . Timedelta or string
Length of period for which the returns ar... | if ax is None :
f , ax = plt . subplots ( 1 , 1 , figsize = ( 18 , 6 ) )
ret_wide = quantile_returns . unstack ( 'factor_quantile' )
cum_ret = ret_wide . apply ( perf . cumulative_returns , period = period , freq = freq )
cum_ret = cum_ret . loc [ : , : : - 1 ]
# we want negative quantiles as ' red '
cum_ret . plot... |
def is_valid_codon ( codon , type = 'start' ) :
"""Given a codon sequence , check if it is a valid start / stop codon""" | if len ( codon ) != 3 :
return False
if type == 'start' :
if codon != 'ATG' :
return False
elif type == 'stop' :
if not any ( _codon == codon for _codon in ( 'TGA' , 'TAG' , 'TAA' ) ) :
return False
else :
logging . error ( "`{0}` is not a valid codon type. " . format ( type ) + "Should ... |
def deploy_templates ( ) :
"""Deploy any templates from your shortest TEMPLATE _ DIRS setting""" | deployed = None
if not hasattr ( env , 'project_template_dir' ) : # the normal pattern would mean the shortest path is the main one .
# its probably the last listed
length = 1000
for dir in env . TEMPLATE_DIRS :
if dir :
len_dir = len ( dir )
if len_dir < length :
... |
def attrs ( self , attribute_name ) :
"""Retrieve HTML attribute values from the elements matched by the query .
Example usage :
. . code : : python
# Assume that the query matches html elements :
# < div class = " foo " > and < div class = " bar " >
> > q . attrs ( ' class ' )
[ ' foo ' , ' bar ' ]
A... | desc = u'attrs({!r})' . format ( attribute_name )
return self . map ( lambda el : el . get_attribute ( attribute_name ) , desc ) . results |
def parse_lines ( self , lines : Iterable [ str ] ) -> List [ ParseResults ] :
"""Parse multiple lines in succession .""" | return [ self . parseString ( line , line_number ) for line_number , line in enumerate ( lines ) ] |
def concatenate_fastas ( output_fna_clustered , output_fna_failures , output_concat_filepath ) :
"""Concatenates two input fastas , writes to output _ concat _ filepath
output _ fna _ clustered : fasta of successful ref clusters
output _ fna _ failures : de novo fasta of cluster failures
output _ concat _ fil... | output_fp = open ( output_concat_filepath , "w" )
for label , seq in parse_fasta ( open ( output_fna_clustered , "U" ) ) :
output_fp . write ( ">%s\n%s\n" % ( label , seq ) )
for label , seq in parse_fasta ( open ( output_fna_failures , "U" ) ) :
output_fp . write ( ">%s\n%s\n" % ( label , seq ) )
return output... |
def cmdline ( argv , flags ) :
"""A cmdopts wrapper that takes a list of flags and builds the
corresponding cmdopts rules to match those flags .""" | rules = dict ( [ ( flag , { 'flags' : [ "--%s" % flag ] } ) for flag in flags ] )
return parse ( argv , rules ) |
def update_m ( data , old_M , old_W , selected_genes , disp = False , inner_max_iters = 100 , parallel = True , threads = 4 , write_progress_file = None , tol = 0.0 , regularization = 0.0 , ** kwargs ) :
"""This returns a new M matrix that contains all genes , given an M that was
created from running state estima... | genes , cells = data . shape
k = old_M . shape [ 1 ]
non_selected_genes = [ x for x in range ( genes ) if x not in set ( selected_genes ) ]
# 1 . initialize new M
new_M = np . zeros ( ( genes , k ) )
new_M [ selected_genes , : ] = old_M
# TODO : how to initialize rest of genes ?
# data * w ?
if disp :
print ( 'comp... |
def get_sdk_version ( self ) :
"""Get the version of Windows SDK
from VCVarsQueryRegistry . bat .""" | name = 'VCVarsQueryRegistry.bat'
path = os . path . join ( self . tool_dir , name )
batch = read_file ( path )
if not batch :
raise RuntimeError ( _ ( 'failed to find the SDK version' ) )
regex = r'(?<=\\Microsoft SDKs\\Windows\\).+?(?=")'
try :
version = re . search ( regex , batch ) . group ( )
except Attribu... |
def extract_options ( name ) :
"""Extracts comparison option from filename .
As example , ` ` Binarizer - SkipDim1 ` ` means
options * SkipDim1 * is enabled .
` ` ( 1 , 2 ) ` ` and ` ` ( 2 , ) ` ` are considered equal .
Available options :
* ` ' SkipDim1 ' ` : reshape arrays by skipping 1 - dimension : ` ... | opts = name . replace ( "\\" , "/" ) . split ( "/" ) [ - 1 ] . split ( '.' ) [ 0 ] . split ( '-' )
if len ( opts ) == 1 :
return { }
else :
res = { }
for opt in opts [ 1 : ] :
if opt in ( "SkipDim1" , "OneOff" , "NoProb" , "Dec4" , "Dec3" , 'Out0' , 'Dec2' , 'Reshape' , 'Opp' ) :
res [ o... |
def import_submodules ( package : Union [ str , ModuleType ] , base_package_for_relative_import : str = None , recursive : bool = True ) -> Dict [ str , ModuleType ] :
"""Import all submodules of a module , recursively , including subpackages .
Args :
package : package ( name or actual module )
base _ package... | # http : / / stackoverflow . com / questions / 3365740 / how - to - import - all - submodules
if isinstance ( package , str ) :
package = importlib . import_module ( package , base_package_for_relative_import )
results = { }
for loader , name , is_pkg in pkgutil . walk_packages ( package . __path__ ) :
full_nam... |
def start_ssh_server ( port , username , password , namespace ) :
"""Start an SSH server on the given port , exposing a Python prompt with the
given namespace .""" | # This is a lot of boilerplate , see http : / / tm . tl / 6429 for a ticket to
# provide a utility function that simplifies this .
from twisted . internet import reactor
from twisted . conch . insults import insults
from twisted . conch import manhole , manhole_ssh
from twisted . cred . checkers import ( InMemoryUserna... |
def credential_add ( self , name , cred_type , ** options ) :
'''Adds a new credential into SecurityCenter . As credentials can be of
multiple types , we have different options to specify for each type of
credential .
* * Global Options ( Required ) * *
: param name : Unique name to be associated to this cr... | if 'pirvateKey' in options :
options [ 'privateKey' ] = self . _upload ( options [ 'privateKey' ] ) [ 'filename' ]
if 'publicKey' in options :
options [ 'publicKey' ] = self . _upload ( options [ 'publicKey' ] ) [ 'filename' ]
return self . raw_query ( "credential" , "add" , data = options ) |
def count_countries ( publishingCountry , ** kwargs ) :
'''Lists occurrence counts for all countries covered by the data published by the given country
: param publishingCountry : [ str ] A two letter country code
: return : dict
Usage : :
from pygbif import occurrences
occurrences . count _ countries ( p... | url = gbif_baseurl + 'occurrence/counts/countries'
out = gbif_GET ( url , { 'publishingCountry' : publishingCountry } , ** kwargs )
return out |
async def dump_variant ( self , elem , elem_type = None , params = None , obj = None ) :
"""Dumps variant type to the writer .
Supports both wrapped and raw variant .
: param elem :
: param elem _ type :
: param params :
: param obj :
: return :""" | fvalue = None
if isinstance ( elem , x . VariantType ) or elem_type . WRAPS_VALUE :
try :
self . tracker . push_variant ( elem . variant_elem_type )
fvalue = { elem . variant_elem : await self . _dump_field ( getattr ( elem , elem . variant_elem ) , elem . variant_elem_type , obj = obj ) }
s... |
def IsTemplateParameterList ( clean_lines , linenum , column ) :
"""Check if the token ending on ( linenum , column ) is the end of template < > .
Args :
clean _ lines : A CleansedLines instance containing the file .
linenum : the number of the line to check .
column : end column of the token to check .
R... | ( _ , startline , startpos ) = ReverseCloseExpression ( clean_lines , linenum , column )
if ( startpos > - 1 and Search ( r'\btemplate\s*$' , clean_lines . elided [ startline ] [ 0 : startpos ] ) ) :
return True
return False |
def expanddotpaths ( env , console ) :
"""Move files with dots in them to sub - directories""" | for filepath in os . listdir ( path . join ( env . dir ) ) :
filename , ext = path . splitext ( filepath )
if ext == '.lua' and '.' in filename :
paths , newfilename = filename . rsplit ( '.' , 1 )
newpath = paths . replace ( '.' , '/' )
newfilename = path . join ( newpath , newfilename ... |
def get_routes ( self , athlete_id = None , limit = None ) :
"""Gets the routes list for an authenticated user .
http : / / strava . github . io / api / v3 / routes / # list
: param athlete _ id : id for the
: param limit : Max rows to return ( default unlimited ) .
: type limit : int
: return : An iterat... | if athlete_id is None :
athlete_id = self . get_athlete ( ) . id
result_fetcher = functools . partial ( self . protocol . get , '/athletes/{id}/routes' . format ( id = athlete_id ) )
return BatchedResultsIterator ( entity = model . Route , bind_client = self , result_fetcher = result_fetcher , limit = limit ) |
def preprocess_value ( self , value , default = tuple ( ) ) :
"""Preprocess the value for set""" | # empty value
if not value :
return default
# list with one empty item
if isinstance ( value , ( list , tuple ) ) :
if len ( value ) == 1 and not value [ 0 ] :
return default
if not isinstance ( value , ( list , tuple ) ) :
value = value ,
return value |
def generate_changelog ( context ) :
"""Generates an automatic changelog from your commit messages .""" | changelog_content = [ '\n## [%s](%s/compare/%s...%s)\n\n' % ( context . new_version , context . repo_url , context . current_version , context . new_version , ) ]
git_log_content = None
git_log = 'log --oneline --no-merges --no-color' . split ( ' ' )
try :
git_log_tag = git_log + [ '%s..master' % context . current_... |
def md5_8_name ( self , url ) :
"""把下载的文件重命名为地址的md5前8位""" | m = hashlib . md5 ( )
m . update ( url . encode ( 'utf-8' ) )
return m . hexdigest ( ) [ : 8 ] + os . path . splitext ( url ) [ 1 ] |
def fasta_format_check ( fasta_path , logger ) :
"""Check that a file is valid FASTA format .
- First non - blank line needs to begin with a ' > ' header character .
- Sequence can only contain valid IUPAC nucleotide characters
Args :
fasta _ str ( str ) : FASTA file contents string
Raises :
Exception :... | header_count = 0
line_count = 1
nt_count = 0
with open ( fasta_path ) as f :
for l in f :
l = l . strip ( )
if l == '' :
continue
if l [ 0 ] == '>' :
header_count += 1
continue
if header_count == 0 and l [ 0 ] != '>' :
error_msg = 'Firs... |
def random_get_instance ( ) -> tcod . random . Random :
"""Return the default Random instance .
Returns :
Random : A Random instance using the default random number generator .""" | return tcod . random . Random . _new_from_cdata ( ffi . cast ( "mersenne_data_t*" , lib . TCOD_random_get_instance ( ) ) ) |
def handleTickSize ( self , msg ) :
"""holds latest tick bid / ask / last size""" | if msg . size < 0 :
return
df2use = self . marketData
if self . contracts [ msg . tickerId ] . m_secType in ( "OPT" , "FOP" ) :
df2use = self . optionsData
# create tick holder for ticker
if msg . tickerId not in df2use . keys ( ) :
df2use [ msg . tickerId ] = df2use [ 0 ] . copy ( )
# market data
# bid siz... |
def get_all_groups ( self , ** kwargs ) : # noqa : E501
"""Get all group information . # noqa : E501
An endpoint for retrieving all group information . * * Example usage : * * ` curl https : / / api . us - east - 1 . mbedcloud . com / v3 / policy - groups - H ' Authorization : Bearer API _ KEY ' ` # noqa : E501
... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . get_all_groups_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . get_all_groups_with_http_info ( ** kwargs )
# noqa : E501
return data |
def get_message_type ( message ) :
"""Return message ' s type""" | for msg_type in MessageType . FIELDS :
if Message . is_type ( msg_type , message ) :
return msg_type
return MessageType . UNKNOWN |
def _string_to_rgb ( color ) :
"""Convert user string or hex color to color array ( length 3 or 4)""" | if not color . startswith ( '#' ) :
if color . lower ( ) not in _color_dict :
raise ValueError ( 'Color "%s" unknown' % color )
color = _color_dict [ color ]
assert color [ 0 ] == '#'
# hex color
color = color [ 1 : ]
lc = len ( color )
if lc in ( 3 , 4 ) :
color = '' . join ( c + c for c in col... |
def requestExec ( self , commandLine ) :
"""Request execution of : commandLine : and return a deferred reply .""" | data = common . NS ( commandLine )
return self . sendRequest ( 'exec' , data , wantReply = True ) |
def setup_benchbuild ( ) :
"""Setup benchbuild inside a container .
This will query a for an existing installation of benchbuild and
try to upgrade it to the latest version , if possible .""" | LOG . debug ( "Setting up Benchbuild..." )
venv_dir = local . path ( "/benchbuild" )
prefixes = CFG [ "container" ] [ "prefixes" ] . value
prefixes . append ( venv_dir )
CFG [ "container" ] [ "prefixes" ] = prefixes
src_dir = str ( CFG [ "source_dir" ] )
have_src = src_dir is not None
if have_src :
__mount_source (... |
def cli ( ) :
"""Command line utility for serving datasets in a directory over HTTP .""" | parser = argparse . ArgumentParser ( description = __doc__ )
parser . add_argument ( "dataset_directory" , help = "Directory with datasets to be served" )
parser . add_argument ( "-p" , "--port" , type = int , default = 8081 , help = "Port to serve datasets on (default 8081)" )
args = parser . parse_args ( )
if not os ... |
def _split_field_list ( field_list ) :
"""Split the list of fields for which to extract values into lists by extraction
methods .
- Remove any duplicated field names .
- Raises ValueError with list of any invalid field names in ` ` field _ list ` ` .""" | lookup_dict = { }
generate_dict = { }
for field_name in field_list or FIELD_NAME_TO_EXTRACT_DICT . keys ( ) :
try :
extract_dict = FIELD_NAME_TO_EXTRACT_DICT [ field_name ]
except KeyError :
assert_invalid_field_list ( field_list )
else :
if "lookup_str" in extract_dict :
... |
def get_list ( self , input_string ) :
"""Return a list of user input
: param input _ string :
: return :""" | if input_string in ( '--ensemble_list' , '--fpf' ) : # was the flag set ?
try :
index_low = self . args . index ( input_string ) + 1
except ValueError :
if input_string in self . required :
print ( "\n {flag} is required" . format ( flag = input_string ) )
print_short_hel... |
def _parse_option ( cls , token ) :
"""Parse an option expression .
: param token : The option expression
: type token : str
: rtype : InputOption""" | description = ""
validator = None
if " : " in token :
token , description = tuple ( token . split ( " : " , 2 ) )
token = token . strip ( )
description = description . strip ( )
# Checking validator :
matches = re . match ( r"(.*)\((.*?)\)" , token )
if matches :
token = matches . group ( 1 ) . strip ( ... |
def get_currencys ( self , site = 'Pro' , _async = False ) :
"""获取所有币种
: param site :
: return :""" | assert site in [ 'Pro' , 'HADAX' ]
params = { }
path = f'/v1{"/" if site == "Pro" else "/hadax/"}common/currencys'
return api_key_get ( params , path , _async = _async ) |
def delete_thing_shadow ( self , thing_name ) :
"""after deleting , get _ thing _ shadow will raise ResourceNotFound .
But version of the shadow keep increasing . . .""" | thing = iot_backends [ self . region_name ] . describe_thing ( thing_name )
if thing . thing_shadow is None :
raise ResourceNotFoundException ( )
payload = None
new_shadow = FakeShadow . create_from_previous_version ( thing . thing_shadow , payload )
thing . thing_shadow = new_shadow
return thing . thing_shadow |
def _set_ovsdb_server ( self , v , load = False ) :
"""Setter method for ovsdb _ server , mapped from YANG variable / ovsdb _ server ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ ovsdb _ server is considered as a private
method . Backends looking to populat... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "name" , ovsdb_server . ovsdb_server , yang_name = "ovsdb-server" , rest_name = "ovsdb-server" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper , yang_keys = 'n... |
def remove_tag ( tag_id ) :
'''Delete the records of certain tag .''' | entry = TabPost2Tag . delete ( ) . where ( TabPost2Tag . tag_id == tag_id )
entry . execute ( ) |
def print_help ( self , script_name : str ) :
'''print a help message from the script''' | textWidth = max ( 60 , shutil . get_terminal_size ( ( 80 , 20 ) ) . columns )
if len ( script_name ) > 20 :
print ( f'usage: sos run {script_name}' )
print ( ' [workflow_name | -t targets] [options] [workflow_options]' )
else :
print ( f'usage: sos run {script_name} [workflow_name | -t targets... |
def plucks ( obj , selector , default = None ) :
"""Safe itemgetter for structured objects .
Happily operates on all ( nested ) objects that implement the item getter ,
i . e . the ` [ ] ` operator .
The ` selector ` is ~
` ` ( < key > | < index > | < slice > | \ * ) ( \ . ( < key > | < index > | < slice > ... | def _filter ( iterable , index ) :
res = [ ]
for obj in iterable :
try :
res . append ( obj [ index ] )
except :
pass
return res
def _int ( val ) :
try :
return int ( val )
except :
return None
def _parsekey ( key ) :
m = re . match ( r"^(?... |
def add_component ( self , symlink_comp ) : # type : ( bytes ) - > None
'''Add a new component to this symlink record .
Parameters :
symlink _ comp - The string to add to this symlink record .
Returns :
Nothing .''' | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'SL record not yet initialized!' )
if ( self . current_length ( ) + RRSLRecord . Component . length ( symlink_comp ) ) > 255 :
raise pycdlibexception . PyCdlibInvalidInput ( 'Symlink would be longer than 255' )
self . symlink_component... |
def url ( self ) :
"""The URL present in this inline results . If you want to " click "
this URL to open it in your browser , you should use Python ' s
` webbrowser . open ( url ) ` for such task .""" | if isinstance ( self . result , types . BotInlineResult ) :
return self . result . url |
def merge_graphs ( main_graph , addition_graph ) :
"""Merges an ' ' addition _ graph ' ' into the ' ' main _ graph ' ' .
Returns a tuple of dictionaries , mapping old node ids and edge ids to new ids .""" | node_mapping = { }
edge_mapping = { }
for node in addition_graph . get_all_node_objects ( ) :
node_id = node [ 'id' ]
new_id = main_graph . new_node ( )
node_mapping [ node_id ] = new_id
for edge in addition_graph . get_all_edge_objects ( ) :
edge_id = edge [ 'id' ]
old_vertex_a_id , old_vertex_b_id... |
def askRasterBounds ( self ) :
"""Prompts the user to provide the raster bounds with a dialog .
Saves the bounds to be applied to the plot""" | dlg = RasterBoundsDialog ( bounds = ( self . rasterBottom , self . rasterTop ) )
if dlg . exec_ ( ) :
bounds = dlg . values ( )
self . setRasterBounds ( bounds ) |
def covar ( self , bessel = True ) :
"""Return covariance matrix :
Parameters :
bessel : bool , optional , default = True
Use Bessel ' s correction in order to
obtain an unbiased estimator of sample covariances .""" | if bessel :
return self . Mxy / ( self . w - 1 )
else :
return self . Mxy / self . w |
def create_variable_is_list ( self ) :
"""Append code for creating variable with bool if it ' s instance of list
with a name ` ` { variable } _ is _ list ` ` . Similar to ` create _ variable _ with _ length ` .""" | variable_name = '{}_is_list' . format ( self . _variable )
if variable_name in self . _variables :
return
self . _variables . add ( variable_name )
self . l ( '{variable}_is_list = isinstance({variable}, list)' ) |
def draw ( self , figure ) :
"""Draw watermark
Parameters
figure : Matplotlib . figure . Figure
Matplolib figure on which to draw""" | X = mimage . imread ( self . filename )
figure . figimage ( X , ** self . kwargs ) |
def execute ( self , query , args = None ) :
"""Execute a query .
query - - string , query to execute on server
args - - optional sequence or mapping , parameters to use with query .
Note : If args is a sequence , then % s must be used as the
parameter placeholder in the query . If a mapping is used ,
% (... | while self . nextset ( ) :
pass
db = self . _get_db ( )
if isinstance ( query , unicode ) :
query = query . encode ( db . encoding )
if args is not None :
if isinstance ( args , dict ) :
nargs = { }
for key , item in args . items ( ) :
if isinstance ( key , unicode ) :
... |
def clear_if_finalized ( iteration : TransitionResult , ) -> TransitionResult [ InitiatorPaymentState ] :
"""Clear the initiator payment task if all transfers have been finalized
or expired .""" | state = cast ( InitiatorPaymentState , iteration . new_state )
if state is None :
return iteration
if len ( state . initiator_transfers ) == 0 :
return TransitionResult ( None , iteration . events )
return iteration |
def calculate_sv_coverage ( data ) :
"""Calculate coverage within bins for downstream CNV calling .
Creates corrected cnr files with log2 ratios and depths .""" | calcfns = { "cnvkit" : _calculate_sv_coverage_cnvkit , "gatk-cnv" : _calculate_sv_coverage_gatk }
from bcbio . structural import cnvkit
data = utils . to_single_data ( data )
if not cnvkit . use_general_sv_bins ( data ) :
out_target_file , out_anti_file = ( None , None )
else :
work_dir = utils . safe_makedir (... |
def is_credit_card ( string , card_type = None ) :
"""Checks if a string is a valid credit card number .
If card type is provided then it checks that specific type ,
otherwise any known credit card number will be accepted .
: param string : String to check .
: type string : str
: param card _ type : Card ... | if not is_full_string ( string ) :
return False
if card_type :
if card_type not in CREDIT_CARDS :
raise KeyError ( 'Invalid card type "{}". Valid types are: {}' . format ( card_type , ', ' . join ( CREDIT_CARDS . keys ( ) ) ) )
return bool ( CREDIT_CARDS [ card_type ] . search ( string ) )
for c in ... |
def partition ( N , k ) :
'''Distribute ` ` N ` ` into ` ` k ` ` parts such that each part
takes the value ` ` N / / k ` ` or ` ` N / / k + 1 ` ` where ` ` / / ` ` denotes integer
division ; i . e . , perform the minimal lexicographic integer partition .
Example : N = 5 , k = 2 - - > return [ 3 , 2]''' | out = [ N // k ] * k
remainder = N % k
for i in range ( remainder ) :
out [ i ] += 1
return out |
def download_torrent ( self ) :
"""Download torrent .
Rated implies download the unique best rated torrent found .
Otherwise : get the magnet and download it .""" | try :
if self . back_to_menu is True :
return
if self . found_torrents is False :
print ( 'Nothing found.' )
return
if self . mode_search == 'best_rated' :
print ( 'Downloading..' )
self . open_magnet ( )
elif self . mode_search == 'list' :
if self . selec... |
def check_power_raw ( self ) :
"""Returns the power state of the smart power strip in raw format .""" | packet = bytearray ( 16 )
packet [ 0x00 ] = 0x0a
packet [ 0x02 ] = 0xa5
packet [ 0x03 ] = 0xa5
packet [ 0x04 ] = 0x5a
packet [ 0x05 ] = 0x5a
packet [ 0x06 ] = 0xae
packet [ 0x07 ] = 0xc0
packet [ 0x08 ] = 0x01
response = self . send_packet ( 0x6a , packet )
err = response [ 0x22 ] | ( response [ 0x23 ] << 8 )
if err ==... |
def ordered_by_replica ( self , request_key ) :
"""Should be called by each replica when request is ordered or replica is removed .""" | state = self . get ( request_key )
if not state :
return
state . unordered_by_replicas_num -= 1 |
def list_available_tools ( self ) :
"""Lists all the Benchmarks configuration files found in the configuration folders
: return :""" | benchmarks = [ ]
if self . alternative_config_dir :
for n in glob . glob ( os . path . join ( self . alternative_config_dir , self . BENCHMARKS_DIR , '*.conf' ) ) :
benchmarks . append ( BenchmarkToolConfiguration ( n ) )
for n in glob . glob ( os . path . join ( self . default_config_dir , self . BENCHMARK... |
def wr_xlsx_nts ( self , fout_xlsx , desc2nts , ** kws_usr ) :
"""Print grouped and sorted GO IDs .""" | # KWS _ XLSX : top _ n section _ prt section _ sortby
# Adjust xlsx keyword args
kws_xlsx = self . _get_xlsx_kws ( ** kws_usr )
# KWS _ SHADE : shade _ hdrgos hdrgo _ prt section _ sortby top _ n
shade_hdrgos = self . _get_shade_hdrgos ( ** kws_usr )
self . _adjust_prt_flds ( kws_xlsx , desc2nts , shade_hdrgos )
# 1 - ... |
def apply_motion_tracks ( self , tracks , accuracy = 0.004 ) :
"""Similar to click but press the screen for the given time interval and then release
Args :
tracks ( : py : obj : ` list ` ) : list of : py : class : ` poco . utils . track . MotionTrack ` object
accuracy ( : py : obj : ` float ` ) : motion accur... | if not tracks :
raise ValueError ( 'Please provide at least one track. Got {}' . format ( repr ( tracks ) ) )
tb = MotionTrackBatch ( tracks )
return self . agent . input . applyMotionEvents ( tb . discretize ( accuracy ) ) |
def transpose ( self , method ) :
"""Transpose bounding box ( flip or rotate in 90 degree steps )
: param method : One of : py : attr : ` PIL . Image . FLIP _ LEFT _ RIGHT ` ,
: py : attr : ` PIL . Image . FLIP _ TOP _ BOTTOM ` , : py : attr : ` PIL . Image . ROTATE _ 90 ` ,
: py : attr : ` PIL . Image . ROTA... | if method not in ( FLIP_LEFT_RIGHT , FLIP_TOP_BOTTOM ) :
raise NotImplementedError ( "Only FLIP_LEFT_RIGHT and FLIP_TOP_BOTTOM implemented" )
image_width , image_height = self . size
xmin , ymin , xmax , ymax = self . _split_into_xyxy ( )
if method == FLIP_LEFT_RIGHT :
TO_REMOVE = 1
transposed_xmin = image_... |
def options ( self , * args , ** kwargs ) :
"""Default OPTIONS response
If the ' cors ' option is True , will respond with an empty response and
set the ' Access - Control - Allow - Headers ' and
' Access - Control - Allow - Methods ' headers""" | if getattr ( options , 'cors' , False ) :
self . set_header ( 'Access-Control-Allow-Headers' , 'Content-Type, Authorization, ' 'Accept, X-Requested-With' )
self . set_header ( 'Access-Control-Allow-Methods' , 'OPTIONS, TRACE, GET, HEAD, POST, ' 'PUT, PATCH, DELETE' )
self . finish ( ) |
def range ( self , dim , data_range = True , dimension_range = True ) :
"""Return the lower and upper bounds of values along dimension .
Args :
dimension : The dimension to compute the range on .
data _ range ( bool ) : Compute range from data values
dimension _ range ( bool ) : Include Dimension ranges
W... | iskdim = self . get_dimension ( dim ) not in self . vdims
return super ( StatisticsElement , self ) . range ( dim , iskdim , dimension_range ) |
def _parse_bands ( self , band_input ) :
"""Parses class input and verifies band names .
: param band _ input : input parameter ` bands `
: type band _ input : str or list ( str ) or None
: return : verified list of bands
: rtype : list ( str )""" | all_bands = AwsConstants . S2_L1C_BANDS if self . data_source is DataSource . SENTINEL2_L1C else AwsConstants . S2_L2A_BANDS
if band_input is None :
return all_bands
if isinstance ( band_input , str ) :
band_list = band_input . split ( ',' )
elif isinstance ( band_input , list ) :
band_list = band_input . c... |
def path ( self , which = None ) :
"""Extend ` ` nailgun . entity _ mixins . Entity . path ` ` .
The format of the returned path depends on the value of ` ` which ` ` :
incremental _ update
/ content _ view _ versions / incremental _ update
promote
/ content _ view _ versions / < id > / promote
` ` supe... | if which in ( 'incremental_update' , 'promote' ) :
prefix = 'base' if which == 'incremental_update' else 'self'
return '{0}/{1}' . format ( super ( ContentViewVersion , self ) . path ( prefix ) , which )
return super ( ContentViewVersion , self ) . path ( which ) |
def getAnalysisRequestTemplates ( self ) :
"""This functions builds a list of tuples with the object AnalysisRequestTemplates ' uids and names .
: returns : A list of tuples where the first value of the tuple is the AnalysisRequestTemplate name and the
second one is the AnalysisRequestTemplate UID . - - > [ ( A... | l = [ ]
art_uids = self . ar_templates
# I have to get the catalog in this way because I can ' t do it with ' self ' . . .
pc = getToolByName ( api . portal . get ( ) , 'uid_catalog' )
for art_uid in art_uids :
art_obj = pc ( UID = art_uid )
if len ( art_obj ) != 0 :
l . append ( ( art_obj [ 0 ] . Title... |
def add_export ( exports = '/etc/exports' , path = None , hosts = None , options = None ) :
'''Add an export
CLI Example :
. . code - block : : bash
salt ' * ' nfs3 . add _ export path = ' / srv / test ' hosts = ' 127.0.0.1 ' options = [ ' rw ' ]''' | if options is None :
options = [ ]
if not isinstance ( hosts , six . string_types ) : # Lists , etc would silently mangle / etc / exports
raise TypeError ( 'hosts argument must be a string' )
edict = list_exports ( exports )
if path not in edict :
edict [ path ] = [ ]
new = { 'hosts' : hosts , 'options' : o... |
def cmd ( send , msg , args ) :
"""Shows or clears the abuse list
Syntax : { command } < - - clear | - - show >""" | parser = arguments . ArgParser ( args [ 'config' ] )
group = parser . add_mutually_exclusive_group ( )
group . add_argument ( '--clear' , action = 'store_true' )
group . add_argument ( '--show' , action = 'store_true' )
try :
cmdargs = parser . parse_args ( msg )
except arguments . ArgumentException as e :
send... |
async def get_box_ids_issued ( self ) -> str :
"""Return json object on lists of all unique box identifiers ( schema identifiers ,
credential definition identifiers , and revocation registry identifiers ) for
all credential definitions and credentials issued ; e . g . ,
" schema _ id " : [
" R17v42T4pk . . ... | LOGGER . debug ( 'Issuer.get_box_ids_issued >>>' )
cd_ids = [ d for d in listdir ( self . dir_tails ) if isdir ( join ( self . dir_tails , d ) ) and ok_cred_def_id ( d , self . did ) ]
s_ids = [ ]
for cd_id in cd_ids :
try :
s_ids . append ( json . loads ( await self . get_schema ( cred_def_id2seq_no ( cd_i... |
def get_records ( self , start_time , end_time , msgid = 1 , number = 10000 ) :
"""获取客服聊天记录
: param start _ time : 查询开始时间 , UNIX 时间戳
: param end _ time : 查询结束时间 , UNIX 时间戳 , 每次查询不能跨日查询
: param msgid : 消息id顺序从小到大 , 从1开始
: param number : 每次获取条数 , 最多10000条
: return : 返回的 JSON 数据包""" | if isinstance ( start_time , datetime . datetime ) :
start_time = time . mktime ( start_time . timetuple ( ) )
if isinstance ( end_time , datetime . datetime ) :
end_time = time . mktime ( end_time . timetuple ( ) )
record_data = { 'starttime' : int ( start_time ) , 'endtime' : int ( end_time ) , 'msgid' : msgi... |
def shellc ( ndim , lenvals , array ) : # This works ! looks like this is a mutable 2d char array
"""Sort an array of character strings according to the ASCII
collating sequence using the Shell Sort algorithm .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / shellc _ c . html
:... | array = stypes . listToCharArray ( array , xLen = lenvals , yLen = ndim )
ndim = ctypes . c_int ( ndim )
lenvals = ctypes . c_int ( lenvals )
libspice . shellc_c ( ndim , lenvals , ctypes . byref ( array ) )
return stypes . cVectorToPython ( array ) |
def tables ( self ) :
"""Generic method that does a depth - first search on the node attributes .
Child classes should override this method for better performance .""" | _tables = set ( )
for attr in six . itervalues ( self . __dict__ ) :
if isinstance ( attr , list ) :
for item in attr :
if isinstance ( item , Node ) :
_tables |= item . tables ( )
elif isinstance ( attr , Node ) :
_tables |= attr . tables ( )
return _tables |
def label_to_original_label_otu_by_id ( otu_by_id ) :
"""Takes a v1.2 otuById dict and , for every otu ,
checks if ot : originalLabel exists . If it does not ,
but @ label does , then ot : originalLabel is set to
@ label and @ label is deleted .""" | for val in otu_by_id . values ( ) :
orig = val . get ( '^ot:originalLabel' )
if orig is None :
label = val . get ( '@label' )
if label :
del val [ '@label' ]
val [ '^ot:originalLabel' ] = label |
def validate ( self , instance ) :
"""Validates the given document against this schema . Raises a
ValidationException if there are any failures .""" | errors = { }
self . _validate_instance ( instance , errors )
if len ( errors ) > 0 :
raise ValidationException ( errors ) |
def key_gen ( self , key_name , type , size = 2048 , ** kwargs ) :
"""Adds a new public key that can be used for name _ publish .
. . code - block : : python
> > > c . key _ gen ( ' example _ key _ name ' )
{ ' Name ' : ' example _ key _ name ' ,
' Id ' : ' QmQLaT5ZrCfSkXTH6rUKtVidcxj8jrW3X2h75Lug1AV7g8 ' }... | opts = { "type" : type , "size" : size }
kwargs . setdefault ( "opts" , opts )
args = ( key_name , )
return self . _client . request ( '/key/gen' , args , decoder = 'json' , ** kwargs ) |
async def songs ( self ) :
'''list of songs in the playlist
| force |
| coro |
Returns
list
of type : class : ` embypy . objects . Audio `''' | items = [ ]
for i in await self . items :
if i . type == 'Audio' :
items . append ( i )
elif hasattr ( i , 'songs' ) :
items . extend ( await i . songs )
return items |
def set_range ( self , bounds , keep_aspect = False ) :
"""Zoom to fit a box .""" | # a * ( v0 + t ) = - 1
# a * ( v1 + t ) = + 1
# a * ( v1 - v0 ) = 2
bounds = np . asarray ( bounds , dtype = np . float64 )
v0 = bounds [ : 2 ]
v1 = bounds [ 2 : ]
pan = - .5 * ( v0 + v1 )
zoom = 2. / ( v1 - v0 )
if keep_aspect :
zoom = zoom . min ( ) * np . ones ( 2 )
self . set_pan_zoom ( pan = pan , zoom = zoom ... |
def norm ( self , coords : Vector3Like , frac_coords : bool = True ) -> float :
"""Compute the norm of vector ( s ) .
Args :
coords :
Array - like object with the coordinates .
frac _ coords :
Boolean stating whether the vector corresponds to fractional or
cartesian coordinates .
Returns :
one - dim... | return np . sqrt ( self . dot ( coords , coords , frac_coords = frac_coords ) ) |
def start ( name , call = None ) :
'''start a machine by name
: param name : name given to the machine
: param call : call value in this case is ' action '
: return : true if successful
CLI Example :
. . code - block : : bash
salt - cloud - a start vm _ name''' | datacenter_id = get_datacenter_id ( )
conn = get_conn ( )
node = get_node ( conn , name )
conn . start_server ( datacenter_id = datacenter_id , server_id = node [ 'id' ] )
return True |
def _su_scripts_regex ( self ) :
""": return :
[ compiled regex , function ]""" | sups = re . escape ( '' . join ( [ k for k in self . superscripts . keys ( ) ] ) )
subs = re . escape ( '' . join ( [ k for k in self . subscripts . keys ( ) ] ) )
# language = PythonRegExp
su_regex = ( r'\\([{su_}])|([{sub}]+|‹[{sub}]+›|˹[{sub}]+˺)' + r'|([{sup}]+)(?=√)|([{sup}]+(?!√)|‹[{sup}]+›|˹[{sup}]+˺)' ) . forma... |
def fetch_extra_data ( resource ) :
"""Return a dict with extra data retrieved from cern oauth .""" | person_id = resource . get ( 'PersonID' , [ None ] ) [ 0 ]
identity_class = resource . get ( 'IdentityClass' , [ None ] ) [ 0 ]
department = resource . get ( 'Department' , [ None ] ) [ 0 ]
return dict ( person_id = person_id , identity_class = identity_class , department = department ) |
def validate_LESSTHAN ( in_value , restriction ) :
"""Test to ensure that a value is less than a prescribed value .
Parameter : Two values , which will be compared for the difference . .""" | # Sometimes restriction values can accidentally be put in the template < item > 100 < / items > ,
# Making them a list , not a number . Rather than blowing up , just get value 1 from the list .
if type ( restriction ) is list :
restriction = restriction [ 0 ]
value = _get_val ( in_value )
if type ( value ) is list ... |
def initialize_pop ( self ) :
"""Generates initial population with random positions and speeds .""" | self . population = self . toolbox . swarm ( n = self . _params [ 'popsize' ] )
if self . _params [ 'neighbours' ] :
for i in range ( len ( self . population ) ) :
self . population [ i ] . ident = i
self . population [ i ] . neighbours = list ( set ( [ ( i - x ) % len ( self . population ) for x in... |
def read_union ( fo , writer_schema , reader_schema = None ) :
"""A union is encoded by first writing a long value indicating the
zero - based position within the union of the schema of its value .
The value is then encoded per the indicated schema within the union .""" | # schema resolution
index = read_long ( fo )
if reader_schema : # Handle case where the reader schema is just a single type ( not union )
if not isinstance ( reader_schema , list ) :
if match_types ( writer_schema [ index ] , reader_schema ) :
return read_data ( fo , writer_schema [ index ] , re... |
def sym_exp_map ( cls , q , eta ) :
"""Quaternion symmetrized exponential map .
Find the symmetrized exponential map on the quaternion Riemannian
manifold .
Params :
q : the base point as a Quaternion object
eta : the tangent vector argument of the exponential map
as a Quaternion object
Returns :
A ... | sqrt_q = q ** 0.5
return sqrt_q * Quaternion . exp ( eta ) * sqrt_q |
def process_selectors ( self , index = 0 , flags = 0 ) :
"""Process selectors .
We do our own selectors as BeautifulSoup4 has some annoying quirks ,
and we don ' t really need to do nth selectors or siblings or
descendants etc .""" | return self . parse_selectors ( self . selector_iter ( self . pattern ) , index , flags ) |
def recompute_grad ( fn ) :
"""Decorator that recomputes the function on the backwards pass .
Args :
fn : a function that takes Tensors ( all as positional arguments ) and returns
a tuple of Tensors .
Returns :
A wrapped fn that is identical to fn when called , but its activations will
be discarded and ... | @ functools . wraps ( fn )
def wrapped ( * args ) :
return _recompute_grad ( fn , args )
return wrapped |
def _get_port_for_acl ( self , port_id , switch ) :
"""Gets interface name for ACLs
Finds the Port - Channel name if port _ id is in a Port - Channel , otherwise
ACLs are applied to Ethernet interface .
: param port _ id : Name of port from ironic db
: param server : Server endpoint on the Arista switch to ... | all_intf_info = self . _port_group_info . get ( switch , { } )
intf_info = all_intf_info . get ( port_id , { } )
member_info = intf_info . get ( 'interfaceMembership' , '' )
port_group_info = re . search ( 'Member of (?P<port_group>\S+)' , member_info )
if port_group_info :
port_id = port_group_info . group ( 'port... |
def start_runtime ( self ) :
'''Start the system !''' | while True :
try :
self . call_runtime ( )
except Exception :
log . error ( 'Exception in Thorium: ' , exc_info = True )
time . sleep ( self . opts [ 'thorium_interval' ] ) |
def connect_patch_namespaced_service_proxy_with_path ( self , name , namespace , path , ** kwargs ) : # noqa : E501
"""connect _ patch _ namespaced _ service _ proxy _ with _ path # noqa : E501
connect PATCH requests to proxy of Service # noqa : E501
This method makes a synchronous HTTP request by default . To ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . connect_patch_namespaced_service_proxy_with_path_with_http_info ( name , namespace , path , ** kwargs )
# noqa : E501
else :
( data ) = self . connect_patch_namespaced_service_proxy_with_path_with_http_info ( name , n... |
def HexEscape ( self , string , match , ** unused_kwargs ) :
"""Converts a hex escaped string .""" | logging . debug ( 'HexEscape matched {0:s}.' . format ( string ) )
hex_string = match . group ( 1 )
try :
hex_string = binascii . unhexlify ( hex_string )
hex_string = codecs . decode ( hex_string , 'utf-8' )
self . string += hex_string
except ( TypeError , binascii . Error ) :
raise errors . ParseError... |
def _netmiko_open ( self , device_type , netmiko_optional_args = None ) :
"""Standardized method of creating a Netmiko connection using napalm attributes .""" | if netmiko_optional_args is None :
netmiko_optional_args = { }
try :
self . _netmiko_device = ConnectHandler ( device_type = device_type , host = self . hostname , username = self . username , password = self . password , timeout = self . timeout , ** netmiko_optional_args )
except NetMikoTimeoutException :
... |
def best_archiver ( random , population , archive , args ) :
"""Archive only the best individual ( s ) .
This function archives the best solutions and removes inferior ones .
If the comparison operators have been overloaded to define Pareto
preference ( as in the ` ` Pareto ` ` class ) , then this archiver wi... | new_archive = archive
for ind in population :
if len ( new_archive ) == 0 :
new_archive . append ( ind )
else :
should_remove = [ ]
should_add = True
for a in new_archive :
if ind . candidate == a . candidate :
should_add = False
break
... |
def make_docker_context ( get_steps_fn , github_project , opts = None , default_context_dir = None ) :
'''Returns a path to the Docker context directory . See parse _ args . py .
Helper for making a command - line utility that writes your project ' s
Dockerfile and associated data into a ( temporary ) directory... | if opts is None :
opts = { }
valid_versions = ( ( 'ubuntu:16.04' , '5' ) , )
def add_args ( parser ) :
parser . add_argument ( '--docker-context-dir' , metavar = 'DIR' , default = default_context_dir , help = 'Write the Dockerfile and its context into this directory. ' 'If empty, make a temporary directory. Def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.