signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def publish_results ( self , dist_dir , use_basename_prefix , vt , bundle_dir , archivepath , id , archive_ext ) :
"""Publish a copy of the bundle and archive from the results dir in dist .""" | # TODO ( from mateor ) move distdir management somewhere more general purpose .
name = vt . target . basename if use_basename_prefix else id
bundle_copy = os . path . join ( dist_dir , '{}-bundle' . format ( name ) )
absolute_symlink ( bundle_dir , bundle_copy )
self . context . log . info ( 'created bundle copy {}' . ... |
def enqueue ( self , payload , interval , job_id , queue_id , queue_type = 'default' , requeue_limit = None ) :
"""Enqueues the job into the specified queue _ id
of a particular queue _ type""" | # validate all the input
if not is_valid_interval ( interval ) :
raise BadArgumentException ( '`interval` has an invalid value.' )
if not is_valid_identifier ( job_id ) :
raise BadArgumentException ( '`job_id` has an invalid value.' )
if not is_valid_identifier ( queue_id ) :
raise BadArgumentException ( '`... |
def create_window ( title , url = None , js_api = None , width = 800 , height = 600 , resizable = True , fullscreen = False , min_size = ( 200 , 100 ) , strings = { } , confirm_quit = False , background_color = '#FFFFFF' , text_select = False , frameless = False , debug = False ) :
"""Create a web view window using... | valid_color = r'^#(?:[0-9a-fA-F]{3}){1,2}$'
if not re . match ( valid_color , background_color ) :
raise ValueError ( '{0} is not a valid hex triplet color' . format ( background_color ) )
# Check if starting up from main thread ; if not , wait ; finally raise exception
if current_thread ( ) . name == 'MainThread' ... |
def post_copy_notes ( self , post_id , other_post_id ) :
"""Function to copy notes ( requires login ) .
Parameters :
post _ id ( int ) :
other _ post _ id ( int ) : The id of the post to copy notes to .""" | return self . _get ( 'posts/{0}/copy_notes.json' . format ( post_id ) , { 'other_post_id' : other_post_id } , 'PUT' , auth = True ) |
def _decrement_current_byte ( self ) :
"""Decrements the value of the current byte at the pointer . If the result is below 0,
then it will overflow to 255""" | # If the current byte is uninitialized , then decrementing it will make it the max cell size
# Otherwise , if it ' s already at the minimum cell size , then it will also make it the max cell size
if self . tape [ self . pointer ] is None or self . tape [ self . pointer ] == self . MIN_CELL_SIZE :
self . tape [ self... |
def _handle_request_exception ( self , e ) :
"""This method handle HTTPError exceptions the same as how tornado does ,
leave other exceptions to be handled by user defined handler function
maped in class attribute ` EXCEPTION _ HANDLERS `
Common HTTP status codes :
200 OK
301 Moved Permanently
302 Found... | handle_func = self . _exception_default_handler
if self . EXCEPTION_HANDLERS :
for excs , func_name in self . EXCEPTION_HANDLERS . items ( ) :
if isinstance ( e , excs ) :
handle_func = getattr ( self , func_name )
break
handle_func ( e )
if not self . _finished :
self . finish (... |
def crack_k_from_sigs ( generator , sig1 , val1 , sig2 , val2 ) :
"""Given two signatures with the same secret exponent and K value , return that K value .""" | # s1 = v1 / k1 + ( se * r1 ) / k1
# s2 = v2 / k2 + ( se * r2 ) / k2
# and k = k1 = k2
# so
# k * s1 = v1 + ( se * r1)
# k * s2 = v2 + ( se * r2)
# so
# k * s1 * r2 = r2 * v1 + ( se * r1 * r2)
# k * s2 * r1 = r1 * v2 + ( se * r2 * r1)
# so
# k ( s1 * r2 - s2 * r1 ) = r2 * v1 - r1 * v2
# so
# k = ( r2 * v1 - r1 * v2 ) / ... |
def floyd_warshall ( self ) :
'''API :
floyd _ warshall ( self )
Description :
Finds all pair shortest paths and stores it in a list of lists .
This is possible if the graph does not have negative cycles . It will
return a tuple with 3 elements . The first element indicates whether
the graph has a negat... | nl = self . get_node_list ( )
el = self . get_edge_list ( )
# initialize distance
distance = { }
for i in nl :
for j in nl :
distance [ ( i , j ) ] = 'infinity'
for i in nl :
distance [ ( i , i ) ] = 0
for e in el :
distance [ ( e [ 0 ] , e [ 1 ] ) ] = self . get_edge_cost ( e )
# = = end of distanc... |
def _writer ( self ) :
"""Indefinitely checks the writer queue for data to write
to socket .""" | while not self . closed :
try :
sock , data = self . _write_queue . get ( timeout = 0.1 )
self . _write_queue . task_done ( )
sock . send ( data )
except Empty :
pass
# nothing to write after timeout
except socket . error as err :
if err . errno == errno . EBA... |
def handle ( cls , value , ** kwargs ) :
"""Split the supplied string on the given delimiter , providing a list .
Format of value :
< delimiter > : : < value >
For example :
Subnets : $ { split , : : subnet - 1 , subnet - 2 , subnet - 3}
Would result in the variable ` Subnets ` getting a list consisting o... | try :
delimiter , text = value . split ( "::" , 1 )
except ValueError :
raise ValueError ( "Invalid value for split: %s. Must be in " "<delimiter>::<text> format." % value )
return text . split ( delimiter ) |
def checktype ( self , elt , ps ) :
'''See if the type of the " elt " element is what we ' re looking for .
Return the element ' s type .
Parameters :
elt - - the DOM element being parsed
ps - - the ParsedSoap object .''' | typeName = _find_type ( elt )
if typeName is None or typeName == "" :
return ( None , None )
# Parse the QNAME .
prefix , typeName = SplitQName ( typeName )
uri = ps . GetElementNSdict ( elt ) . get ( prefix )
if uri is None :
raise EvaluateException ( 'Malformed type attribute (bad NS)' , ps . Backtrace ( elt ... |
def unpack_from ( cls , payload , expected_parts ) :
"""Unpack parts from payload""" | for num_part in iter_range ( expected_parts ) :
hdr = payload . read ( cls . header_size )
try :
part_header = PartHeader ( * cls . header_struct . unpack ( hdr ) )
except struct . error :
raise InterfaceError ( "No valid part header" )
if part_header . payload_size % 8 != 0 :
pa... |
def reload_dependencies ( force = False ) :
"""Reloads all python modules that law depends on . Currently , this is just * luigi * and * six * .
Unless * force * is * True * , multiple calls to this function will not have any effect .""" | global _reloaded_deps
if _reloaded_deps and not force :
return
_reloaded_deps = True
for mod in deps :
six . moves . reload_module ( mod )
logger . debug ( "reloaded module '{}'" . format ( mod ) ) |
def remove_tag_and_push_registries ( tag_and_push_registries , version ) :
"""Remove matching entries from tag _ and _ push _ registries ( in - place )
: param tag _ and _ push _ registries : dict , uri - > dict
: param version : str , ' version ' to match against""" | registries = [ uri for uri , regdict in tag_and_push_registries . items ( ) if regdict [ 'version' ] == version ]
for registry in registries :
logger . info ( "removing %s registry: %s" , version , registry )
del tag_and_push_registries [ registry ] |
def execute ( self , limitRequest = 350000 , limitResMax = - 1 ) :
"""Executes the query .""" | query = self . getQueries ( )
query = self . __buildLimit ( query , limitResMax )
nbr_results = limitResMax
if ( limitResMax == - 1 ) :
query . setBaseUrl ( self . __url + '/count' )
countUrl = query . getUrl ( )
result_count = Util . retrieveJsonResponseFromServer ( countUrl )
nbr_results = result_coun... |
def main ( ) :
"""HAR converter : parse command line options and run commands .""" | parser = argparse . ArgumentParser ( description = __description__ )
parser . add_argument ( '-V' , '--version' , dest = 'version' , action = 'store_true' , help = "show version" )
parser . add_argument ( '--log-level' , default = 'INFO' , help = "Specify logging level, default is INFO." )
parser . add_argument ( 'har_... |
def aggregate_region ( self , variable , region = 'World' , subregions = None , components = None , append = False ) :
"""Compute the aggregate of timeseries over a number of regions
including variable components only defined at the ` region ` level
Parameters
variable : str
variable for which the aggregate... | # default subregions to all regions other than ` region `
if subregions is None :
rows = self . _apply_filters ( variable = variable )
subregions = set ( self . data [ rows ] . region ) - set ( [ region ] )
if not len ( subregions ) :
msg = 'cannot aggregate variable `{}` to `{}` because it does not' ' exis... |
def load_auth_token ( token , load = True ) :
"""Validate an auth0 token . Returns the token ' s payload , or an exception
of the type :""" | assert get_config ( ) . jwt_secret , "No JWT secret configured for pymacaron"
assert get_config ( ) . jwt_issuer , "No JWT issuer configured for pymacaron"
assert get_config ( ) . jwt_audience , "No JWT audience configured for pymacaron"
log . info ( "Validating token, using issuer:%s, audience:%s, secret:%s***" % ( ge... |
def safe_mkdir_for_all ( paths ) :
"""Make directories which would contain all of the passed paths .
This avoids attempting to re - make the same directories , which may be noticeably expensive if many
paths mostly fall in the same set of directories .
: param list of str paths : The paths for which containin... | created_dirs = set ( )
for path in paths :
dir_to_make = os . path . dirname ( path )
if dir_to_make not in created_dirs :
safe_mkdir ( dir_to_make )
created_dirs . add ( dir_to_make ) |
def child ( self , local_name = None , name = None , ns_uri = None , node_type = None , filter_fn = None ) :
""": return : the first child node matching the given constraints , or * None * if there are no matching child nodes .
Delegates to : meth : ` NodeList . filter ` .""" | return self . children ( name = name , local_name = local_name , ns_uri = ns_uri , node_type = node_type , filter_fn = filter_fn , first_only = True ) |
def get_top_tags ( self , limit = None , cacheable = True ) :
"""Returns the most used tags as a sequence of TopItem objects .""" | # Last . fm has no " limit " parameter for tag . getTopTags
# so we need to get all ( 250 ) and then limit locally
doc = _Request ( self , "tag.getTopTags" ) . execute ( cacheable )
seq = [ ]
for node in doc . getElementsByTagName ( "tag" ) :
if limit and len ( seq ) >= limit :
break
tag = Tag ( _extrac... |
def FetchSizeOfSignedBinary ( binary_urn , token = None ) :
"""Returns the size of the given binary ( in bytes ) .
Args :
binary _ urn : RDFURN that uniquely identifies the binary .
token : ACL token to use with the legacy ( non - relational ) datastore .
Raises :
SignedBinaryNotFoundError : If no signed ... | if _ShouldUseLegacyDatastore ( ) :
try :
aff4_stream = aff4 . FACTORY . Open ( binary_urn , aff4_type = collects . GRRSignedBlob , mode = "r" , token = token )
return aff4_stream . size
except aff4 . InstantiationError :
raise SignedBinaryNotFoundError ( binary_urn )
else :
try :
... |
def execute ( self ) :
"""Convert the notebook to a python script and execute it , returning the local context
as a dict""" | from nbformat import read
from nbconvert . exporters import export_script
from cStringIO import StringIO
notebook = read ( StringIO ( self . record . unpacked_contents ) , 4 )
script , resources = export_script ( notebook )
env_dict = { }
exec ( compile ( script . replace ( '# coding: utf-8' , '' ) , 'script' , 'exec' ... |
def underlying_symbol ( self ) :
"""[ str ] 合约标的代码 , 目前除股指期货 ( IH , IF , IC ) 之外的期货合约 , 这一字段全部为 ’ null ’ ( 期货专用 )""" | try :
return self . __dict__ [ "underlying_symbol" ]
except ( KeyError , ValueError ) :
raise AttributeError ( "Instrument(order_book_id={}) has no attribute 'underlying_symbol' " . format ( self . order_book_id ) ) |
def find_root ( node ) :
"""Find the top level namespace .""" | # Scamper up to the top level namespace
while node . type != syms . file_input :
node = node . parent
if not node :
raise ValueError ( "root found before file_input node was found." )
return node |
def is_member ( self , rtc ) :
'''Is the given component a member of this composition ?
rtc may be a Component object or a string containing a component ' s
instance name . Component objects are more reliable .
Returns False if the given component is not a member of this
composition .
Raises NotCompositeE... | if not self . is_composite :
raise exceptions . NotCompositeError ( self . name )
members = self . organisations [ 0 ] . obj . get_members ( )
if type ( rtc ) is str :
for m in members :
if m . get_component_profile ( ) . instance_name == rtc :
return True
else :
for m in members :
... |
def cartesian_to_homogeneous_vectors ( cartesian_vector , matrix_type = "numpy" ) :
"""Converts a cartesian vector to an homogenous vector""" | dimension_x = cartesian_vector . shape [ 0 ]
# Vector
if matrix_type == "numpy" :
homogeneous_vector = np . zeros ( dimension_x + 1 )
# Last item is a 1
homogeneous_vector [ - 1 ] = 1
homogeneous_vector [ : - 1 ] = cartesian_vector
return homogeneous_vector |
def _append_dataframe ( self , df , source_info = "" , units = None ) :
"""Appends a new data group from a Pandas data frame .""" | units = units or { }
t = df . index
index_name = df . index . name
time_name = index_name or "time"
version = self . version
timestamps = t
# if self . version < ' 3.10 ' :
# if timestamps . dtype . byteorder = = ' > ' :
# timestamps = timestamps . byteswap ( ) . newbyteorder ( )
# for signal in signals :
# if signal .... |
def setlist ( self , key , new_list ) : # type : ( Hashable , List [ Any ] ) - > None
"""Remove the old values for a key and add new ones . Note that the list
you pass the values in will be shallow - copied before it is inserted in
the dictionary .
> > > d = MultiValueDict ( )
> > > d . setlist ( ' foo ' , ... | dict . __setitem__ ( self , key , list ( new_list ) ) |
def r ( self ) :
"""Extract read lock ( r ) counter if available ( lazy ) .""" | if not self . _counters_calculated :
self . _counters_calculated = True
self . _extract_counters ( )
return self . _r |
def saveCertPem ( self , cert , path ) :
'''Save a certificate in PEM format to a file outside the certdir .''' | with s_common . genfile ( path ) as fd :
fd . write ( crypto . dump_certificate ( crypto . FILETYPE_PEM , cert ) ) |
def semActsSatisfied ( acts : Optional [ List [ ShExJ . SemAct ] ] , cntxt : Context ) -> bool :
"""` 5.7.1 Semantic Actions Semantics < http : / / shex . io / shex - semantics / # semantic - actions - semantics > ` _
The evaluation semActsSatisfied on a list of SemActs returns success or failure . The evaluation... | return True |
def agent_leave ( consul_url = None , token = None , node = None ) :
'''Used to instruct the agent to force a node into the left state .
: param consul _ url : The Consul server URL .
: param node : The node the agent will force into left state
: return : Boolean and message indicating success or failure .
... | ret = { }
query_params = { }
if not consul_url :
consul_url = _get_config ( )
if not consul_url :
log . error ( 'No Consul URL found.' )
ret [ 'message' ] = 'No Consul URL found.'
ret [ 'res' ] = False
return ret
if not node :
raise SaltInvocationError ( 'Required argument "n... |
def getExportsList ( self , enable = True ) :
"""Return the exports list .
if enable is True , only return the active exporters ( default )
if enable is False , return all the exporters
Return : list of export module name""" | if enable :
return [ e for e in self . _exports ]
else :
return [ e for e in self . _exports_all ] |
def _load_resource_listing ( resource_listing ) :
"""Load the resource listing from file , handling errors .
: param resource _ listing : path to the api - docs resource listing file
: type resource _ listing : string
: returns : contents of the resource listing file
: rtype : dict""" | try :
with open ( resource_listing ) as resource_listing_file :
return simplejson . load ( resource_listing_file )
# If not found , raise a more user - friendly error .
except IOError :
raise ResourceListingNotFoundError ( 'No resource listing found at {0}. Note that your json file ' 'must be named {1}'... |
def losing_abbr ( self ) :
"""Returns a ` ` string ` ` of the losing team ' s abbreviation , such as ' LAD '
for the Los Angeles Dodgers .""" | if self . winner == HOME :
return utils . _parse_abbreviation ( self . _away_name )
return utils . _parse_abbreviation ( self . _home_name ) |
def _reduced_stack ( istart = 3 , iend = 5 , ipython = True ) :
"""Returns the reduced function call stack that includes only relevant
function calls ( i . e . , ignores any that are not part of the specified package
or acorn .
Args :
package ( str ) : name of the package that the logged method belongs to .... | import inspect
return [ i [ istart : iend ] for i in inspect . stack ( ) if _decorated_path ( i [ 1 ] ) ] |
def train ( params , dtrain , num_boost_round = 10 , evals = ( ) , obj = None , feval = None , maximize = False , early_stopping_rounds = None , evals_result = None , verbose_eval = True , xgb_model = None , callbacks = None , learning_rates = None ) : # pylint : disable = too - many - statements , too - many - branche... | callbacks = [ ] if callbacks is None else callbacks
# Most of legacy advanced options becomes callbacks
if isinstance ( verbose_eval , bool ) and verbose_eval :
callbacks . append ( callback . print_evaluation ( ) )
else :
if isinstance ( verbose_eval , int ) :
callbacks . append ( callback . print_eval... |
def scatter ( self , projection = None , c = None , cmap = 'rainbow' , linewidth = 0.0 , edgecolor = 'k' , axes = None , colorbar = True , s = 10 , ** kwargs ) :
"""Display a scatter plot .
Displays a scatter plot using the SAM projection or another input
projection with or without annotations .
Parameters
... | if ( not PLOTTING ) :
print ( "matplotlib not installed!" )
else :
if ( isinstance ( projection , str ) ) :
try :
dt = self . adata . obsm [ projection ]
except KeyError :
print ( 'Please create a projection first using run_umap or' 'run_tsne' )
elif ( projection is N... |
def serialize_instance ( instance ) :
"""Since Django 1.6 items added to the session are no longer pickled ,
but JSON encoded by default . We are storing partially complete models
in the session ( user , account , token , . . . ) . We cannot use standard
Django serialization , as these are models are not " co... | ret = dict ( [ ( k , v ) for k , v in instance . __dict__ . items ( ) if not k . startswith ( '_' ) ] )
return json . loads ( json . dumps ( ret , cls = DjangoJSONEncoder ) ) |
def i18n_alternate_links ( ) :
"""Render the < link rel = " alternate " hreflang / >
if page is in a I18nBlueprint""" | if ( not request . endpoint or not current_app . url_map . is_endpoint_expecting ( request . endpoint , 'lang_code' ) ) :
return Markup ( '' )
try :
LINK_PATTERN = ( '<link rel="alternate" href="{url}" hreflang="{lang}" />' )
links = [ ]
current_lang = get_current_locale ( ) . language
params = { }
... |
def store_relation ( self , src , name , dst ) :
'''use this to store a relation between two objects''' | self . __require_string__ ( name )
# print ( ' storing relation ' , src , name , dst )
# make sure both items are stored
self . store_item ( src )
self . store_item ( dst )
with self . _write_lock : # print ( locals ( ) )
# run the insertion
self . _execute ( 'insert into relations select ob1.id, ?, ob2.id from obj... |
def signmsg ( msg , priv , iscompressed , k = 0 ) :
'''Sign a message - - the message itself , not a hash - - with a given
private key .
Input private key must be hex , NOT WIF . Use wiftohex ( ) found in
. bitcoin in order to get the hex private key and whether it is
( or rather , its public key is ) compr... | omsg = msg
# Stripping carraige returns is standard practice in every
# implementation I found , including Bitcoin Core
msg = msg . replace ( "\r\n" , "\n" )
msg1 = hexstrlify ( bytearray ( "\x18Bitcoin Signed Message:\n" , 'utf-8' ) )
msg2 = tovarint ( len ( msg ) )
msg3 = hexstrlify ( bytearray ( msg , 'utf-8' ) )
ms... |
def create_branches ( self , branches ) :
"""Create branches from a TreeBuffer or dict mapping names to type names
Parameters
branches : TreeBuffer or dict""" | if not isinstance ( branches , TreeBuffer ) :
branches = TreeBuffer ( branches )
self . set_buffer ( branches , create_branches = True ) |
def execute ( self , * args , ** kwargs ) :
'''Executes all appropriate modules according to the options specified in args / kwargs .
Returns a list of executed module objects .''' | run_modules = [ ]
orig_arguments = self . arguments
if args or kwargs :
self . _set_arguments ( list ( args ) , kwargs )
# Run all modules
for module in self . list ( ) :
obj = self . run ( module )
# Add all loaded modules that marked themselves as enabled to the
# run _ modules list
for ( module , obj ) in it... |
def incrementKeySequenceCounter ( self , iIncrementValue = 1 ) :
"""increment the key sequence with a given value
Args :
iIncrementValue : specific increment value to be added
Returns :
True : successful to increment the key sequence with a given value
False : fail to increment the key sequence with a giv... | print '%s call incrementKeySequenceCounter' % self . port
print iIncrementValue
currentKeySeq = ''
try :
currentKeySeq = self . getKeySequenceCounter ( )
keySequence = int ( currentKeySeq , 10 ) + iIncrementValue
print keySequence
return self . setKeySequenceCounter ( keySequence )
except Exception , e ... |
def _set_get_vnetwork_vswitches ( self , v , load = False ) :
"""Setter method for get _ vnetwork _ vswitches , mapped from YANG variable / brocade _ vswitch _ rpc / get _ vnetwork _ vswitches ( rpc )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ get _ vnetwork _ vswi... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = get_vnetwork_vswitches . get_vnetwork_vswitches , is_leaf = True , yang_name = "get-vnetwork-vswitches" , rest_name = "get-vnetwork-vswitches" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmeth... |
def linterp ( self , setx , sety , x ) :
"""Linear interp of model data values between time steps""" | if math . isnan ( sety [ 0 ] ) or math . isnan ( setx [ 0 ] ) :
return np . nan
# if math . isnan ( sety [ 0 ] ) :
# sety [ 0 ] = 0.
# if math . isnan ( sety [ 1 ] ) :
# sety [ 1 ] = 0.
return sety [ 0 ] + ( x - setx [ 0 ] ) * ( ( sety [ 1 ] - sety [ 0 ] ) / ( setx [ 1 ] - setx [ 0 ] ) ) |
def find_declared_encoding ( cls , markup , is_html = False , search_entire_document = False ) :
"""Given a document , tries to find its declared encoding .
An XML encoding is declared at the beginning of the document .
An HTML encoding is declared in a < meta > tag , hopefully near the
beginning of the docum... | if search_entire_document :
xml_endpos = html_endpos = len ( markup )
else :
xml_endpos = 1024
html_endpos = max ( 2048 , int ( len ( markup ) * 0.05 ) )
declared_encoding = None
declared_encoding_match = xml_encoding_re . search ( markup , endpos = xml_endpos )
if not declared_encoding_match and is_html :
... |
def namedb_flatten_history ( hist ) :
"""Given a name ' s history , flatten it into a list of deltas .
They will be in * increasing * order .""" | ret = [ ]
block_ids = sorted ( hist . keys ( ) )
for block_id in block_ids :
vtxinfos = hist [ block_id ]
for vtxinfo in vtxinfos :
info = copy . deepcopy ( vtxinfo )
ret . append ( info )
return ret |
def _get_all_files ( self , path , * exclude ) :
'''Walk implementation . Version in python 2 . x and 3 . x works differently .''' | files = list ( )
dirs = list ( )
links = list ( )
if os . access ( path , os . R_OK ) :
for obj in os . listdir ( path ) :
obj = os . path . join ( path , obj )
valid = True
for ex_obj in exclude :
if obj . startswith ( str ( ex_obj ) ) :
valid = False
... |
def describe_export ( self , export_type ) :
"""Fetch metadata for an export .
- * * export _ type * * is a string specifying which type of export to look
up .
Returns a : py : class : ` dict ` containing metadata for the export .""" | if export_type in TALK_EXPORT_TYPES :
return talk . get_data_request ( 'project-{}' . format ( self . id ) , export_type . replace ( 'talk_' , '' ) ) [ 0 ]
return self . http_get ( self . _export_path ( export_type ) , ) [ 0 ] |
def resource_present ( name , resource_id , resource_type , resource_options = None , cibname = None ) :
'''Ensure that a resource is created
Should be run on one cluster node only
( there may be races )
Can only be run on a node with a functional pacemaker / corosync
name
Irrelevant , not used ( recommen... | return _item_present ( name = name , item = 'resource' , item_id = resource_id , item_type = resource_type , extra_args = resource_options , cibname = cibname ) |
def initialize_ports ( self ) -> None :
"""Load IO port parameters for device .""" | if not self . params :
self . initialize_params ( preload_data = False )
self . params . update_ports ( )
self . ports = Ports ( self . params , self . request ) |
def _unlock ( self ) :
'''Unlocks the index''' | if self . _devel :
self . logger . debug ( "Unlocking Index" )
if self . _is_locked ( ) :
os . remove ( self . _lck )
return True
else :
return True |
def predict_pRF_radius ( eccentricity , visual_area = 'V1' , source = 'Wandell2015' ) :
'''predict _ pRF _ radius ( eccentricity ) yields an estimate of the pRF size for a patch of cortex at the
given eccentricity in V1.
predict _ pRF _ radius ( eccentricity , area ) yields an estimate in the given visual area ... | visual_area = visual_area . lower ( )
if pimms . is_str ( source ) :
source = source . lower ( )
if source not in pRF_data :
raise ValueError ( 'Given source (%s) not found in pRF-size database' % source )
dat = pRF_data [ source ]
dat = dat [ visual_area ]
else :
dat = { 'm' : source [ 0 ] ... |
def digest_manifest ( self , manifest , java_algorithm = "SHA-256" ) :
"""Create a main section checksum and sub - section checksums based off
of the data from an existing manifest using an algorithm given
by Java - style name .""" | # pick a line separator for creating checksums of the manifest
# contents . We want to use either the one from the given
# manifest , or the OS default if it hasn ' t specified one .
linesep = manifest . linesep or os . linesep
all_key = java_algorithm + "-Digest-Manifest"
main_key = java_algorithm + "-Digest-Manifest-... |
def column_vectors ( self ) :
"""The values of the transform as three 2D column vectors""" | a , b , c , d , e , f , _ , _ , _ = self
return ( a , d ) , ( b , e ) , ( c , f ) |
def mute_string ( text ) :
"""Replace contents with ' xxx ' to prevent syntax matching .
> > > mute _ string ( ' " abc " ' )
' " xxx " '
> > > mute _ string ( " ' ' ' abc ' ' ' " )
" ' ' ' xxx ' ' ' "
> > > mute _ string ( " r ' abc ' " )
" r ' xxx ' " """ | start = 1
end = len ( text ) - 1
# String modifiers ( e . g . u or r )
if text . endswith ( '"' ) :
start += text . index ( '"' )
elif text . endswith ( "'" ) :
start += text . index ( "'" )
# Triple quotes
if text . endswith ( '"""' ) or text . endswith ( "'''" ) :
start += 2
end -= 2
return text [ : s... |
def _parse_content ( self , text ) :
'''Parses the content of a response doc into the correct
format for . state .''' | try :
return json . loads ( text )
except ValueError :
raise exc . UnexpectedlyNotJSON ( "The resource at {.uri} wasn't valid JSON" , self ) |
def make_strain_from_inj_object ( self , inj , delta_t , detector_name , f_lower = None , distance_scale = 1 ) :
"""Make a h ( t ) strain time - series from an injection object as read from
a sim _ inspiral table , for example .
Parameters
inj : injection object
The injection object to turn into a strain h ... | detector = Detector ( detector_name )
if f_lower is None :
f_l = inj . f_lower
else :
f_l = f_lower
name , phase_order = legacy_approximant_name ( inj . waveform )
# compute the waveform time series
hp , hc = get_td_waveform ( inj , approximant = name , delta_t = delta_t , phase_order = phase_order , f_lower = ... |
def scene_on ( self ) :
"""Trigger group / scene to ON level .""" | user_data = Userdata ( { 'd1' : self . _group , 'd2' : 0x00 , 'd3' : 0x00 , 'd4' : 0x11 , 'd5' : 0xff , 'd6' : 0x00 } )
self . _set_sent_property ( DIMMABLE_KEYPAD_SCENE_ON_LEVEL , 0xff )
cmd = ExtendedSend ( self . _address , COMMAND_EXTENDED_TRIGGER_ALL_LINK_0X30_0X00 , user_data )
cmd . set_checksum ( )
_LOGGER . de... |
def find_objects ( self , ObjectClass , ** kwargs ) :
"""Retrieve all objects of type ` ` ObjectClass ` ` ,
matching the specified filters in ` ` * * kwargs ` ` - - case sensitive .""" | filter = None
for k , v in kwargs . items ( ) :
cond = ObjectClass . getattr ( k ) == v
filter = cond if filter is None else filter & cond
return ObjectClass . scan ( filter ) |
def levenshtein ( seq1 , seq2 , normalized = False , max_dist = - 1 ) :
"""Compute the absolute Levenshtein distance between the two sequences
` seq1 ` and ` seq2 ` .
The Levenshtein distance is the minimum number of edit operations necessary
for transforming one sequence into the other . The edit operations ... | if normalized :
return nlevenshtein ( seq1 , seq2 , method = 1 )
if seq1 == seq2 :
return 0
len1 , len2 = len ( seq1 ) , len ( seq2 )
if max_dist >= 0 and abs ( len1 - len2 ) > max_dist :
return - 1
if len1 == 0 :
return len2
if len2 == 0 :
return len1
if len1 < len2 :
len1 , len2 = len2 , len1
... |
def platform ( ) :
"""Return platform for the current shell , e . g . windows or unix""" | executable = parent ( )
basename = os . path . basename ( executable )
basename , _ = os . path . splitext ( basename )
if basename in ( "bash" , "sh" ) :
return "unix"
if basename in ( "cmd" , "powershell" ) :
return "windows"
raise SystemError ( "Unsupported shell: %s" % basename ) |
def request_encode_body ( self , method , url , fields = None , headers = None , encode_multipart = True , multipart_boundary = None , ** urlopen_kw ) :
"""Make a request using : meth : ` urlopen ` with the ` ` fields ` ` encoded in
the body . This is useful for request methods like POST , PUT , PATCH , etc .
W... | if headers is None :
headers = self . headers
extra_kw = { 'headers' : { } }
if fields :
if 'body' in urlopen_kw :
raise TypeError ( "request got values for both 'fields' and 'body', can only specify one." )
if encode_multipart :
body , content_type = encode_multipart_formdata ( fields , bou... |
def get_all_logger_names ( include_root = False ) :
"""Return ` ` list ` ` of names of all loggers than have been accessed .
Warning : this is sensitive to internal structures in the standard logging module .""" | # noinspection PyUnresolvedReferences
rv = list ( logging . Logger . manager . loggerDict . keys ( ) )
if include_root :
rv . insert ( 0 , '' )
return rv |
def select_rows ( cols , rows , mode = 'list' , cast = True ) :
"""Yield data selected from rows .
It is sometimes useful to select a subset of data from a profile .
This function selects the data in * cols * from * rows * and yields it
in a form specified by * mode * . Possible values of * mode * are :
mod... | mode = mode . lower ( )
if mode == 'list' :
modecast = lambda cols , data : data
elif mode == 'dict' :
modecast = lambda cols , data : dict ( zip ( cols , data ) )
elif mode == 'row' :
modecast = lambda cols , data : encode_row ( data )
else :
raise ItsdbError ( 'Invalid mode for select operation: {}\n'... |
def run ( self ) :
"""Initializes the stream .""" | if not hasattr ( self , 'queue' ) :
raise RuntimeError ( "Audio queue is not intialized." )
self . stream . start_stream ( )
self . keep_listening = True
while self . keep_listening :
try :
frame = self . queue . get ( False , timeout = queue_timeout )
self . stream . write ( frame )
except ... |
def spline_functions ( lower_points , upper_points , degree = 3 ) :
"""Method that creates two ( upper and lower ) spline functions based on points lower _ points and upper _ points .
Args :
lower _ points :
Points defining the lower function .
upper _ points :
Points defining the upper function .
degre... | lower_xx = np . array ( [ pp [ 0 ] for pp in lower_points ] )
lower_yy = np . array ( [ pp [ 1 ] for pp in lower_points ] )
upper_xx = np . array ( [ pp [ 0 ] for pp in upper_points ] )
upper_yy = np . array ( [ pp [ 1 ] for pp in upper_points ] )
lower_spline = UnivariateSpline ( lower_xx , lower_yy , k = degree , s =... |
def keras_tuples ( stream , inputs = None , outputs = None ) :
"""Reformat data objects as keras - compatible tuples .
For more detail : https : / / keras . io / models / model / # fit
Parameters
stream : iterable
Stream of data objects .
inputs : string or iterable of strings , None
Keys to use for ord... | flatten_inputs , flatten_outputs = False , False
if inputs and isinstance ( inputs , six . string_types ) :
inputs = [ inputs ]
flatten_inputs = True
if outputs and isinstance ( outputs , six . string_types ) :
outputs = [ outputs ]
flatten_outputs = True
inputs , outputs = ( inputs or [ ] ) , ( outputs... |
def zncc ( ts1 , ts2 ) :
"""Zero mean normalised cross - correlation ( ZNCC )
This function does ZNCC of two signals , ts1 and ts2
Normalisation by very small values is avoided by doing
max ( nmin , nvalue )
Parameters
ts1 : ndarray
Input signal 1 to be aligned with
ts2 : ndarray
Input signal 2
Re... | # Output is the same size as ts1
Ns1 = np . size ( ts1 )
Ns2 = np . size ( ts2 )
ts_out = np . zeros ( ( Ns1 , 1 ) , dtype = 'float64' )
ishift = int ( np . floor ( Ns2 / 2 ) )
# origin of ts2
t1m = np . mean ( ts1 )
t2m = np . mean ( ts2 )
for k in range ( 0 , Ns1 ) :
lstart = np . int ( ishift - k )
if lstart... |
def unArrayify ( self , gene ) :
"""Copies gene bias values and weights to network bias values and
weights .""" | g = 0
# if gene is too small an IndexError will be thrown
for layer in self . layers :
if layer . type != 'Input' :
for i in range ( layer . size ) :
layer . weight [ i ] = float ( gene [ g ] )
g += 1
for connection in self . connections :
for i in range ( connection . fromLayer ... |
def register_elasticapm ( client , worker ) :
"""Given an ElasticAPM client and an RQ worker , registers exception handlers
with the worker so exceptions are logged to the apm server .
E . g . :
from elasticapm . contrib . django . models import client
from elasticapm . contrib . rq import register _ elasti... | def send_to_server ( job , * exc_info ) :
client . capture_exception ( exc_info = exc_info , extra = { "job_id" : job . id , "func" : job . func_name , "args" : job . args , "kwargs" : job . kwargs , "description" : job . description , } , )
worker . push_exc_handler ( send_to_server ) |
def revoke_session ( self , sid = '' , token = '' ) :
"""Mark session as revoked but also explicitly revoke all issued tokens
: param token : any token connected to the session
: param sid : Session identifier""" | if not sid :
if token :
sid = self . handler . sid ( token )
else :
raise ValueError ( 'Need one of "sid" or "token"' )
for typ in [ 'access_token' , 'refresh_token' , 'code' ] :
try :
self . revoke_token ( self [ sid ] [ typ ] , typ )
except KeyError : # If no such token has bee... |
def load_stream ( handle , delimiter = None ) :
"""Creates a string generator from a stream ( file handle ) containing data
delimited by the delimiter strings . This is a stand - alone function and
should be used to feed external data into a pipeline .
Arguments :
- hande ( ` ` file ` ` ) A file handle open... | delimiter = ( delimiter or "" ) + "\n"
while True :
item = [ ]
while True :
line = handle . readline ( )
if line == "" :
raise StopIteration
elif line == delimiter :
if item :
break
elif line != '\n' :
item . append ( line )
... |
def plot_ac ( calc_id ) :
"""Aggregate loss curves plotter .""" | # read the hazard data
dstore = util . read ( calc_id )
agg_curve = dstore [ 'agg_curve-rlzs' ]
plt = make_figure ( agg_curve )
plt . show ( ) |
def init ( self , value ) :
'''hash passwords given in the constructor''' | value = self . value_or_default ( value )
if value is None :
return None
if is_hashed ( value ) :
return value
return make_password ( value ) |
def fullsplit ( path , result = None , base_path = None ) :
"""Split a pathname into components ( the opposite of os . path . join ) in a
platform - neutral way .""" | if base_path :
path = path . replace ( base_path , '' )
if result is None :
result = [ ]
head , tail = os . path . split ( path )
if head == '' :
return [ tail ] + result
if head == path :
return result
return fullsplit ( head , [ tail ] + result ) |
def append ( self , ** kwargs ) :
"""Add commands at the end of the sequence .
Be careful : because this runs in Python 2 . x , the order of the kwargs dict may not match
the order in which the args were specified . Thus , if you care about specific ordering ,
you must make multiple calls to append in that or... | for k , v in six . iteritems ( kwargs ) :
self . commands . append ( { k : v } )
return self |
def resources ( self ) :
"""Retrieve contents of each page of PDF""" | return [ self . pdf . getPage ( i ) for i in range ( self . pdf . getNumPages ( ) ) ] |
def maybe_print_as_json ( opts , data , page_info = None ) :
"""Maybe print data as JSON .""" | if opts . output not in ( "json" , "pretty_json" ) :
return False
root = { "data" : data }
if page_info is not None and page_info . is_valid :
meta = root [ "meta" ] = { }
meta [ "pagination" ] = page_info . as_dict ( num_results = len ( data ) )
if opts . output == "pretty_json" :
dump = json . dumps (... |
def bundles ( ) :
"""Display bundles .""" | per_page = int ( request . args . get ( 'per_page' , 30 ) )
page = int ( request . args . get ( 'page' , 1 ) )
query = store . bundles ( )
query_page = query . paginate ( page , per_page = per_page )
data = [ ]
for bundle_obj in query_page . items :
bundle_data = bundle_obj . to_dict ( )
bundle_data [ 'versions... |
def remove_device ( self , device , id_override = None , type_override = None ) :
"""Remove a device .
Args :
device ( WinkDevice ) : The device the change is being requested for .
id _ override ( String , optional ) : A device ID used to override the
passed in device ' s ID . Used to make changes on sub - ... | object_id = id_override or device . object_id ( )
object_type = type_override or device . object_type ( )
url_string = "{}/{}s/{}" . format ( self . BASE_URL , object_type , object_id )
try :
arequest = requests . delete ( url_string , headers = API_HEADERS )
if arequest . status_code == 204 :
return Tr... |
def calculateKey ( cls , target ) :
"""Calculate the reference key for this reference
Currently this is a two - tuple of the id ( ) ' s of the
target object and the target function respectively .""" | return ( id ( getattr ( target , im_self ) ) , id ( getattr ( target , im_func ) ) ) |
def _dry_message_received ( self , msg ) :
"""Report a dry state .""" | for callback in self . _dry_wet_callbacks :
callback ( LeakSensorState . DRY )
self . _update_subscribers ( 0x11 ) |
async def enqueue ( self , query , queue_index = None , stop_current = False , shuffle = False ) :
"""Queues songs based on either a YouTube search or a link
Args :
query ( str ) : Either a search term or a link
queue _ index ( str ) : The queue index to enqueue at ( None for end )
stop _ current ( bool ) :... | if query is None or query == "" :
return
self . statuslog . info ( "Parsing {}" . format ( query ) )
self . logger . debug ( "Enqueueing from query" )
indexnum = None
if queue_index is not None :
try :
indexnum = int ( queue_index ) - 1
except TypeError :
self . statuslog . error ( "Play ind... |
def get ( self , key , dt ) :
"""Get the value of a cached object .
Parameters
key : any
The key to lookup .
dt : datetime
The time of the lookup .
Returns
result : any
The value for ` ` key ` ` .
Raises
KeyError
Raised if the key is not in the cache or the value for the key
has expired .""" | try :
return self . _cache [ key ] . unwrap ( dt )
except Expired :
self . cleanup ( self . _cache [ key ] . _unsafe_get_value ( ) )
del self . _cache [ key ]
raise KeyError ( key ) |
def pop ( self , key , default = NO_DEFAULT ) :
"""If key is in the flat dictionary , remove it and return its value ,
else return default . If default is not given and key is not in the
dictionary , : exc : ` KeyError ` is raised .
: param mixed key : The key name
: param mixed default : The default value ... | if key not in self and default != NO_DEFAULT :
return default
value = self [ key ]
self . __delitem__ ( key )
return value |
def _set_lsp_commit ( self , v , load = False ) :
"""Setter method for lsp _ commit , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / lsp / secondary _ path / lsp _ commit ( empty )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ lsp _... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGBool , is_leaf = True , yang_name = "lsp-commit" , rest_name = "commit" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions = { u'tailf-common' : { u'... |
def run ( self ) :
"""Run git add and commit with message if provided .""" | if os . system ( 'git add .' ) :
sys . exit ( 1 )
if self . message is not None :
os . system ( 'git commit -a -m "' + self . message + '"' )
else :
os . system ( 'git commit -a' ) |
async def get_constraints ( self ) :
"""Return the machine constraints dict for this application .""" | app_facade = client . ApplicationFacade . from_connection ( self . connection )
log . debug ( 'Getting constraints for %s' , self . name )
result = ( await app_facade . Get ( self . name ) ) . constraints
return vars ( result ) if result else result |
def update_holder ( self , holder ) :
"""Udpate the Holder state according to the occurrence .
This implementation is a example of how a Occurrence object
can update the Holder state ; this method should be overriden
by classes that inherit from the Occurrence class .
This sample implementation simply updat... | subject_symbol = self . subject . symbol
# If the Holder already have a state regarding this Subject ,
# update that state
if subject_symbol in holder . state : # If the Holder have zero units of this subject , the average
# value paid / received for the subject is the value of the trade itself
if not holder . stat... |
def make_strain_from_inj_object ( self , inj , delta_t , detector_name , f_lower = None , distance_scale = 1 ) :
"""Make a h ( t ) strain time - series from an injection object .
Parameters
inj : injection object
The injection object to turn into a strain h ( t ) . Can be any
object which has waveform param... | detector = Detector ( detector_name )
if f_lower is None :
f_l = inj . f_lower
else :
f_l = f_lower
# compute the waveform time series
hp , hc = get_td_waveform ( inj , delta_t = delta_t , f_lower = f_l , ** self . extra_args )
hp /= distance_scale
hc /= distance_scale
hp . _epoch += inj . tc
hc . _epoch += inj... |
def classes ( self , name = None , function = None , header_dir = None , header_file = None , recursive = None , allow_empty = None ) :
"""returns a set of class declarations , that are matched defined
criteria""" | return ( self . _find_multiple ( self . _impl_matchers [ scopedef_t . class_ ] , name = name , function = function , decl_type = self . _impl_decl_types [ scopedef_t . class_ ] , header_dir = header_dir , header_file = header_file , recursive = recursive , allow_empty = allow_empty ) ) |
def find_hass_config ( ) :
"""Try to find HASS config .""" | if "HASSIO_TOKEN" in os . environ :
return "/config"
config_dir = default_hass_config_dir ( )
if os . path . isdir ( config_dir ) :
return config_dir
raise ValueError ( "Unable to automatically find the location of Home Assistant " "config. Please pass it in." ) |
def to_json ( self ) :
"""Serialize to JSON , which can be returned e . g . via RPC""" | ret = { 'address' : self . address , 'domain' : self . domain , 'block_number' : self . block_height , 'sequence' : self . n , 'txid' : self . txid , 'value_hash' : get_zonefile_data_hash ( self . zonefile_str ) , 'zonefile' : base64 . b64encode ( self . zonefile_str ) , 'name' : self . get_fqn ( ) , }
if self . pendin... |
def add_company_quarter ( self , company_name , quarter_name , dt , calendar_id = 'notices' ) :
'''Adds a company _ name quarter event to the calendar . dt should be a date object . Returns True if the event was added .''' | assert ( calendar_id in self . configured_calendar_ids . keys ( ) )
calendarId = self . configured_calendar_ids [ calendar_id ]
quarter_name = quarter_name . title ( )
quarter_numbers = { 'Spring' : 1 , 'Summer' : 2 , 'Fall' : 3 , 'Winter' : 4 }
assert ( quarter_name in quarter_numbers . keys ( ) )
start_time = datetim... |
def _qmed_from_pot_records ( self ) :
"""Return QMED estimate based on peaks - over - threshold ( POT ) records .
Methodology source : FEH , Vol . 3 , pp . 77-78
: return : QMED in m3 / s
: rtype : float""" | pot_dataset = self . catchment . pot_dataset
if not pot_dataset :
raise InsufficientDataError ( "POT dataset must be set for catchment {} to estimate QMED from POT data." . format ( self . catchment . id ) )
complete_year_records , length = self . _complete_pot_years ( pot_dataset )
if length < 1 :
raise Insuff... |
def update ( self , name = None , metadata = None ) :
"""Updates this webhook . One or more of the parameters may be specified .""" | return self . policy . update_webhook ( self , name = name , metadata = metadata ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.