signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def iter_languages ( self , number = - 1 , etag = None ) :
"""Iterate over the programming languages used in the repository .
: param int number : ( optional ) , number of languages to return . Default :
-1 returns all used languages
: param str etag : ( optional ) , ETag from a previous request to the same
... | url = self . _build_url ( 'languages' , base_url = self . _api )
return self . _iter ( int ( number ) , url , tuple , etag = etag ) |
def all_collections ( db ) :
"""Yield all non - sytem collections in db .""" | include_pattern = r'(?!system\.)'
return ( db [ name ] for name in db . list_collection_names ( ) if re . match ( include_pattern , name ) ) |
def confirm_redirect_uri ( self , client_id , code , redirect_uri , client , request , * args , ** kwargs ) :
"""Ensure that the authorization process represented by this authorization
code began with this ' redirect _ uri ' .
If the client specifies a redirect _ uri when obtaining code then that
redirect URI... | raise NotImplementedError ( 'Subclasses must implement this method.' ) |
def Drop ( self : dict , n ) :
"""' self ' : [ 1 , 2 , 3 , 4 , 5 ] ,
' n ' : 3,
' assert ' : lambda ret : list ( ret ) = = [ 1 , 2]""" | n = len ( self ) - n
if n <= 0 :
yield from self . items ( )
else :
for i , e in enumerate ( self . items ( ) ) :
if i == n :
break
yield e |
def subdict ( super_dict , keys ) :
"""Returns a subset of the super _ dict with the specified keys .""" | sub_dict = { }
valid_keys = super_dict . keys ( )
for key in keys :
if key in valid_keys :
sub_dict [ key ] = super_dict [ key ]
return sub_dict |
def _stringtie_expression ( bam , data , out_dir = "." ) :
"""only estimate expression the Stringtie , do not assemble new transcripts""" | gtf_file = dd . get_gtf_file ( data )
num_cores = dd . get_num_cores ( data )
error_message = "The %s file for %s is missing. StringTie has an error."
stringtie = config_utils . get_program ( "stringtie" , data , default = "stringtie" )
# don ' t assemble transcripts unless asked
exp_flag = ( "-e" if "stringtie" not in... |
def add_ticks_to_x ( ax , newticks , newnames ) :
"""Add new ticks to an axis .
I use this for the right - hand plotting of resonance names in my plots .""" | ticks = list ( ax . get_xticks ( ) )
ticks . extend ( newticks )
ax . set_xticks ( ticks )
names = list ( ax . get_xticklabels ( ) )
names . extend ( newnames )
ax . set_xticklabels ( names ) |
def coupleTo_vswitch ( userid , vswitch_name ) :
"""Couple to vswitch .
Input parameters :
: userid : USERID of the guest , last 8 if length > 8
: network _ info : dict of network info""" | print ( "\nCoupleing to vswitch for %s ..." % userid )
vswitch_info = client . send_request ( 'guest_nic_couple_to_vswitch' , userid , '1000' , vswitch_name )
if vswitch_info [ 'overallRC' ] :
raise RuntimeError ( "Failed to couple to vswitch for guest %s!\n%s" % ( userid , vswitch_info ) )
else :
print ( "Succ... |
def _abbrieviate_direction ( ext_dir_str ) :
"""Convert extended ( non - abbrievated ) directions to abbrieviation .""" | return ( ext_dir_str . upper ( ) . replace ( '_' , '' ) . replace ( '-' , '' ) . replace ( ' ' , '' ) . replace ( 'NORTH' , 'N' ) . replace ( 'EAST' , 'E' ) . replace ( 'SOUTH' , 'S' ) . replace ( 'WEST' , 'W' ) ) |
def add_styles ( self , ** styles ) :
"""Add ODF styles to the current document .""" | for stylename in sorted ( styles ) :
self . _doc . styles . addElement ( styles [ stylename ] ) |
def unix_time ( self , dt ) :
"""Returns the number of seconds since the UNIX epoch for the given
datetime ( dt ) .
PARAMETERS :
dt - - datetime""" | epoch = datetime . utcfromtimestamp ( 0 )
delta = dt - epoch
return int ( delta . total_seconds ( ) ) |
def Target_setAttachToFrames ( self , value ) :
"""Function path : Target . setAttachToFrames
Domain : Target
Method name : setAttachToFrames
Parameters :
Required arguments :
' value ' ( type : boolean ) - > Whether to attach to frames .
No return value .""" | assert isinstance ( value , ( bool , ) ) , "Argument 'value' must be of type '['bool']'. Received type: '%s'" % type ( value )
subdom_funcs = self . synchronous_command ( 'Target.setAttachToFrames' , value = value )
return subdom_funcs |
def labelset_heads ( self , label ) :
"""Return the heads of the labelset selected by * label * .
Args :
label : the label from which to find head nodes / EPs .
Returns :
An iterable of nodeids .""" | _eps = self . _eps
_vars = self . _vars
_hcons = self . _hcons
nodeids = { nodeid : _eps [ nodeid ] [ 3 ] . get ( IVARG_ROLE , None ) for nodeid in _vars [ label ] [ 'refs' ] [ 'LBL' ] }
if len ( nodeids ) <= 1 :
return list ( nodeids )
scope_sets = { }
for nid in nodeids :
scope_sets [ nid ] = _ivs_in_scope ( ... |
def _load_formatters ( module_name ) :
"""Load a formatter ( and all others in the module too ) .""" | mod = __import__ ( module_name , None , None , [ '__all__' ] )
for formatter_name in mod . __all__ :
cls = getattr ( mod , formatter_name )
_formatter_cache [ cls . name ] = cls |
async def checks ( self , service , * , dc = None , near = None , watch = None , consistency = None ) :
"""Returns the checks of a service
Parameters :
dc ( str ) : Specify datacenter that will be used .
Defaults to the agent ' s local datacenter .
near ( str ) : With a node name will sort the node list in ... | service_id = extract_attr ( service , keys = [ "ServiceID" , "ID" ] )
params = { "dc" : dc , "near" : near }
response = await self . _api . get ( "/v1/health/checks" , service_id , params = params , watch = watch , consistency = consistency )
return consul ( response ) |
def find ( * args , ** kwargs ) :
"""kwargs supported :
user : the username
start _ at : start datetime object
end _ at : end datetime object
limit : # of objects to fetch""" | # default end _ at to now and start to 1 day from now
end_at = kwargs . get ( 'end_at' , datetime . datetime . now ( ) )
start_at = kwargs . get ( 'start_at' , end_at - datetime . timedelta ( days = 1 ) )
# default # of records to fetch to be 50
limit = kwargs . get ( 'limit' , 50 )
# if no user is defined , fetch for ... |
def encode_offset_fetch_request ( cls , group , payloads , from_kafka = False ) :
"""Encode an OffsetFetchRequest struct . The request is encoded using
version 0 if from _ kafka is false , indicating a request for Zookeeper
offsets . It is encoded using version 1 otherwise , indicating a request
for Kafka off... | version = 1 if from_kafka else 0
return kafka . protocol . commit . OffsetFetchRequest [ version ] ( consumer_group = group , topics = [ ( topic , list ( topic_payloads . keys ( ) ) ) for topic , topic_payloads in six . iteritems ( group_by_topic_and_partition ( payloads ) ) ] ) |
def _get_vm_by_id ( vmid , allDetails = False ) :
'''Retrieve a VM based on the ID .''' | for vm_name , vm_details in six . iteritems ( get_resources_vms ( includeConfig = allDetails ) ) :
if six . text_type ( vm_details [ 'vmid' ] ) == six . text_type ( vmid ) :
return vm_details
log . info ( 'VM with ID "%s" could not be found.' , vmid )
return False |
def is_right_model ( instance , attribute , value ) :
"""Must include at least the ` ` source ` ` and ` ` license ` ` keys , but
not a ` ` rightsOf ` ` key ( ` ` source ` ` indicates that the Right is
derived from and allowed by a source Right ; it cannot contain the
full rights to a Creation ) .""" | for key in [ 'source' , 'license' ] :
key_value = value . get ( key )
if not isinstance ( key_value , str ) :
instance_name = instance . __class__ . __name__
raise ModelDataError ( ( "'{key}' must be given as a string in " "the '{attr}' parameter of a '{cls}'. Given " "'{value}'" ) . format ( ke... |
def parse_irreg ( self , l ) :
"""Constructeur de la classe Irreg .
: param l : Ligne de chargement des irréguliers
: type l : str""" | ecl = l . split ( ':' )
grq = ecl [ 0 ]
exclusif = False
if grq . endswith ( "*" ) :
grq = grq [ : - 1 ]
exclusif = True
return Irreg ( graphie_accentuee = grq , graphie = atone ( grq ) , exclusif = exclusif , morphos = listeI ( ecl [ 2 ] ) , lemme = self . lemmatiseur . lemme ( ecl [ 1 ] ) , parent = self . le... |
def PCA ( Y , components ) :
"""run PCA , retrieving the first ( components ) principle components
return [ s0 , eig , w0]
s0 : factors
w0 : weights""" | N , D = Y . shape
sv = linalg . svd ( Y , full_matrices = 0 ) ;
[ s0 , w0 ] = [ sv [ 0 ] [ : , 0 : components ] , np . dot ( np . diag ( sv [ 1 ] ) , sv [ 2 ] ) . T [ : , 0 : components ] ]
v = s0 . std ( axis = 0 )
s0 /= v ;
w0 *= v ;
return [ s0 , w0 ]
if N > D :
sv = linalg . svd ( Y , full_matrices = 0 ) ;
... |
def get_os_file_names ( files ) :
"""returns file names
: param files : list of strings and \\ or : class : ` file _ configuration _ t `
instances .
: type files : list""" | fnames = [ ]
for f in files :
if utils . is_str ( f ) :
fnames . append ( f )
elif isinstance ( f , file_configuration_t ) :
if f . content_type in ( file_configuration_t . CONTENT_TYPE . STANDARD_SOURCE_FILE , file_configuration_t . CONTENT_TYPE . CACHED_SOURCE_FILE ) :
fnames . app... |
def valid_fits_key ( key ) :
"""Makes valid key for a FITS header
" The keyword names may be up to 8 characters long and can only contain
uppercase letters A to Z , the digits 0 to 9 , the hyphen , and the underscore
character . " ( http : / / fits . gsfc . nasa . gov / fits _ primer . html )""" | ret = re . sub ( "[^A-Z0-9\-_]" , "" , key . upper ( ) ) [ : 8 ]
if len ( ret ) == 0 :
raise RuntimeError ( "key '{0!s}' has no valid characters to be a key in a FITS header" . format ( key ) )
return ret |
def wait_script ( name , source = None , template = None , onlyif = None , unless = None , cwd = None , runas = None , shell = None , env = None , stateful = False , umask = None , use_vt = False , output_loglevel = 'debug' , hide_output = False , success_retcodes = None , success_stdout = None , success_stderr = None ... | # Ignoring our arguments is intentional .
return { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' } |
def listen_on_udp_port ( ) :
"""listen _ on _ udp _ port
Run a simple server for processing messages over ` ` UDP ` ` .
` ` UDP _ LISTEN _ ON _ HOST ` ` - listen on this host ip address
` ` UDP _ LISTEN _ ON _ PORT ` ` - listen on this ` ` UDP ` ` port
` ` UDP _ LISTEN _ SIZE ` ` - listen on to packets of t... | host = os . getenv ( "UDP_LISTEN_ON_HOST" , "127.0.0.1" ) . strip ( ) . lstrip ( )
port = int ( os . getenv ( "UDP_LISTEN_ON_PORT" , "17000" ) . strip ( ) . lstrip ( ) )
backlog = int ( os . getenv ( "UDP_LISTEN_BACKLOG" , "5" ) . strip ( ) . lstrip ( ) )
size = int ( os . getenv ( "UDP_LISTEN_SIZE" , "1024" ) . strip ... |
def _set_auditlog ( self , v , load = False ) :
"""Setter method for auditlog , mapped from YANG variable / logging / auditlog ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ auditlog is considered as a private
method . Backends looking to populate this ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = auditlog . auditlog , is_container = 'container' , presence = False , yang_name = "auditlog" , rest_name = "auditlog" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = Tr... |
def write ( self , output ) :
"""Writes specified text to the underlying stream
Parameters
output bytes - like object
Bytes to write""" | self . _stream . write ( output )
if self . _auto_flush :
self . _stream . flush ( ) |
def _isna_compat ( arr , fill_value = np . nan ) :
"""Parameters
arr : a numpy array
fill _ value : fill value , default to np . nan
Returns
True if we can fill using this fill _ value""" | dtype = arr . dtype
if isna ( fill_value ) :
return not ( is_bool_dtype ( dtype ) or is_integer_dtype ( dtype ) )
return True |
def addOntology ( self ) :
"""Adds a new Ontology to this repo .""" | self . _openRepo ( )
name = self . _args . name
filePath = self . _getFilePath ( self . _args . filePath , self . _args . relativePath )
if name is None :
name = getNameFromPath ( filePath )
ontology = ontologies . Ontology ( name )
ontology . populateFromFile ( filePath )
self . _updateRepo ( self . _repo . insert... |
def register_click_watcher ( self , watcher_name , selectors , * condition_list ) :
"""The watcher click on the object which has the * selectors * when conditions match .""" | watcher = self . device . watcher ( watcher_name )
for condition in condition_list :
watcher . when ( ** self . __unicode_to_dict ( condition ) )
watcher . click ( ** self . __unicode_to_dict ( selectors ) )
self . device . watchers . run ( ) |
def getClass ( self , tryImport = True ) :
"""Gets the underlying class . Tries to import if tryImport is True ( the default ) .
Returns None if the import has failed ( the exception property will contain the reason )""" | if not self . triedImport and tryImport :
self . tryImportClass ( )
return self . _cls |
def linear ( arr1 , arr2 ) :
"""Create a linear blend of arr1 ( fading out ) and arr2 ( fading in )""" | n = N . shape ( arr1 ) [ 0 ]
try :
channels = N . shape ( arr1 ) [ 1 ]
except :
channels = 1
f_in = N . linspace ( 0 , 1 , num = n )
f_out = N . linspace ( 1 , 0 , num = n )
# f _ in = N . arange ( n ) / float ( n - 1)
# f _ out = N . arange ( n - 1 , - 1 , - 1 ) / float ( n )
if channels > 1 :
f_in = N . t... |
def generate ( self , M , age = 9.6 , feh = 0.0 , ichrone = 'mist' , n = 1e4 , bands = None , ** kwargs ) :
"""Function that generates population .
Called by ` ` _ _ init _ _ ` ` if ` ` M ` ` is passed .""" | ichrone = get_ichrone ( ichrone , bands = bands )
if np . size ( M ) > 1 :
n = np . size ( M )
else :
n = int ( n )
M2 = M * self . q_fn ( n , qmin = np . maximum ( self . qmin , self . minmass / M ) )
P = self . P_fn ( n )
ecc = self . ecc_fn ( n , P )
mass = np . ascontiguousarray ( np . ones ( n ) * M )
mass... |
def create ( self , path , metadata , filter_ = filter_hidden , object_class = None ) :
"""Create objects in CDSTAR and register them in the catalog .
Note that we guess the mimetype based on the filename extension , using
` mimetypes . guess _ type ` . Thus , it is the caller ' s responsibility to add custom o... | path = Path ( path )
if path . is_file ( ) :
fnames = [ path ]
elif path . is_dir ( ) :
fnames = list ( walk ( path , mode = 'files' ) )
else :
raise ValueError ( 'path must be a file or directory' )
# pragma : no cover
for fname in fnames :
if not filter_ or filter_ ( fname ) :
created , ob... |
def compile_column ( name : str , data_type : str , nullable : bool ) -> str :
"""Create column definition statement .""" | null_str = 'NULL' if nullable else 'NOT NULL'
return '{name} {data_type} {null},' . format ( name = name , data_type = data_type , null = null_str ) |
def named_tuple_factory ( colnames , rows ) :
"""Returns each row as a ` namedtuple < https : / / docs . python . org / 2 / library / collections . html # collections . namedtuple > ` _ .
This is the default row factory .
Example : :
> > > from cassandra . query import named _ tuple _ factory
> > > session ... | clean_column_names = map ( _clean_column_name , colnames )
try :
Row = namedtuple ( 'Row' , clean_column_names )
except SyntaxError :
warnings . warn ( "Failed creating namedtuple for a result because there were too " "many columns. This is due to a Python limitation that affects " "namedtuple in Python 3.0-3.6... |
def p_declarray ( self , p ) :
'declname : ID length' | p [ 0 ] = ( p [ 1 ] , p [ 2 ] )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def get_objectives_by_ids ( self , objective_ids ) :
"""Gets an ` ` ObjectiveList ` ` corresponding to the given ` ` IdList ` ` .
In plenary mode , the returned list contains all of the
objectives specified in the ` ` Id ` ` list , in the order of the
list , including duplicates , or an error results if an ` ... | # Implemented from template for
# osid . resource . ResourceLookupSession . get _ resources _ by _ ids
# NOTE : This implementation currently ignores plenary view
collection = JSONClientValidated ( 'learning' , collection = 'Objective' , runtime = self . _runtime )
object_id_list = [ ]
for i in objective_ids :
obje... |
def write_force_constants_to_hdf5 ( force_constants , filename = 'force_constants.hdf5' , p2s_map = None , physical_unit = None , compression = None ) :
"""Write force constants in hdf5 format .
Parameters
force _ constants : ndarray
Force constants
shape = ( n _ satom , n _ satom , 3,3 ) or ( n _ patom , n... | try :
import h5py
except ImportError :
raise ModuleNotFoundError ( "You need to install python-h5py." )
with h5py . File ( filename , 'w' ) as w :
w . create_dataset ( 'force_constants' , data = force_constants , compression = compression )
if p2s_map is not None :
w . create_dataset ( 'p2s_map'... |
def load_template ( self , template_name , template_source = None , template_path = None , ** template_vars ) :
"""Will load a templated configuration on the device .
: param cls : Instance of the driver class .
: param template _ name : Identifies the template name .
: param template _ source ( optional ) : ... | return napalm . base . helpers . load_template ( self , template_name , template_source = template_source , template_path = template_path , ** template_vars ) |
def set_camera ( self , camera_id ) :
"""Set the camera view to the specified camera ID .""" | self . viewer . cam . fixedcamid = camera_id
self . viewer . cam . type = const . CAMERA_FIXED |
def change_mpl_backend ( self , command ) :
"""If the user is trying to change Matplotlib backends with
% matplotlib , send the same command again to the kernel to
correctly change it .
Fixes issue 4002""" | if command . startswith ( '%matplotlib' ) and len ( command . splitlines ( ) ) == 1 :
if not 'inline' in command :
self . silent_execute ( command ) |
def lambda_handler ( event , context ) :
"""Main handler .""" | users = boto3 . resource ( "dynamodb" ) . Table ( os . environ [ 'people' ] )
auth = check_auth ( event , role = [ "admin" ] )
if not auth [ 'success' ] :
return auth
user_email = event . get ( 'user_email' , None )
if not user_email :
msg = "Missing user_email parameter in your request."
return { 'success'... |
def load_depth ( self , idx ) :
"""Load pre - processed depth for NYUDv2 segmentation set .""" | im = Image . open ( '{}/data/depth/img_{}.png' . format ( self . nyud_dir , idx ) )
d = np . array ( im , dtype = np . float32 )
d = np . log ( d )
d -= self . mean_logd
d = d [ np . newaxis , ... ]
return d |
def prod_sum_var ( A , B ) :
"""dot product and sum over axis 1 ( var ) equivalent to np . sum ( A * B , 1)""" | return A . multiply ( B ) . sum ( 1 ) . A1 if issparse ( A ) else np . einsum ( 'ij, ij -> i' , A , B ) |
def export ( self , top = True ) :
"""Exports object to its string representation .
Args :
top ( bool ) : if True appends ` internal _ name ` before values .
All non list objects should be exported with value top = True ,
all list objects , that are embedded in as fields inlist objects
should be exported ... | out = [ ]
if top :
out . append ( self . _internal_name )
out . append ( self . _to_str ( self . holiday_name ) )
out . append ( self . _to_str ( self . holiday_day ) )
return "," . join ( out ) |
def _handle_oss_error ( ) :
"""Handle OSS exception and convert to class IO exceptions
Raises :
OSError subclasses : IO error .""" | try :
yield
except _OssError as exception :
if exception . status in _ERROR_CODES :
raise _ERROR_CODES [ exception . status ] ( exception . details . get ( 'Message' , '' ) )
raise |
def iter_grants ( self , as_json = True ) :
"""Fetch grants from a remote OAI - PMH endpoint .
Return the Sickle - provided generator object .""" | records = self . client . ListRecords ( metadataPrefix = 'oaf' , set = self . setspec )
for rec in records :
try :
grant_out = rec . raw
# rec . raw is XML
if as_json :
grant_out = self . grantxml2json ( grant_out )
yield grant_out
except FunderNotFoundError as e :
... |
def String ( length = None , ** kwargs ) :
"""A string valued property with max . ` length ` .""" | return Property ( length = length , types = stringy_types , convert = to_string , ** kwargs ) |
def get_topics ( self ) :
'''Returns the topics available on unbabel''' | result = self . api_call ( 'topic/' )
topics_json = json . loads ( result . content )
topics = [ Topic ( name = topic_json [ "topic" ] [ "name" ] ) for topic_json in topics_json [ "objects" ] ]
return topics |
def import_vol_mesh ( file_name ) :
"""Generates a NURBS volume object from a mesh file .
: param file _ name : input mesh file
: type file _ name : str
: return : a NURBS volume
: rtype : NURBS . Volume""" | raw_content = read_file ( file_name )
raw_content = raw_content . split ( "\n" )
content = [ ]
for rc in raw_content :
temp = rc . strip ( ) . split ( )
content . append ( temp )
# 1st line defines the dimension and it must be 3
if int ( content [ 0 ] [ 0 ] ) != 3 :
raise TypeError ( "Input mesh '" + str ( ... |
def receive_minimum_set ( self , amount ) :
"""Set * * amount * * as new receive minimum for node until restart
. . enable _ control required
. . version 8.0 required
: param amount : Amount in raw to set as minimum to receive
: type amount : int
: raises : : py : exc : ` nano . rpc . RPCException `
> >... | amount = self . _process_value ( amount , 'int' )
payload = { "amount" : amount }
resp = self . call ( 'receive_minimum_set' , payload )
return 'success' in resp |
def GenerateLabels ( self , hash_information ) :
"""Generates a list of strings that will be used in the event tag .
Args :
hash _ information ( dict [ str , object ] ) : JSON decoded contents of the result
of a Viper lookup , as produced by the ViperAnalyzer .
Returns :
list [ str ] : list of labels to a... | if not hash_information :
return [ 'viper_not_present' ]
projects = [ ]
tags = [ ]
for project , entries in iter ( hash_information . items ( ) ) :
if not entries :
continue
projects . append ( project )
for entry in entries :
if entry [ 'tags' ] :
tags . extend ( entry [ 'ta... |
def actionsFreqsAngles ( self , * args , ** kwargs ) :
"""NAME :
actionsFreqsAngles
PURPOSE :
evaluate the actions , frequencies , and angles ( jr , lz , jz , Omegar , Omegaphi , Omegaz , angler , anglephi , anglez )
INPUT :
Either :
a ) R , vR , vT , z , vz , phi :
1 ) floats : phase - space value fo... | try :
return self . _actionsFreqsAngles ( * args , ** kwargs )
except AttributeError : # pragma : no cover
raise NotImplementedError ( "'actionsFreqsAngles' method not implemented for this actionAngle module" ) |
def visible_object_layers ( self ) :
"""This must return layer objects
This is not required for custom data formats .
: return : Sequence of pytmx object layers / groups""" | return ( layer for layer in self . tmx . visible_layers if isinstance ( layer , pytmx . TiledObjectGroup ) ) |
def position_permutation ( obs_stat , context_counts , context_to_mut , seq_context , gene_seq , gene_vest = None , num_permutations = 10000 , stop_criteria = 100 , pseudo_count = 0 , max_batch = 25000 ) :
"""Performs null - permutations for position - based mutation statistics
in a single gene .
Parameters
o... | # get contexts and somatic base
mycontexts = context_counts . index . tolist ( )
somatic_base = [ base for one_context in mycontexts for base in context_to_mut [ one_context ] ]
# calculate the # of batches for simulations
max_batch = min ( num_permutations , max_batch )
num_batches = num_permutations // max_batch
rema... |
def request_check_all ( self , wait_time = 5 ) :
"""Wake all monitors , wait for at least one to check its server .""" | with self . _lock :
self . _request_check_all ( )
self . _condition . wait ( wait_time ) |
def read_long ( self , registeraddress , functioncode = 3 , signed = False ) :
"""Read a long integer ( 32 bits ) from the slave .
Long integers ( 32 bits = 4 bytes ) are stored in two consecutive 16 - bit registers in the slave .
Args :
* registeraddress ( int ) : The slave register start address ( use decim... | _checkFunctioncode ( functioncode , [ 3 , 4 ] )
_checkBool ( signed , description = 'signed' )
return self . _genericCommand ( functioncode , registeraddress , numberOfRegisters = 2 , signed = signed , payloadformat = 'long' ) |
def tree_adj_to_prec ( graph , root = 0 ) :
"""Transforms a tree given as adjacency list into predecessor table form .
if graph is not a tree : will return a DFS spanning tree
: param graph : directed graph in listlist or listdict format
: returns : tree in predecessor table representation
: complexity : li... | prec = [ None ] * len ( graph )
prec [ root ] = root
# mark to visit root only once
to_visit = [ root ]
while to_visit : # DFS
node = to_visit . pop ( )
for neighbor in graph [ node ] :
if prec [ neighbor ] is None :
prec [ neighbor ] = node
to_visit . append ( neighbor )
prec [ ... |
def get ( self , key , default = None ) :
"""Retrieve an item from the cache by key .
: param key : The cache key
: type key : str
: param default : The default value to return
: type default : mixed
: rtype : mixed""" | val = self . _store . get ( key )
if val is None :
return value ( default )
return val |
def assert_visible ( self , locator , msg = None ) :
"""Hard assert for whether and element is present and visible in the current window / frame
: params locator : the locator of the element to search for
: params msg : ( Optional ) msg explaining the difference""" | e = driver . find_elements_by_locator ( locator )
if len ( e ) == 0 :
raise AssertionError ( "Element at %s was not found" % locator )
assert e . is_displayed ( ) |
def create_widget ( self ) :
"""Create the underlying widget .""" | d = self . declaration
self . widget = Flexbox ( self . get_context ( ) , None , d . style ) |
def do_allowrep ( self , line ) :
"""allowrep Allow new objects to be replicated .""" | self . _split_args ( line , 0 , 0 )
self . _command_processor . get_session ( ) . get_replication_policy ( ) . set_replication_allowed ( True )
self . _print_info_if_verbose ( "Set replication policy to allow replication" ) |
def set_single_attribute ( self , other , trigger_klass , property_name ) :
"""Used to set guard the setting of an attribute which is singular and can ' t be set twice""" | if isinstance ( other , trigger_klass ) : # Check property exists
if not hasattr ( self , property_name ) :
raise AttributeError ( "%s has no property %s" % ( self . __class__ . __name__ , property_name ) )
if getattr ( self , property_name ) is None :
setattr ( self , property_name , other )
... |
def delete_datapoint ( self , datapoint ) :
"""Delete the provided datapoint from this stream
: raises devicecloud . DeviceCloudHttpException : in the case of an unexpected http error""" | datapoint = validate_type ( datapoint , DataPoint )
self . _conn . delete ( "/ws/DataPoint/{stream_id}/{datapoint_id}" . format ( stream_id = self . get_stream_id ( ) , datapoint_id = datapoint . get_id ( ) , ) ) |
def draw ( self ) :
'''Draws samples from the ` true ` distribution .
Returns :
` np . ndarray ` of samples .''' | sampled_arr = np . empty ( ( self . __batch_size , self . __seq_len , self . __dim ) )
for batch in range ( self . __batch_size ) :
key = np . random . randint ( low = 0 , high = len ( self . __midi_df_list ) )
midi_df = self . __midi_df_list [ key ]
program_arr = midi_df . program . drop_duplicates ( ) . v... |
def get_annotation ( self , key , result_format = 'list' ) :
"""Is a convenience method for accessing annotations on models that have them""" | value = self . get ( '_annotations_by_key' , { } ) . get ( key )
if not value :
return value
if result_format == 'one' :
return value [ 0 ]
return value |
def setUser ( self , * args , ** kwargs ) :
"""Adds the user for this loan to a ' user ' field .
User is a MambuUser object .
Returns the number of requests done to Mambu .""" | try :
user = self . mambuuserclass ( entid = self [ 'assignedUserKey' ] , * args , ** kwargs )
except KeyError as kerr :
err = MambuError ( "La cuenta %s no tiene asignado un usuario" % self [ 'id' ] )
err . noUser = True
raise err
except AttributeError as ae :
from . mambuuser import MambuUser
... |
def discover ( name , timeout = None , minimum_providers = 1 ) :
"""discovers a service . If timeout is specified , waits for at least minimum _ providers service instance to be available .
Note : we do not want to make the discovery block undefinitely since we never know for sure if a service is running or not
... | start = time . time ( )
endtime = timeout if timeout else 0
while True :
timed_out = time . time ( ) - start > endtime
if name in services and isinstance ( services [ name ] , list ) :
if len ( services [ name ] ) >= minimum_providers or timed_out :
providers = services [ name ]
... |
def iterate ( self , params , repetition , iteration ) :
"""Called once for each training iteration ( = = epoch here ) .""" | print ( "\nStarting iteration" , iteration )
print ( "Learning rate:" , self . learningRate if self . lr_scheduler is None else self . lr_scheduler . get_lr ( ) )
t1 = time . time ( )
ret = { }
# Update dataset epoch when using pre - processed speech dataset
if self . use_preprocessed_dataset :
t2 = time . time ( )... |
def get_unique_named_object_in_all_models ( root , name ) :
"""retrieves a unique named object ( no fully qualified name )
Args :
root : start of search ( if root is a model all known models are searched
as well )
name : name of object
Returns :
the object ( if not unique , raises an error )""" | if hasattr ( root , '_tx_model_repository' ) :
src = list ( root . _tx_model_repository . local_models . filename_to_model . values ( ) )
if root not in src :
src . append ( root )
else :
src = [ root ]
a = [ ]
for m in src :
print ( "analyzing {}" . format ( m . _tx_filename ) )
a = a + get... |
def blacklist ( ctx , blacklist_account , account ) :
"""Add an account to a blacklist""" | account = Account ( account , blockchain_instance = ctx . blockchain )
print_tx ( account . blacklist ( blacklist_account ) ) |
def _apply_section_hosts ( self , section , hosts ) :
"""Add the variables for each entry in a ' hosts ' section to the hosts
belonging to that entry .""" | for entry in section [ 'entries' ] :
for hostname in self . expand_hostdef ( entry [ 'name' ] ) :
if hostname not in hosts : # Expanded host or child host or something else refers to a
# host that isn ' t actually defined . Ansible skips this , so
# we will too .
continue
... |
def get_app_name ( app_name ) :
"""Returns a app name from new app config if is
a class or the same app name if is not a class .""" | type_ = locate ( app_name )
if inspect . isclass ( type_ ) :
return type_ . name
return app_name |
def set_features ( self , partition = 1 ) :
"""Parses market data JSON for technical analysis indicators
Args :
partition : Int of how many dates to take into consideration
when evaluating technical analysis indicators .
Returns :
Pandas DataFrame instance with columns as numpy . float32 features .""" | if len ( self . json ) < partition + 1 :
raise ValueError ( 'Not enough dates for the specified partition size: {0}. Try a smaller partition.' . format ( partition ) )
data = [ ]
for offset in range ( len ( self . json ) - partition ) :
json = self . json [ offset : offset + partition ]
data . append ( eva... |
def update_hash ( a_hash , mv ) :
"""Adds ` ` mv ` ` to ` ` a _ hash ` `
Args :
a _ hash ( ` Hash ` ) : the secure hash , e . g created by hashlib . md5
mv ( : class : ` MetricValue ` ) : the instance to add to the hash""" | if mv . labels :
signing . add_dict_to_hash ( a_hash , encoding . MessageToPyValue ( mv . labels ) )
money_value = mv . get_assigned_value ( u'moneyValue' )
if money_value is not None :
a_hash . update ( b'\x00' )
a_hash . update ( money_value . currencyCode . encode ( 'utf-8' ) ) |
def locales ( self , query = None ) :
"""Fetches all Locales from the Environment ( up to the set limit , can be modified in ` query ` ) .
# TODO : fix url
API Reference : https : / / www . contentful . com / developers / docs / references / content - delivery - api / # / reference / assets / assets - collectio... | if query is None :
query = { }
return self . _get ( self . environment_url ( '/locales' ) , query ) |
def comment_handle ( self , original , loc , tokens ) :
"""Store comment in comments .""" | internal_assert ( len ( tokens ) == 1 , "invalid comment tokens" , tokens )
ln = self . adjust ( lineno ( loc , original ) )
internal_assert ( lambda : ln not in self . comments , "multiple comments on line" , ln )
self . comments [ ln ] = tokens [ 0 ]
return "" |
def list ( self ) :
"""Lists the jobs on the server .""" | queue = self . _get_queue ( )
if queue is None :
raise QueueDoesntExist
output = self . check_output ( '%s' % shell_escape ( queue / 'commands/list' ) )
job_id , info = None , None
for line in output . splitlines ( ) :
line = line . decode ( 'utf-8' )
if line . startswith ( ' ' ) :
key , value = ... |
def create_residual_graph ( self ) :
'''API : create _ residual _ graph ( self )
Description :
Creates and returns residual graph , which is a Graph instance
itself .
Pre :
(1 ) Arcs should have ' flow ' , ' capacity ' and ' cost ' attribute
(2 ) Graph should be a directed graph
Return :
Returns res... | if self . graph_type is UNDIRECTED_GRAPH :
raise Exception ( 'residual graph is defined for directed graphs.' )
residual_g = Graph ( type = DIRECTED_GRAPH )
for e in self . get_edge_list ( ) :
capacity_e = self . get_edge_attr ( e [ 0 ] , e [ 1 ] , 'capacity' )
flow_e = self . get_edge_attr ( e [ 0 ] , e [ ... |
def collect ( self , file_paths ) :
"""Takes in a list of string file _ paths , and parses through them using
the converter , strategies , and switches defined at object
initialization .
It returns two dictionaries - the first maps from
file _ path strings to inner dictionaries , and those inner dictionarie... | for file_path in file_paths :
self . _anchors [ file_path ] , d = self . collect_single_file ( file_path )
if len ( d ) > 0 : # There were duplicates found in the file
self . _duplicate_tags [ file_path ] = d
self . _reset_switches ( )
return self . _anchors , self . _duplicate_tags |
def upload_status ( self , upload_id ) :
"""The method is checking status of uploaded dataset""" | path = '/api/1.0/upload/status'
query = 'id={}' . format ( upload_id )
return self . _api_get ( definition . DatasetUploadStatusResponse , path , query ) |
def apply_timefactor ( cls , values ) :
"""Change and return the given value ( s ) in accordance with
| Parameter . get _ timefactor | and the type of time - dependence
of the actual parameter subclass .
. . testsetup : :
> > > from hydpy import pub
> > > del pub . timegrids
For the same conversion fact... | if cls . TIME is True :
return values * cls . get_timefactor ( )
if cls . TIME is False :
return values / cls . get_timefactor ( )
return values |
def export_to_fta ( self , sample_rate , filename : str , include_amplitude = False ) :
"""Export to Frequency , Time , Amplitude file .
Frequency is double , Time ( nanosecond ) is uint32 , Amplitude is float32
: return :""" | spectrogram = self . __calculate_spectrogram ( self . samples )
spectrogram = np . flipud ( spectrogram . T )
if include_amplitude :
result = np . empty ( ( spectrogram . shape [ 0 ] , spectrogram . shape [ 1 ] , 3 ) , dtype = [ ( 'f' , np . float64 ) , ( 't' , np . uint32 ) , ( 'a' , np . float32 ) ] )
else :
... |
def process_image_field ( self , data ) :
"""Process perseus fields like questions and hints , which look like :
. . code - block : : python
" content " : " md string including imgs like ! [ ] ( URL - key ) and ! [ ] ( URL - key2 ) " ,
" images " : {
" URL - key " : { " width " : 425 , " height " : 425 } , ... | new_images_dict = copy . deepcopy ( data [ 'images' ] )
image_files = [ ]
# STEP 1 . Compile dict of { old _ url - - > new _ url } image URL replacements
image_replacements = { }
# STEP 1A . get all images specified in data [ ' images ' ]
for old_url , image_settings in data [ 'images' ] . items ( ) :
new_url , new... |
def prepare_partial ( self , X , initialization = "median" , k = 25 , ** affinity_params ) :
"""Prepare a partial embedding which can be optimized .
Parameters
X : np . ndarray
The data matrix to be added to the existing embedding .
initialization : Union [ np . ndarray , str ]
The initial point positions... | P , neighbors , distances = self . affinities . to_new ( X , return_distances = True , ** affinity_params )
# If initial positions are given in an array , use a copy of that
if isinstance ( initialization , np . ndarray ) :
init_checks . num_samples ( initialization . shape [ 0 ] , X . shape [ 0 ] )
init_checks... |
def get_FEC ( molecule_list , temperature , pressure , electronic_energy = 'Default' ) :
"""Returns the Gibbs free energy corrections to be added to raw reaction energies .
Parameters
molecule _ list : list of strings
temperature : numeric
temperature in K
pressure : numeric
pressure in mbar
Returns
... | if not temperature or not pressure :
return ( 0 )
else :
molecule_list = [ m for m in molecule_list if m != 'star' ]
# print ( molecule _ list )
FEC_sum = [ ]
for molecule in molecule_list :
if 'gas' in molecule :
mol = GasMolecule ( molecule . replace ( 'gas' , '' ) )
... |
def uncollapse ( self ) :
"""Uncollapse a private message or modmail .""" | url = self . reddit_session . config [ 'uncollapse_message' ]
self . reddit_session . request_json ( url , data = { 'id' : self . name } ) |
def handle_get_scanner_details ( self ) :
"""Handles < get _ scanner _ details > command .
@ return : Response string for < get _ scanner _ details > command .""" | desc_xml = Element ( 'description' )
desc_xml . text = self . get_scanner_description ( )
details = [ desc_xml , self . get_scanner_params_xml ( ) ]
return simple_response_str ( 'get_scanner_details' , 200 , 'OK' , details ) |
def _windows_resolve ( command ) :
"""Try and find the full path and file extension of the executable to run .
This is so that e . g . calls to ' somescript ' will point at ' somescript . cmd '
without the need to set shell = True in the subprocess .
If the executable contains periods it is a special case . H... | try :
import win32api
except ImportError :
if ( 2 , 8 ) < sys . version_info < ( 3 , 5 ) :
logger . info ( "Resolving executable names only supported on Python 2.7 and 3.5+" )
else :
logger . warning ( "Could not resolve executable name: package win32api missing" )
return command
if not ... |
def add_val ( self , subj : Node , pred : URIRef , json_obj : JsonObj , json_key : str , valuetype : Optional [ URIRef ] = None ) -> Optional [ BNode ] :
"""Add the RDF representation of val to the graph as a target of subj , pred . Note that FHIR lists are
represented as a list of BNODE objects with a fhir : ind... | if json_key not in json_obj :
print ( "Expecting to find object named '{}' in JSON:" . format ( json_key ) )
print ( json_obj . _as_json_dumps ( ) )
print ( "entry skipped" )
return None
val = json_obj [ json_key ]
if isinstance ( val , List ) :
list_idx = 0
for lv in val :
entry_bnode =... |
def forecast_names ( self ) :
"""get the forecast names from the pestpp options ( if any ) .
Returns None if no forecasts are named
Returns
forecast _ names : list
a list of forecast names .""" | if "forecasts" in self . pestpp_options . keys ( ) :
return self . pestpp_options [ "forecasts" ] . lower ( ) . split ( ',' )
elif "predictions" in self . pestpp_options . keys ( ) :
return self . pestpp_options [ "predictions" ] . lower ( ) . split ( ',' )
else :
return None |
def interfaces ( self ) :
"""Collect the available wlan interfaces .""" | self . _ifaces = [ ]
wifi_ctrl = wifiutil . WifiUtil ( )
for interface in wifi_ctrl . interfaces ( ) :
iface = Interface ( interface )
self . _ifaces . append ( iface )
self . _logger . info ( "Get interface: %s" , iface . name ( ) )
if not self . _ifaces :
self . _logger . error ( "Can't get wifi inter... |
def update_table_row ( self , table , row_idx ) :
"""Add this instance as a row on a ` astropy . table . Table `""" | try :
table [ row_idx ] [ 'timestamp' ] = self . timestamp
table [ row_idx ] [ 'status' ] = self . status
except IndexError :
print ( "Index error" , len ( table ) , row_idx ) |
def run ( self , refant = [ ] , antsel = [ ] , uvrange = '' , fluxname = '' , fluxname_full = '' , band = '' , spw0 = '' , spw1 = '' , flaglist = [ ] ) :
"""Run calibration pipeline . Assumes L - band .
refant is list of antenna name strings ( e . g . , [ ' ea10 ' ] ) . default is to calculate based on distance f... | os . chdir ( self . workdir )
if not len ( refant ) :
refant = self . find_refants ( )
antposname = self . fileroot + '.antpos'
# antpos
delayname = self . fileroot + '.delay'
# delay cal
g0name = self . fileroot + '.g0'
# initial gain correction before bp
b1name = self . fileroot + '.b1'
# bandpass file
g1name = s... |
def get_app ( self ) :
"""Get current app from Flast stack to use .
This will allow to ensure which Redis connection to be used when
accessing Redis connection public methods via plugin .""" | # First see to connection stack
ctx = connection_stack . top
if ctx is not None :
return ctx . app
# Next return app from instance cache
if self . app is not None :
return self . app
# Something went wrong , in most cases app just not instantiated yet
# and we cannot locate it
raise RuntimeError ( 'Flask applic... |
def _should_split_cell ( cls , cell_text : str ) -> bool :
"""Checks whether the cell should be split . We ' re just doing the same thing that SEMPRE did
here .""" | if ', ' in cell_text or '\n' in cell_text or '/' in cell_text :
return True
return False |
def add_entity_errors ( self , property_name , direct_errors = None , schema_errors = None ) :
"""Attach nested entity errors
Accepts a list errors coming from validators attached directly ,
or a dict of errors produced by a nested schema .
: param property _ name : str , property name
: param direct _ erro... | if direct_errors is None and schema_errors is None :
return self
# direct errors
if direct_errors is not None :
if property_name not in self . errors :
self . errors [ property_name ] = dict ( )
if 'direct' not in self . errors [ property_name ] :
self . errors [ property_name ] [ 'direct' ]... |
def interpret_maskval ( paramDict ) :
"""Apply logic for interpreting final _ maskval value . . .""" | # interpret user specified final _ maskval value to use for initializing
# output SCI array . . .
if 'maskval' not in paramDict :
return 0
maskval = paramDict [ 'maskval' ]
if maskval is None :
maskval = np . nan
else :
maskval = float ( maskval )
# just to be clear and absolutely sure . . .
return mask... |
def save_config ( self , cmd = "write mem" , confirm = False , confirm_response = "" ) :
"""Save config : write mem""" | return super ( OneaccessOneOSBase , self ) . save_config ( cmd = cmd , confirm = confirm , confirm_response = confirm_response ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.