signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def load_resource ( resource_url : str , forceupdate : bool = False ) :
"""Load BEL Resource file
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists .
Args :
resource _ url : URL from which to download the resource to load into the BE... | log . info ( f"Loading resource {resource_url}" )
try : # Download resource
fo = bel . utils . download_file ( resource_url )
if not fo :
log . error ( f"Could not download and open file {resource_url}" )
return "Failed to download resource_url"
# Get metadata
fo . seek ( 0 )
with gz... |
def parse ( cls , parser , text , pos ) :
"""Parse InspireKeyword .
If the keyword is ` texkey ` , enable the parsing texkey expression flag , since its value contains ' : ' which
normally isn ' t allowed .""" | try :
remaining_text , keyword = parser . parse ( text , cls . grammar )
if keyword . lower ( ) == 'texkey' :
parser . _parsing_texkey_expression = True
return remaining_text , InspireKeyword ( keyword )
except SyntaxError as e :
parser . _parsing_texkey_expression = False
return text , e |
def create_client ( self , client_id , client_secret , manifest = None , client_credentials = True , refresh_token = True , authorization_code = False , redirect_uri = [ ] ) :
"""Will create a new client for your application use .
- client _ credentials : allows client to get access token
- refresh _ token : ca... | self . assert_has_permission ( 'clients.admin' )
if authorization_code and not redirect_uri :
raise ValueError ( "Must provide a redirect_uri for clients used with authorization_code" )
# Check if client already exists
client = self . get_client ( client_id )
if client :
return client
uri = self . uri + '/oauth... |
def require ( self , lock , guard_func , * guard_args , ** guard_kw ) :
"""Decorate a function to be run only when a lock is acquired .
The lock is requested if the guard function returns True .
The decorated function is called if the lock has been granted .""" | def decorator ( f ) :
@ wraps ( f )
def wrapper ( * args , ** kw ) :
if self . granted ( lock ) :
self . msg ( 'Granted {}' . format ( lock ) )
return f ( * args , ** kw )
if guard_func ( * guard_args , ** guard_kw ) and self . acquire ( lock ) :
return f ( * ... |
def _build_mountpoint ( self , volume ) :
"""Given a generic volume definition , create the mountPoints element""" | self . add_volume ( self . _build_volume ( volume ) )
return { 'sourceVolume' : self . path_to_name ( volume . get ( 'host' ) ) , 'containerPath' : volume . get ( 'container' ) } |
def _nemo_accpars ( self , vo , ro ) :
"""NAME :
_ nemo _ accpars
PURPOSE :
return the accpars potential parameters for use of this potential with NEMO
INPUT :
vo - velocity unit in km / s
ro - length unit in kpc
OUTPUT :
accpars string
HISTORY :
2014-12-18 - Written - Bovy ( IAS )""" | warnings . warn ( "NEMO's LogPot does not allow flattening in z (for some reason); therefore, flip y and z in NEMO wrt galpy; also does not allow the triaxial b parameter" , galpyWarning )
ampl = self . _amp * vo ** 2.
return "0,%s,%s,1.0,%s" % ( ampl , self . _core2 * ro ** 2. * self . _q ** ( 2. / 3. ) , # somewhat w... |
def export_pages ( root_page , export_unpublished = False ) :
"""Create a JSON defintion of part of a site ' s page tree starting
from root _ page and descending into its descendants
By default only published pages are exported .
If a page is unpublished it and all its descendants are pruned even
if some of... | pages = Page . objects . descendant_of ( root_page , inclusive = True ) . order_by ( 'path' ) . specific ( )
if not export_unpublished :
pages = pages . filter ( live = True )
page_data = [ ]
exported_paths = set ( )
for ( i , page ) in enumerate ( pages ) :
parent_path = page . path [ : - ( Page . steplen ) ]
... |
def calculate_sunrise_sunset ( self , month , day , depression = 0.833 , is_solar_time = False ) :
"""Calculate sunrise , noon and sunset .
Return :
A dictionary . Keys are ( " sunrise " , " noon " , " sunset " )""" | datetime = DateTime ( month , day , hour = 12 , leap_year = self . is_leap_year )
return self . calculate_sunrise_sunset_from_datetime ( datetime , depression , is_solar_time ) |
def remove_tag ( self , name , user , message = None , date = None ) :
"""Removes tag with the given ` ` name ` ` .
: param name : name of the tag to be removed
: param user : full username , i . e . : " Joe Doe < joe . doe @ example . com > "
: param message : message of the tag ' s removal commit
: param ... | if name not in self . tags :
raise TagDoesNotExistError ( "Tag %s does not exist" % name )
tagpath = posixpath . join ( self . _repo . refs . path , 'refs' , 'tags' , name )
try :
os . remove ( tagpath )
self . _parsed_refs = self . _get_parsed_refs ( )
self . tags = self . _get_tags ( )
except OSError ... |
def previous_active_pane ( self ) :
"""The previous active : class : ` . Pane ` or ` None ` if unknown .""" | p = self . _prev_active_pane and self . _prev_active_pane ( )
# Only return when this pane actually still exists in the current
# window .
if p and p in self . panes :
return p |
async def answer_inline_query ( self , inline_query_id : base . String , results : typing . List [ types . InlineQueryResult ] , cache_time : typing . Union [ base . Integer , None ] = None , is_personal : typing . Union [ base . Boolean , None ] = None , next_offset : typing . Union [ base . String , None ] = None , s... | results = prepare_arg ( results )
payload = generate_payload ( ** locals ( ) )
result = await self . request ( api . Methods . ANSWER_INLINE_QUERY , payload )
return result |
def order_by_on_list ( objects , order_field , is_desc = False ) :
"""Utility function to sort objects django - style even for non - query set collections
: param objects : list of objects to sort
: param order _ field : field name , follows django conventions , so " foo _ _ bar " means ` foo . bar ` , can be a... | if callable ( order_field ) :
objects . sort ( key = order_field , reverse = is_desc )
return
def order_key ( x ) :
v = getattr_path ( x , order_field )
if v is None :
return MIN
return v
objects . sort ( key = order_key , reverse = is_desc ) |
def _sliced_shape ( self , shapes , i , major_axis ) :
"""Get the sliced shapes for the i - th executor .
Parameters
shapes : list of ( str , tuple )
The original ( name , shape ) pairs .
i : int
Which executor we are dealing with .""" | sliced_shapes = [ ]
for desc , axis in zip ( shapes , major_axis ) :
shape = list ( desc . shape )
if axis >= 0 :
shape [ axis ] = self . slices [ i ] . stop - self . slices [ i ] . start
sliced_shapes . append ( DataDesc ( desc . name , tuple ( shape ) , desc . dtype , desc . layout ) )
return slic... |
def check_geographic_region ( self , ds ) :
"""6.1.1 When data is representative of geographic regions which can be identified by names but which have complex
boundaries that cannot practically be specified using longitude and latitude boundary coordinates , a labeled
axis should be used to identify the regions... | ret_val = [ ]
region_list = [ # TODO maybe move this ( and other info like it ) into a config file ?
'africa' , 'antarctica' , 'arabian_sea' , 'aral_sea' , 'arctic_ocean' , 'asia' , 'atlantic_ocean' , 'australia' , 'baltic_sea' , 'barents_opening' , 'barents_sea' , 'beaufort_sea' , 'bellingshausen_sea' , 'bering_sea' ,... |
def sign ( self , msg , key ) :
"""Create a signature over a message as defined in RFC7515 using an
RSA key
: param msg : the message .
: type msg : bytes
: returns : bytes , the signature of data .
: rtype : bytes""" | if not isinstance ( key , rsa . RSAPrivateKey ) :
raise TypeError ( "The key must be an instance of rsa.RSAPrivateKey" )
sig = key . sign ( msg , self . padding , self . hash )
return sig |
def imagetransformer2d_base_8l_8_32_big ( ) :
"""hparams fo 8 layer big 2d model for cifar 10.""" | hparams = image_transformer2d_base ( )
hparams . num_heads = 16
hparams . hidden_size = 1024
hparams . filter_size = 2048
hparams . num_decoder_layers = 8
hparams . batch_size = 1
hparams . layer_prepostprocess_dropout = 0.3
hparams . query_shape = ( 8 , 16 )
hparams . memory_flange = ( 0 , 32 )
hparams . unconditional... |
def fetch_defense_data ( self ) :
"""Lazy initialization of data necessary to execute defenses .""" | if self . defenses_data_initialized :
return
logging . info ( 'Fetching defense data from datastore' )
# init data from datastore
self . submissions . init_from_datastore ( )
self . dataset_batches . init_from_datastore ( )
self . adv_batches . init_from_datastore ( )
# read dataset metadata
self . read_dataset_met... |
def is_script ( self , container ) :
"""Returns ` True ` if this styled text is super / subscript .""" | try :
style = self . _style ( container )
return style . get_value ( 'position' , container ) != TextPosition . NORMAL
except StyleException :
return False |
def setSingleStep ( self , singleStep ) :
"""setter to _ singleStep . converts negativ values to positiv ones .
Args :
singleStep ( int ) : new _ singleStep value . converts negativ values to positiv ones .
Raises :
TypeError : If the given argument is not an integer .
Returns :
int or long : the absolu... | if not isinstance ( singleStep , int ) :
raise TypeError ( "Argument is not of type int" )
# don ' t use negative values
self . _singleStep = abs ( singleStep )
return self . _singleStep |
def start_service ( self , stack , service ) :
"""启动服务
启动指定名称服务的所有容器 。
Args :
- stack : 服务所属的服务组名称
- service : 服务名
Returns :
返回一个tuple对象 , 其格式为 ( < result > , < ResponseInfo > )
- result 成功返回空dict { } , 失败返回 { " error " : " < errMsg string > " }
- ResponseInfo 请求的Response信息""" | url = '{0}/v3/stacks/{1}/services/{2}/start' . format ( self . host , stack , service )
return self . __post ( url ) |
def find_free_prefix ( self , auth , vrf , args ) :
"""Finds free prefixes in the sources given in ` args ` .
* ` auth ` [ BaseAuth ]
AAA options .
* ` vrf ` [ vrf ]
Full VRF - dict specifying in which VRF the prefix should be
unique .
* ` args ` [ find _ free _ prefix _ args ]
Arguments to the find f... | # input sanity
if type ( args ) is not dict :
raise NipapInputError ( "invalid input, please provide dict as args" )
# TODO : find good default value for max _ num
# TODO : let max _ num be configurable from configuration file
max_count = 1000
if 'count' in args :
if int ( args [ 'count' ] ) > max_count :
... |
def destruct ( particles , index ) :
"""Fermion annihilation operator in matrix representation for a indexed
particle in a bounded N - particles fermion fock space""" | mat = np . zeros ( ( 2 ** particles , 2 ** particles ) )
flipper = 2 ** index
for i in range ( 2 ** particles ) :
ispin = btest ( i , index )
if ispin == 1 :
mat [ i ^ flipper , i ] = phase ( i , index )
return csr_matrix ( mat ) |
def addr ( self , address ) :
'''returns dictionary with frame information for given address ( a tuple of two hex numbers )''' | if isinstance ( address , basestring ) : # If you just gave me a single string , assume its " XXXX XXXX "
addr = address . split ( )
else :
addr = list ( address )
# Convert to actual hex if you give me strings
for i in xrange ( len ( addr ) ) :
if isinstance ( addr [ i ] , basestring ) :
addr [ i ]... |
def delete_endpoint_subscriptions ( self , device_id , ** kwargs ) : # noqa : E501
"""Delete subscriptions from an endpoint # noqa : E501
Deletes all resource subscriptions in a single endpoint . * * Example usage : * * curl - X DELETE \\ https : / / api . us - east - 1 . mbedcloud . com / v2 / subscriptions / { ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . delete_endpoint_subscriptions_with_http_info ( device_id , ** kwargs )
# noqa : E501
else :
( data ) = self . delete_endpoint_subscriptions_with_http_info ( device_id , ** kwargs )
# noqa : E501
return data |
def simple_locking ( lock_id , expiration = None ) :
"""A decorator that wraps a function in a single lock getting algorithm""" | def inner_decorator ( function ) :
def wrapper ( * args , ** kwargs ) :
try : # Trying to acquire lock
lock = Lock . acquire_lock ( lock_id , expiration )
except LockError : # Unable to acquire lock - non fatal
pass
else : # Lock acquired , proceed normally , release ... |
def GenerateHelpText ( self , env , sort = None ) :
"""Generate the help text for the options .
env - an environment that is used to get the current values
of the options .
cmp - Either a function as follows : The specific sort function should take two arguments and return - 1 , 0 or 1
or a boolean to indic... | if callable ( sort ) :
options = sorted ( self . options , key = cmp_to_key ( lambda x , y : sort ( x . key , y . key ) ) )
elif sort is True :
options = sorted ( self . options , key = lambda x : x . key )
else :
options = self . options
def format ( opt , self = self , env = env ) :
if opt . key in en... |
def create_saved_search ( self , ** kwargs ) : # noqa : E501
"""Create a saved search # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . create _ saved _ search ( async _ req = True ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . create_saved_search_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . create_saved_search_with_http_info ( ** kwargs )
# noqa : E501
return data |
def extended_flag ( self , which , new = None ) :
"""Get or set a extended flag .
' which ' can be either a string ( ' SERIAL _ API _ VISIBLE ' etc . ) , or an integer .
You should ALWAYS use a string , unless you really know what you are doing .""" | flag = _get_flag ( which , ExtendedFlags )
if flag :
if not self . capabilities . have_extended_flag ( flag ) :
raise yubikey_base . YubiKeyVersionError ( 'Extended flag %s requires %s, and this is %s %d.%d' % ( which , flag . req_string ( self . capabilities . model ) , self . capabilities . model , self .... |
def removeFileSafely ( filename , clobber = True ) :
"""Delete the file specified , but only if it exists and clobber is True .""" | if filename is not None and filename . strip ( ) != '' :
if os . path . exists ( filename ) and clobber :
os . remove ( filename ) |
def _removecleaner ( self , cleaner ) :
"""Remove the cleaner from the list if it already exists . Returns True if
the cleaner was removed .""" | oldlen = len ( self . _old_cleaners )
self . _old_cleaners = [ oldc for oldc in self . _old_cleaners if not oldc . issame ( cleaner ) ]
return len ( self . _old_cleaners ) != oldlen |
async def get_metrics ( self , element ) :
"""Get all the metrics for a monitored element .""" | await self . get_data ( )
await self . get_plugins ( )
if element in self . plugins :
self . values = self . data [ element ]
else :
raise exceptions . GlancesApiError ( "Element data not available" ) |
def adjustPhase ( self , adjustment ) :
"""Adjust the accelerating phase of the cavity by the value of ` ` adjustment ` ` .
The adjustment is additive , so a value of ` ` scalingFactor = 0.0 ` ` will result
in no change of the phase .""" | self . phase = self . phase . _replace ( val = self . phase . val + adjustment ) |
def find_group_consistencies ( groups1 , groups2 ) :
r"""Returns a measure of group consistency
Example :
> > > # ENABLE _ DOCTEST
> > > from utool . util _ alg import * # NOQA
> > > groups1 = [ [ 1 , 2 , 3 ] , [ 4 ] , [ 5 , 6 ] ]
> > > groups2 = [ [ 1 , 2 ] , [ 4 ] , [ 5 , 6 ] ]
> > > common _ groups =... | group1_list = { tuple ( sorted ( _group ) ) for _group in groups1 }
group2_list = { tuple ( sorted ( _group ) ) for _group in groups2 }
common_groups = list ( group1_list . intersection ( group2_list ) )
return common_groups |
def create_table ( self , model_class ) :
'''Creates a table for the given model class , if it does not exist already .''' | if model_class . is_system_model ( ) :
raise DatabaseException ( "You can't create system table" )
if getattr ( model_class , 'engine' ) is None :
raise DatabaseException ( "%s class must define an engine" % model_class . __name__ )
self . _send ( model_class . create_table_sql ( self ) ) |
def dict_of ( validate_key , validate_item ) :
"""Returns a validator function that succeeds only if the input is a dict , and each key and value in the dict passes
as input to the provided validators validate _ key and validate _ item , respectively .
: param callable validate _ key : the validator function fo... | def validate ( value , should_raise = True ) :
validate_type = is_type ( dict )
if not validate_type ( value , should_raise = should_raise ) :
return False
for key , item in value . items ( ) :
try :
validate_key ( key )
except TypeError as e :
if should_raise... |
def content_present ( self , x : int , y : int ) -> bool :
"""Determines if a line or printed text is at the given location .""" | # Text ?
if ( x , y ) in self . entries :
return True
# Vertical line ?
if any ( v . x == x and v . y1 < y < v . y2 for v in self . vertical_lines ) :
return True
# Horizontal line ?
if any ( line_y == y and x1 < x < x2 for line_y , x1 , x2 , _ in self . horizontal_lines ) :
return True
return False |
def align_CONLL_with_Text ( lines , text , feature_generator , ** kwargs ) :
'''Aligns CONLL format syntactic analysis ( a list of strings ) with given EstNLTK ' s Text
object .
Basically , for each word position in the Text object , finds corresponding line ( s ) in
the CONLL format output ;
Returns a list... | from estnltk . text import Text
if not isinstance ( text , Text ) :
raise Exception ( '(!) Unexpected type of input argument! Expected EstNLTK\'s Text. ' )
if not isinstance ( lines , list ) :
raise Exception ( '(!) Unexpected type of input argument! Expected a list of strings.' )
try :
granularity = featur... |
def json ( cls , status_code , process ) :
"""Callback to validate and extract a JSON object .
The returned callback checks a given response for the given
status _ code using : function : ` response _ boolean ` . On success the
response JSON is parsed and returned .
Args :
status _ code ( int ) : The http... | def func ( response ) :
ret = None
if cls . boolean ( status_code ) ( response ) :
ret = response . json ( ) or { }
return process ( ret )
return func |
def approx_contains ( self , point , atol ) :
"""Return ` ` True ` ` if ` ` point ` ` is " almost " contained in this set .
Parameters
point : ` array - like ` or float
Point to be tested . Its length must be equal to ` ndim ` .
In the 1d case , ` ` point ` ` can be given as a float .
atol : float
Maxim... | try : # Duck - typed check of type
point = np . array ( point , dtype = np . float , copy = False , ndmin = 1 )
except ( ValueError , TypeError ) :
return False
if point . size == 0 :
return True
elif point . shape != ( self . ndim , ) :
return False
return self . dist ( point , exponent = np . inf ) <=... |
def compileUiDir ( dir , recurse = False , map = None , ** compileUi_args ) :
"""compileUiDir ( dir , recurse = False , map = None , * * compileUi _ args )
Creates Python modules from Qt Designer . ui files in a directory or
directory tree .
dir is the name of the directory to scan for files whose name ends w... | import os
# Compile a single . ui file .
def compile_ui ( ui_dir , ui_file ) : # Ignore if it doesn ' t seem to be a . ui file .
if ui_file . endswith ( '.ui' ) :
py_dir = ui_dir
py_file = ui_file [ : - 3 ] + '.py'
# Allow the caller to change the name of the . py file or generate
# ... |
def run ( tpu_job_name , tpu , gcp_project , tpu_zone , model_dir , model_type = "bitransformer" , vocabulary = gin . REQUIRED , train_dataset_fn = None , eval_dataset_fn = None , dataset_split = "train" , autostack = True , checkpoint_path = "" , mode = "train" , iterations_per_loop = 100 , save_checkpoints_steps = 10... | if not isinstance ( batch_size , int ) :
batch_size = batch_size ( sequence_length , mesh_shape , layout_rules )
tf . logging . info ( "mode=%s" % mode , )
tf . logging . info ( "batch_size=%s" % batch_size , )
tf . logging . info ( "sequence_length=%s" % sequence_length , )
tf . logging . info ( "mesh_shape=%s" % ... |
def to_json ( value , ** kwargs ) :
"""Convert instance to JSON""" | if isinstance ( value , HasProperties ) :
return value . serialize ( ** kwargs )
try :
return json . loads ( json . dumps ( value ) )
except TypeError :
raise TypeError ( "Cannot convert type {} to JSON without calling 'serialize' " "on an instance of Instance Property and registering a custom " "serializer... |
def split_query ( qs , keep_blank_values = False ) :
'''Split the query string .
Note for empty values : If an equal sign ( ` ` = ` ` ) is present , the value
will be an empty string ( ` ` ' ' ` ` ) . Otherwise , the value will be ` ` None ` ` : :
> > > list ( split _ query ( ' a = & b ' , keep _ blank _ valu... | items = [ ]
for pair in qs . split ( '&' ) :
name , delim , value = pair . partition ( '=' )
if not delim and keep_blank_values :
value = None
if keep_blank_values or value :
items . append ( ( name , value ) )
return items |
def install_from_rpm_py_package ( self ) :
"""Run install from RPM Python binding RPM package .""" | self . _download_and_extract_rpm_py_package ( )
# Find . / usr / lib64 / pythonN . N / site - packages / rpm directory .
# A binary built by same version Python with used Python is target
# for the safe installation .
if self . rpm . has_set_up_py_in ( ) : # If RPM has setup . py . in , this strict check is okay .
# Be... |
def weekday ( cls , year , month , day ) :
"""Returns the weekday of the date . 0 = aaitabar""" | return NepDate . from_bs_date ( year , month , day ) . weekday ( ) |
def register_action ( action ) :
"""Adds an action to the parser cli .
: param action ( BaseAction ) : a subclass of the BaseAction class""" | sub = _subparsers . add_parser ( action . meta ( 'cmd' ) , help = action . meta ( 'help' ) )
sub . set_defaults ( cmd = action . meta ( 'cmd' ) )
for ( name , arg ) in action . props ( ) . items ( ) :
sub . add_argument ( arg . name , arg . flag , ** arg . options )
_actions [ action . meta ( 'cmd' ) ] = action |
def fit ( self , X , y = None ) :
"""Fits the GraphLasso covariance model to X .
Closely follows sklearn . covariance . graph _ lasso . GraphLassoCV .
Parameters
X : ndarray , shape ( n _ samples , n _ features )
Data from which to compute the covariance estimate""" | # quic - specific outputs
self . opt_ = None
self . cputime_ = None
self . iters_ = None
self . duality_gap_ = None
# these must be updated upon self . fit ( )
self . sample_covariance_ = None
self . lam_scale_ = None
self . is_fitted_ = False
# initialize
X = check_array ( X , ensure_min_features = 2 , estimator = sel... |
def clear ( self ) :
"""Clear all contents in the relay memory""" | self . states [ : ] = 0
self . actions [ : ] = 0
self . rewards [ : ] = 0
self . terminate_flags [ : ] = 0
self . top = 0
self . size = 0 |
def pythonize ( self , val ) :
"""Convert value into a address ip format : :
* If value is a list , try to take the last element
* match ip address and port ( if available )
: param val : value to convert
: type val :
: return : address / port corresponding to value
: rtype : dict""" | val = unique_value ( val )
matches = re . match ( r"^([^:]*)(?::(\d+))?$" , val )
if matches is None :
raise ValueError
addr = { 'address' : matches . group ( 1 ) }
if matches . group ( 2 ) is not None :
addr [ 'port' ] = int ( matches . group ( 2 ) )
return addr |
def find_library ( library_root , additional_places = None ) :
"""Returns the name of the library without extension
: param library _ root : root of the library to search , for example " cfitsio _ " will match libcfitsio _ 1.2.3.4 . so
: return : the name of the library found ( NOTE : this is * not * the path )... | # find _ library searches for all system paths in a system independent way ( but NOT those defined in
# LD _ LIBRARY _ PATH or DYLD _ LIBRARY _ PATH )
first_guess = ctypes . util . find_library ( library_root )
if first_guess is not None : # Found in one of the system paths
if sys . platform . lower ( ) . find ( "l... |
def matches ( self , * args , ** kwargs ) :
"""Test if a request matches a : ref : ` message spec < message spec > ` .
Returns ` ` True ` ` or ` ` False ` ` .""" | request = make_prototype_request ( * args , ** kwargs )
if self . _prototype . opcode not in ( None , request . opcode ) :
return False
if self . _prototype . is_command not in ( None , request . is_command ) :
return False
for name in dir ( self . _prototype ) :
if name . startswith ( '_' ) or name in requ... |
def add_proof ( self , text , publisher_account , keeper ) :
"""Add a proof to the DDO , based on the public _ key id / index and signed with the private key
add a static proof to the DDO , based on one of the public keys .""" | # just incase clear out the current static proof property
self . _proof = None
self . _proof = { 'type' : PROOF_TYPE , 'created' : DDO . _get_timestamp ( ) , 'creator' : publisher_account . address , 'signatureValue' : keeper . sign_hash ( text , publisher_account ) , } |
def set_default ( self , section , option , default ) :
"""If the option did not exist , create a default value .""" | if not self . parser . has_option ( section , option ) :
self . parser . set ( section , option , default ) |
def create_project ( name , include_examples = True ) :
'''creates the initial project skeleton and files
: param name : the project name
: return :''' | # from the start directory , create a project directory with the project name
path = "{}/{}" . format ( os . getcwd ( ) , name )
if os . path . exists ( path ) :
return None , "path {} already exists" . format ( path )
print ( bright ( "creating new ezo project '{}" . format ( name ) ) )
# make project directory
os... |
def fit ( self , dpp_vector ) :
"""Finds row of self . dpp _ matrix most closely corresponds to X by means
of Kendall tau distance .
https : / / en . wikipedia . org / wiki / Kendall _ tau _ distance
Args :
dpp _ vector ( np . array ) : Array with shape ( n _ components , )""" | # decompose X and generate the rankings of the elements in the
# decomposed matrix
dpp_vector_decomposed = self . mf_model . transform ( dpp_vector )
dpp_vector_ranked = stats . rankdata ( dpp_vector_decomposed , method = 'dense' , )
max_agreement_index = None
max_agreement = - 1
# min value of Kendall Tau agremment
fo... |
def get_parser ( commands ) :
"""Generate argument parser given a list of subcommand specifications .
: type commands : list of ( str , function , function )
: arg commands :
Each element must be a tuple ` ` ( name , adder , runner ) ` ` .
: param name : subcommand
: param adder : a function takes one obj... | parser = argparse . ArgumentParser ( formatter_class = Formatter , description = __doc__ , epilog = EPILOG , )
subparsers = parser . add_subparsers ( )
for ( name , adder , runner ) in commands :
subp = subparsers . add_parser ( name , formatter_class = Formatter , description = runner . __doc__ and textwrap . dede... |
def _parse_ppm_segment ( self , fptr ) :
"""Parse the PPM segment .
Parameters
fptr : file
Open file object .
Returns
PPMSegment
The current PPM segment .""" | offset = fptr . tell ( ) - 2
read_buffer = fptr . read ( 3 )
length , zppm = struct . unpack ( '>HB' , read_buffer )
numbytes = length - 3
read_buffer = fptr . read ( numbytes )
return PPMsegment ( zppm , read_buffer , length , offset ) |
def process_npdu ( self , npdu ) :
"""encode NPDUs from the service access point and send them downstream .""" | if _debug :
DeviceToDeviceServerService . _debug ( "process_npdu %r" , npdu )
# broadcast messages go to peers
if npdu . pduDestination . addrType == Address . localBroadcastAddr :
destList = self . connections . keys ( )
else :
if npdu . pduDestination not in self . connections :
if _debug :
... |
def q_mentioned_fields ( q , model ) :
"""Returns list of field names mentioned in Q object .
Q ( a _ _ isnull = True , b = F ( ' c ' ) ) - > [ ' a ' , ' b ' , ' c ' ]""" | query = Query ( model )
where = query . _add_q ( q , used_aliases = set ( ) , allow_joins = False ) [ 0 ]
return list ( sorted ( set ( expression_mentioned_fields ( where ) ) ) ) |
def add_subjects_to_group ( self , group_id , body , ** kwargs ) : # noqa : E501
"""Add members to a group . # noqa : E501
An endpoint for adding users and API keys to a group . * * Example usage : * * ` curl - X POST https : / / api . us - east - 1 . mbedcloud . com / v3 / policy - groups / { group - id } - d ' ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . add_subjects_to_group_with_http_info ( group_id , body , ** kwargs )
# noqa : E501
else :
( data ) = self . add_subjects_to_group_with_http_info ( group_id , body , ** kwargs )
# noqa : E501
return data |
def append ( self , term , type = None , value = None ) :
"""Appends the given term to the taxonomy and tags it as the given type .
Optionally , a disambiguation value can be supplied .
For example : taxonomy . append ( " many " , " quantity " , " 50-200 " )""" | term = self . _normalize ( term )
type = self . _normalize ( type )
self . setdefault ( term , ( odict ( ) , odict ( ) ) ) [ 0 ] . push ( ( type , True ) )
self . setdefault ( type , ( odict ( ) , odict ( ) ) ) [ 1 ] . push ( ( term , True ) )
self . _values [ term ] = value |
def get_facility_status ( self , facility ) :
"""Get the current status of a Guest Additions facility .
in facility of type : class : ` AdditionsFacilityType `
Facility to check status for .
out timestamp of type int
Timestamp ( in ms ) of last status update seen by the host .
return status of type : clas... | if not isinstance ( facility , AdditionsFacilityType ) :
raise TypeError ( "facility can only be an instance of type AdditionsFacilityType" )
( status , timestamp ) = self . _call ( "getFacilityStatus" , in_p = [ facility ] )
status = AdditionsFacilityStatus ( status )
return ( status , timestamp ) |
def to_iso_time_string ( self ) -> str :
"""Return the iso time string only""" | short_time = self . to_short_time_string ( )
second = self . time . second
return f"{short_time}:{second:02}" |
def acquire ( self ) :
"""Acquire the lock
Raises :
IOError : if the call to flock fails""" | self . _fd = open ( self . _path , mode = 'w+' )
os . chmod ( self . _path , 0o660 )
fcntl . flock ( self . _fd , self . _op ) |
def average_time_bounds ( ds ) :
"""Return the average of each set of time bounds in the Dataset .
Useful for creating a new time array to replace the Dataset ' s native time
array , in the case that the latter matches either the start or end bounds .
This can cause errors in grouping ( akin to an off - by - ... | bounds = ds [ TIME_BOUNDS_STR ]
new_times = bounds . mean ( dim = BOUNDS_STR , keep_attrs = True )
new_times = new_times . drop ( TIME_STR ) . rename ( TIME_STR )
new_times [ TIME_STR ] = new_times
return new_times |
def mqtt_subscribe ( self , topics , packet_id ) :
""": param topics : array of topics [ { ' filter ' : ' / a / b ' , ' qos ' : 0x00 } , . . . ]
: return :""" | # Build and send SUBSCRIBE message
subscribe = SubscribePacket . build ( topics , packet_id )
yield from self . _send_packet ( subscribe )
# Wait for SUBACK is received
waiter = futures . Future ( loop = self . _loop )
self . _subscriptions_waiter [ subscribe . variable_header . packet_id ] = waiter
return_codes = yiel... |
def _characterize_header ( self , header , hgroups ) :
"""Characterize header groups into different data types .""" | out = [ ]
for h in [ header [ g [ 0 ] ] for g in hgroups ] :
this_ctype = None
for ctype , names in self . _col_types . items ( ) :
if h . startswith ( names ) :
this_ctype = ctype
break
out . append ( this_ctype )
return out |
def get_webpack ( request , name = 'DEFAULT' ) :
"""Get the Webpack object for a given webpack config .
Called at most once per request per config name .""" | if not hasattr ( request , '_webpack_map' ) :
request . _webpack_map = { }
wp = request . _webpack_map . get ( name )
if wp is None :
wp = request . _webpack_map [ name ] = Webpack ( request , name )
return wp |
def walk_snmp_values ( sess , helper , oid , check ) :
"""return a snmp value or exits the plugin with unknown""" | try :
snmp_walk = sess . walk_oid ( oid )
result_list = [ ]
for x in range ( len ( snmp_walk ) ) :
result_list . append ( snmp_walk [ x ] . val )
if result_list != [ ] :
return result_list
else :
raise SnmpException ( "No content" )
except SnmpException :
helper . exit ( ... |
def int ( self , q ) :
"""Converts the chimera _ index ` q ` into an linear _ index
Parameters
q : tuple
The chimera _ index node label
Returns
r : int
The linear _ index node label corresponding to q""" | u , w , k , z = q
m , m1 = self . args
return ( ( m * u + w ) * 12 + k ) * m1 + z |
def newLayer ( self , name , color = None ) :
"""Make a new layer with * * name * * and * * color * * .
* * name * * must be a : ref : ` type - string ` and
* * color * * must be a : ref : ` type - color ` or ` ` None ` ` .
> > > layer = font . newLayer ( " My Layer 3 " )
The will return the newly created
... | name = normalizers . normalizeLayerName ( name )
if name in self . layerOrder :
layer = self . getLayer ( name )
if color is not None :
layer . color = color
return layer
if color is not None :
color = normalizers . normalizeColor ( color )
layer = self . _newLayer ( name = name , color = color ... |
def get_occurrence ( event_id , occurrence_id = None , year = None , month = None , day = None , hour = None , minute = None , second = None , tzinfo = None ) :
"""Because occurrences don ' t have to be persisted , there must be two ways to
retrieve them . both need an event , but if its persisted the occurrence ... | if ( occurrence_id ) :
occurrence = get_object_or_404 ( Occurrence , id = occurrence_id )
event = occurrence . event
elif None not in ( year , month , day , hour , minute , second ) :
event = get_object_or_404 ( Event , id = event_id )
date = timezone . make_aware ( datetime . datetime ( int ( year ) , ... |
def maximum_address ( self ) :
"""The maximum address of the data , or ` ` None ` ` if the file is empty .""" | maximum_address = self . _segments . maximum_address
if maximum_address is not None :
maximum_address //= self . word_size_bytes
return maximum_address |
def initLogging ( verbosity = 0 , name = "SCOOP" ) :
"""Creates a logger .""" | global loggingConfig
verbose_levels = { - 2 : "CRITICAL" , - 1 : "ERROR" , 0 : "WARNING" , 1 : "INFO" , 2 : "DEBUG" , 3 : "DEBUG" , 4 : "NOSET" , }
log_handlers = { "console" : { "class" : "logging.StreamHandler" , "formatter" : "{name}Formatter" . format ( name = name ) , "stream" : "ext://sys.stderr" , } , }
loggingC... |
def get_revision ( self , id , rev , ** kwargs ) :
"""Get specific audited revision of this build configuration
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please define a ` callback ` function
to be invoked when receiving the response .
> > > def callbac... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . get_revision_with_http_info ( id , rev , ** kwargs )
else :
( data ) = self . get_revision_with_http_info ( id , rev , ** kwargs )
return data |
def match ( self , objects : List [ Any ] ) -> bool :
"""Return True if the list of objects matches the expression .""" | s = self . _make_string ( objects )
m = self . _compiled_expression . match ( s )
return m is not None |
def run_ding0 ( self , session , mv_grid_districts_no = None , debug = False , export_figures = False ) :
"""Let DING0 run by shouting at this method ( or just call
it from NetworkDing0 instance ) . This method is a wrapper
for the main functionality of DING0.
Parameters
session : sqlalchemy . orm . session... | if debug :
start = time . time ( )
# STEP 1 : Import MV Grid Districts and subjacent objects
self . import_mv_grid_districts ( session , mv_grid_districts_no = mv_grid_districts_no )
# STEP 2 : Import generators
self . import_generators ( session , debug = debug )
# STEP 3 : Parametrize MV grid
self . mv_parametriz... |
def _generate_sequences ( self , primary_label , secondary_label , ngrams ) :
"""Generates aligned sequences between each witness labelled
` primary _ label ` and each witness labelled ` secondary _ label ` ,
based around ` ngrams ` .
: param primary _ label : label for one side of the pairs of
witnesses to... | cols = [ constants . WORK_FIELDNAME , constants . SIGLUM_FIELDNAME ]
primary_works = self . _matches [ self . _matches [ constants . LABEL_FIELDNAME ] == primary_label ] [ cols ] . drop_duplicates ( )
secondary_works = self . _matches [ self . _matches [ constants . LABEL_FIELDNAME ] == secondary_label ] [ cols ] . dro... |
def GetMemSharedMB ( self ) :
'''Retrieves the amount of physical memory associated with this virtual
machine that is copy - on - write ( COW ) shared on the host .''' | counter = c_uint ( )
ret = vmGuestLib . VMGuestLib_GetMemSharedMB ( self . handle . value , byref ( counter ) )
if ret != VMGUESTLIB_ERROR_SUCCESS :
raise VMGuestLibException ( ret )
return counter . value |
def sls_build ( repository , tag = 'latest' , base = 'opensuse/python' , mods = None , dryrun = False , ** kwargs ) :
'''. . versionchanged : : 2018.3.0
The repository and tag must now be passed separately using the
` ` repository ` ` and ` ` tag ` ` arguments , rather than together in the ( now
deprecated ) ... | create_kwargs = __utils__ [ 'args.clean_kwargs' ] ( ** copy . deepcopy ( kwargs ) )
for key in ( 'image' , 'name' , 'cmd' , 'interactive' , 'tty' , 'extra_filerefs' ) :
try :
del create_kwargs [ key ]
except KeyError :
pass
# start a new container
ret = create ( image = base , cmd = 'sleep infin... |
def print_solution ( model , solver ) :
"""Prints the solution associated with solver .
If solver has already had Solve ( ) called on it , prints the solution . This
includes each variable and its assignment , along with the objective function
and its optimal value .
If solver has not had Solve ( ) called o... | model_proto = model . Proto ( )
response_proto = solver . ResponseProto ( )
variables_in_objective_map = { }
maximization = False
if model_proto . HasField ( 'objective' ) :
objective = model_proto . objective
for i in range ( len ( objective . vars ) ) :
variables_in_objective_map [ objective . vars [ ... |
def numpy_bins_with_mask ( self ) -> Tuple [ np . ndarray , np . ndarray ] :
"""Bins in the numpy format , including the gaps in inconsecutive binnings .
Returns
edges , mask : np . ndarray
See Also
bin _ utils . to _ numpy _ bins _ with _ mask""" | bwm = to_numpy_bins_with_mask ( self . bins )
if not self . includes_right_edge :
bwm [ 0 ] . append ( np . inf )
return bwm |
def _run ( self , stdout = subprocess . PIPE ) :
'''Internal . Starts running this command and those before it . Can only
be called once .
: param stdout : Where to send stdout for this link in the chain .''' | assert self . _pop is None
if self . _input is not None :
self . _input . _run ( )
cwd = ( self . _cwd if self . _cwd else os . getcwd ( ) ) + '/'
def glob_or ( expr ) :
res = [ expr ]
if self . _expand and ( '*' in expr or '?' in expr ) :
if expr and expr [ 0 ] != '/' :
expr = cwd + exp... |
def run ( self ) :
"""this is the actual execution of the ReadProbes thread : continuously read values from the probes""" | if self . probes is None :
self . _stop = True
while True :
if self . _stop :
break
self . probes_values = { instrument_name : { probe_name : probe_instance . value for probe_name , probe_instance in probe . items ( ) } for instrument_name , probe in self . probes . items ( ) }
self . updateProg... |
def XYZ_to_lbd ( X , Y , Z , degree = False ) :
"""NAME :
XYZ _ to _ lbd
PURPOSE :
transform from rectangular Galactic coordinates to spherical Galactic coordinates ( works with vector inputs )
INPUT :
X - component towards the Galactic Center ( in kpc ; though this obviously does not matter ) )
Y - com... | # Whether to use degrees and scalar input is handled by decorators
d = nu . sqrt ( X ** 2. + Y ** 2. + Z ** 2. )
b = nu . arcsin ( Z / d )
cosl = X / d / nu . cos ( b )
sinl = Y / d / nu . cos ( b )
l = nu . arcsin ( sinl )
l [ cosl < 0. ] = nu . pi - l [ cosl < 0. ]
l [ ( cosl >= 0. ) * ( sinl < 0. ) ] += 2. * nu . pi... |
def index_impl ( self ) :
"""Return { runName : { tagName : { displayName : . . . , description : . . . } } } .""" | if self . _db_connection_provider : # Read tags from the database .
db = self . _db_connection_provider ( )
cursor = db . execute ( '''
SELECT
Tags.tag_name,
Tags.display_name,
Runs.run_name
FROM Tags
JOIN Runs
ON Tags.run_id = Runs.run_id
... |
def _attr_to_property ( self , attr ) :
"""Common routine to translate a python attribute name to a property name and
return the appropriate property .""" | # get the property
prop = self . _properties . get ( attr )
if not prop :
raise PropertyError ( attr )
# found it
return prop |
def to_dict ( self ) :
"""Get a dictionary serialization of the object to convert into a Json
object .
Returns
dict""" | doc = { 'filename' : self . filename , 'mimeType' : self . mime_type }
# Add path if present
if self . filename != self . path :
doc [ 'path' ] = self . path
return doc |
def getserialized ( self , key , decoder_func = None , ** kwargs ) :
"""Gets the setting value as a : obj : ` dict ` or : obj : ` list ` trying : meth : ` json . loads ` , followed by : meth : ` yaml . load ` .
: rtype : dict , list""" | value = self . get ( key , cast_func = None , ** kwargs )
if isinstance ( value , ( dict , list , tuple ) ) or value is None :
return value
if decoder_func :
return decoder_func ( value )
try :
o = json . loads ( value )
return o
except json . decoder . JSONDecodeError :
pass
try :
o = yaml . lo... |
def simple_slice ( value ) :
"""> > > simple _ slice ( ' 2:5 ' )
(2 , 5)
> > > simple _ slice ( ' 0 : None ' )
(0 , None )""" | try :
start , stop = value . split ( ':' )
start = ast . literal_eval ( start )
stop = ast . literal_eval ( stop )
if start is not None and stop is not None :
assert start < stop
except Exception :
raise ValueError ( 'invalid slice: %s' % value )
return ( start , stop ) |
def autocomplete ( request , app_label = None , model = None ) :
"""returns ` ` \\ n ` ` delimited strings in the form < tag > | | ( # )
GET params are ` ` q ` ` , ` ` limit ` ` , ` ` counts ` ` , ` ` q ` ` is what the user
has typed , ` ` limit ` ` defaults to 10 , and ` ` counts ` ` can be " model " , " all "... | # get the relevent model if applicable
if app_label and model :
try :
model = ContentType . objects . get ( app_label = app_label , model = model )
except :
raise Http404
else :
model = None
if not request . GET . has_key ( "q" ) :
raise Http404
else :
q = request . GET [ "q" ]
# cou... |
def WorkersDensity ( dataTasks ) :
"""Return the worker density data for the graph .""" | start_time , end_time = getTimes ( dataTasks )
graphdata = [ ]
for name in getWorkersName ( dataTasks ) :
vals = dataTasks [ name ]
if hasattr ( vals , 'values' ) : # Data from worker
workerdata = [ ]
print ( "Plotting density map for {}" . format ( name ) )
# We only have 800 pixels
... |
def _set_vni_add ( self , v , load = False ) :
"""Setter method for vni _ add , mapped from YANG variable / rbridge _ id / evpn _ instance / vni / vni _ add ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ vni _ add is considered as a private
method . Bac... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = vni_add . vni_add , is_container = 'container' , presence = False , yang_name = "vni-add" , rest_name = "" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extens... |
def setup_signal_handlers ( self ) :
"""Called when a child process is spawned to register the signal
handlers""" | LOGGER . debug ( 'Registering signal handlers' )
signal . signal ( signal . SIGABRT , self . on_sigabrt ) |
def inserir ( self , id_script_type , script , model , description ) :
"""Inserts a new Script and returns its identifier .
: param id _ script _ type : Identifier of the Script Type . Integer value and greater than zero .
: param script : Script name . String with a minimum 3 and maximum of 40 characters
: p... | script_map = dict ( )
script_map [ 'id_script_type' ] = id_script_type
script_map [ 'script' ] = script
script_map [ 'model' ] = model
script_map [ 'description' ] = description
code , xml = self . submit ( { 'script' : script_map } , 'POST' , 'script/' )
return self . response ( code , xml ) |
def does_external_program_run ( prog , verbose ) :
"""Test to see if the external programs can be run .""" | try :
with open ( '/dev/null' ) as null :
subprocess . call ( [ prog , '-h' ] , stdout = null , stderr = null )
result = True
except OSError :
if verbose > 1 :
print ( "couldn't run {}" . format ( prog ) )
result = False
return result |
def push ( self , remote , branch = None ) :
'''Push a repository
: param remote : git - remote instance
: param branch : name of the branch to push
: return : PushInfo , git push output lines''' | pb = ProgressBar ( )
pb . setup ( self . name , ProgressBar . Action . PUSH )
if branch :
result = remote . push ( branch , progress = pb )
else : # pragma : no cover
result = remote . push ( progress = pb )
print ( )
return result , pb . other_lines |
async def update_state ( self , short_name , state ) :
"""Set the current state of a service .
If the state is unchanged from a previous attempt , this routine does
nothing .
Args :
short _ name ( string ) : The short name of the service
state ( int ) : The new stae of the service""" | if short_name not in self . services :
raise ArgumentError ( "Service name is unknown" , short_name = short_name )
if state not in states . KNOWN_STATES :
raise ArgumentError ( "Invalid service state" , state = state )
serv = self . services [ short_name ] [ 'state' ]
if serv . state == state :
return
updat... |
def extract_number ( text ) :
"""Extract digit character from text .""" | result = list ( )
chunk = list ( )
valid_char = set ( ".1234567890" )
for char in text :
if char in valid_char :
chunk . append ( char )
else :
result . append ( "" . join ( chunk ) )
chunk = list ( )
result . append ( "" . join ( chunk ) )
result_new = list ( )
for number in result :
... |
def _set_ssh ( self , v , load = False ) :
"""Setter method for ssh , mapped from YANG variable / rbridge _ id / ssh ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ ssh is considered as a private
method . Backends looking to populate this variable should... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = ssh . ssh , is_container = 'container' , presence = False , yang_name = "ssh" , rest_name = "ssh" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions = { ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.