signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def find_missing ( message , all_params , given_opts , default_opts , header = None , prompt_missing = True ) :
"""Find and interactively prompt the user for missing parameters ,
given the list of all valid parameters and a dict of known options .
Return the ( updated dict of known options , missing , num _ pro... | # are we missing anything ?
missing_params = list ( set ( all_params ) - set ( given_opts ) )
num_prompted = 0
if not missing_params :
return given_opts , missing_params , num_prompted
if not prompt_missing : # count the number missing , and go with defaults
missing_values = set ( default_opts ) - set ( given_o... |
def add_device ( self , model , serial ) :
"""Returns ' device object ' of newly created device .
http : / / docs . exosite . com / portals / # create - device
http : / / docs . exosite . com / portals / # device - object""" | device = { 'model' : model , 'vendor' : self . vendor ( ) , 'sn' : serial , 'type' : 'vendor' }
headers = { 'User-Agent' : self . user_agent ( ) , }
headers . update ( self . headers ( ) )
r = requests . post ( self . portals_url ( ) + '/portals/' + self . portal_id ( ) + '/devices' , data = json . dumps ( device ) , h... |
def hide_intf_loopback_holder_interface_loopback_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
hide_intf_loopback_holder = ET . SubElement ( config , "hide-intf-loopback-holder" , xmlns = "urn:brocade.com:mgmt:brocade-intf-loopback" )
interface = ET . SubElement ( hide_intf_loopback_holder , "interface" )
loopback = ET . SubElement ( interface , "loopback" )
id = ET . SubElemen... |
def forward_word_end ( self , e ) :
u"""Move forward to the end of the next word . Words are composed of
letters and digits .""" | self . l_buffer . forward_word_end ( self . argument_reset )
self . finalize ( ) |
def _parse_qemu_img_info ( info ) :
'''Parse qemu - img info JSON output into disk infos dictionary''' | raw_infos = salt . utils . json . loads ( info )
disks = [ ]
for disk_infos in raw_infos :
disk = { 'file' : disk_infos [ 'filename' ] , 'file format' : disk_infos [ 'format' ] , 'disk size' : disk_infos [ 'actual-size' ] , 'virtual size' : disk_infos [ 'virtual-size' ] , 'cluster size' : disk_infos [ 'cluster-size... |
def yaml ( self , with_plugin = False ) :
"""Return YAML representation of this data - source
The output may be roughly appropriate for inclusion in a YAML
catalog . This is a best - effort implementation
Parameters
with _ plugin : bool
If True , create a " plugins " section , for cases where this source ... | from yaml import dump
data = self . _yaml ( with_plugin = with_plugin )
return dump ( data , default_flow_style = False ) |
def map_alleles ( self , mapping , copy = True ) :
"""Transform alleles via a mapping .
Parameters
mapping : ndarray , int8 , shape ( n _ variants , max _ allele )
An array defining the allele mapping for each variant .
copy : bool , optional
If True , return a new array ; if False , apply mapping in plac... | # check inputs
mapping = asarray_ndim ( mapping , 2 )
check_dim0_aligned ( self , mapping )
# use optimisation
mapping = np . asarray ( mapping , dtype = self . dtype )
mapping = memoryview_safe ( mapping )
values = memoryview_safe ( self . values )
data = haplotype_array_map_alleles ( values , mapping , copy = copy )
... |
def auto_dict ( ival = None , miss = None ) :
'''auto _ dict ( ) yields an auto - dict that vivifies value of { } on miss .
auto _ dict ( ival ) uses the given dict ival as an initializer .
auto _ dict ( ival , miss ) uses the given miss function .
auto _ dict ( None , miss ) is equivalent to auto _ dict ( ) ... | if ival is None :
d = AutoDict ( )
else :
d = AutoDict ( ival )
if miss == { } or miss is None :
return d
elif miss == [ ] :
d . on_miss = lambda : [ ]
elif miss == set ( [ ] ) :
d . on_miss = lambda : set ( [ ] )
else :
d . on_miss = miss
return d |
def get_rt ( self ) :
"""Returns the right top border of the cell""" | cell_above_right = CellBorders ( self . cell_attributes , * self . cell . get_above_right_key_rect ( ) )
return cell_above_right . get_b ( ) |
def list_anime_series ( self , sort = META . SORT_ALPHA , limit = META . MAX_SERIES , offset = 0 ) :
"""Get a list of anime series
@ param str sort pick how results should be sorted , should be one
of META . SORT _ *
@ param int limit limit number of series to return , there doesn ' t
seem to be an upper bo... | result = self . _android_api . list_series ( media_type = ANDROID . MEDIA_TYPE_ANIME , filter = sort , limit = limit , offset = offset )
return result |
def get ( self , variable_path : str , default : t . Optional [ t . Any ] = None , coerce_type : t . Optional [ t . Type ] = None , coercer : t . Optional [ t . Callable ] = None , required : bool = False , ** kwargs ) :
"""Tries to read a ` ` variable _ path ` ` from each of the passed parsers .
It stops if read... | for p in self . parsers :
try :
val = p . get ( variable_path , default = self . sentinel , coerce_type = coerce_type , coercer = coercer , ** kwargs )
if val != self . sentinel :
self . enqueue ( variable_path , p , val )
return val
except Exception as e :
if not... |
def init_selection ( self ) :
"""Call selection changed in the beginning , so signals get emitted once
Emit shot _ taskfile _ sel _ changed signal and asset _ taskfile _ sel _ changed .
: returns : None
: raises : None""" | si = self . shotverbrws . selected_indexes ( 0 )
if si :
self . shot_ver_sel_changed ( si [ 0 ] )
else :
self . shot_ver_sel_changed ( QtCore . QModelIndex ( ) )
ai = self . assetverbrws . selected_indexes ( 0 )
if ai :
self . asset_ver_sel_changed ( ai [ 0 ] )
else :
self . asset_ver_sel_changed ( QtCo... |
def _print ( self , tree , prefix , carryon ) :
"""Compute and print a new line of the tree .
This is a recursive function .
arguments
tree - - tree to print
prefix - - prefix to the current line to print
carryon - - prefix which is used to carry on the vertical lines""" | level = prefix . count ( self . cross ) + prefix . count ( self . vline )
len_children = 0
if isinstance ( tree , _Node ) :
len_children = len ( tree . children )
# add vertex
prefix += str ( tree )
# and as many spaces as the vertex is long
carryon += self . space * len ( str ( tree ) )
if ( level == self . maxdep... |
def conditionally_create_profile ( role_name , service_type ) :
"""Check that there is a 1:1 correspondence with an InstanceProfile having the same name
as the role , and that the role is contained in it . Create InstanceProfile and attach to role if needed .""" | # make instance profile if this service _ type gets an instance profile
if service_type not in INSTANCE_PROFILE_SERVICE_TYPES :
print_if_verbose ( "service type: {} not eligible for instance profile" . format ( service_type ) )
return
instance_profile = get_instance_profile ( role_name )
if not instance_profile... |
def optimize ( self ) :
"""Optimize index for faster by - document - id queries .""" | self . check_session ( )
result = self . session . optimize ( )
if self . autosession :
self . commit ( )
return result |
def build_data_input ( cls , name = 'input' ) :
"""Build a data input port .
: param name : port name
: type name : str
: return : port object
: rtype : PortDef""" | return cls ( name , PortDirection . INPUT , type = PortType . DATA ) |
def weather_history_at_coords ( self , lat , lon , start = None , end = None ) :
"""Queries the OWM Weather API for weather history for the specified at the
specified geographic ( eg : 51.503614 , - 0.107331 ) . A list of * Weather *
objects is returned . It is possible to query for weather history in a
close... | geo . assert_is_lon ( lon )
geo . assert_is_lat ( lat )
params = { 'lon' : lon , 'lat' : lat , 'lang' : self . _language }
if start is not None :
unix_start = timeformatutils . to_UNIXtime ( start )
current_time = time ( )
if unix_start > current_time :
raise ValueError ( "Error: the start time boun... |
def check_table ( self , instance , snmp_engine , mib_view_controller , oids , lookup_names , timeout , retries , enforce_constraints = False , mibs_to_load = None , ) :
'''Perform a snmpwalk on the domain specified by the oids , on the device
configured in instance .
lookup _ names is a boolean to specify whet... | # UPDATE : We used to perform only a snmpgetnext command to fetch metric values .
# It returns the wrong value when the OID passeed is referring to a specific leaf .
# For example :
# snmpgetnext - v2c - c public localhost : 11111 1.3.6.1.2.1.25.4.2.1.7.222
# iso . 3.6.1.2.1.25.4.2.1.7.224 = INTEGER : 2
# SOLUTION : pe... |
def Then0 ( self , f , * args , ** kwargs ) :
"""` Then0 ( f , . . . ) ` is equivalent to ` ThenAt ( 0 , f , . . . ) ` . Checkout ` phi . builder . Builder . ThenAt ` for more information .""" | return self . ThenAt ( 0 , f , * args , ** kwargs ) |
def mark_targets_as_explicit ( self , target_names ) :
"""Add ' target ' to the list of targets in this project
that should be build only by explicit request .""" | # Record the name of the target , not instance , since this
# rule is called before main target instaces are created .
assert is_iterable_typed ( target_names , basestring )
self . explicit_targets_ . update ( target_names ) |
def post_public ( self , path , data , is_json = True ) :
'''Make a post request requiring no auth .''' | return self . _post ( path , data , is_json ) |
def c_rho0 ( self , rho0 ) :
"""computes the concentration given a comoving overdensity rho0 ( inverse of function rho0 _ c )
: param rho0 : density normalization in h ^ 2 / Mpc ^ 3 ( comoving )
: return : concentration parameter c""" | if not hasattr ( self , '_c_rho0_interp' ) :
c_array = np . linspace ( 0.1 , 10 , 100 )
rho0_array = self . rho0_c ( c_array )
from scipy import interpolate
self . _c_rho0_interp = interpolate . InterpolatedUnivariateSpline ( rho0_array , c_array , w = None , bbox = [ None , None ] , k = 3 )
return self... |
def cut ( self , name , disconnect = False ) :
"""Cut a wire ( undo a wire ( ) call )
Arguments :
- name ( str ) : name of the wire
Keyword Arguments :
- disconnect ( bool ) : if True also disconnect all connections on the
specified wire""" | wire = getattr ( self , name , None )
if wire and isinstance ( wire , Wire ) :
if name != "main" :
delattr ( self , name )
if disconnect :
wire . disconnect ( )
wire . off ( "receive" , self . on_receive )
if self . main == wire :
self . main = None
self . set_main_wire (... |
def get_annotation_url ( module , version ) :
"""Get a BEL annotation file from artifactory given the name and version .
: param str module :
: param str version :
: type : str""" | module = module . strip ( '/' )
return '{module}/{name}' . format ( module = get_annotation_module_url ( module ) , name = get_annotation_file_name ( module , version ) , ) |
def clear_stalled_files ( self ) :
"""Scan upload directory and delete stalled files .
Stalled files are files uploaded more than
` DELETE _ STALLED _ AFTER ` seconds ago .""" | # FIXME : put lock in directory ?
CLEAR_AFTER = self . config [ "DELETE_STALLED_AFTER" ]
minimum_age = time . time ( ) - CLEAR_AFTER
for user_dir in self . UPLOAD_DIR . iterdir ( ) :
if not user_dir . is_dir ( ) :
logger . error ( "Found non-directory in upload dir: %r" , bytes ( user_dir ) )
contin... |
def match ( self , name , chamber = None ) :
"""If this matcher has uniquely seen a matching name , return its
value . Otherwise , return None .
If chamber is set then the search will be limited to legislators
with matching chamber . If chamber is None then the search
will be cross - chamber .""" | try :
return self . _manual [ chamber ] [ name ]
except KeyError :
pass
if chamber == 'joint' :
chamber = None
try :
return self . _codes [ chamber ] [ name ]
except KeyError :
pass
if chamber not in self . _names :
logger . warning ( "Chamber %s is invalid for a legislator." % ( chamber ) )
... |
def p_args ( self , p ) :
"""args : LPAR pos _ args _ list COMMA kw _ args RPAR
| LPAR pos _ args _ list RPAR
| LPAR kw _ args RPAR
| LPAR RPAR
| empty""" | if len ( p ) > 3 :
if p [ 3 ] == ',' :
p [ 0 ] = ( p [ 2 ] , p [ 4 ] )
elif isinstance ( p [ 2 ] , dict ) :
p [ 0 ] = ( [ ] , p [ 2 ] )
else :
p [ 0 ] = ( p [ 2 ] , { } )
else :
p [ 0 ] = ( [ ] , { } ) |
def datastore ( args ) :
"""% prog datastore datastore . log > gfflist . log
Generate a list of gff filenames to merge . The ` datastore . log ` file can be
generated by something like :
$ find
/ usr / local / scratch / htang / EVM _ test / gannotation / maker / 1132350111853 _ default / i1/
- maxdepth 4 ... | p = OptionParser ( datastore . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
ds , = args
fp = open ( ds )
for row in fp :
fn = row . strip ( )
assert op . exists ( fn )
pp , logfile = op . split ( fn )
flog = open ( fn )
for row in f... |
def strict_resolve ( self , context , ignore_failures = False ) :
"""Resolves a ` ` FilterExpression ` ` within the context of the template .
This patched method acts as a proxy to the original , but forces
` ` ignore _ failures ` ` to False so that an exception is always raised when a
variable is accessed ou... | return __orig_resolve ( self , context , ignore_failures = False ) |
def findSnpWithMaf0 ( freqFileName , prefix ) :
"""Finds SNPs with MAF of 0 and put them in a file .
: param freqFileName : the name of the frequency file .
: param prefix : the prefix of all the files .
: type freqFileName : str
: type prefix : str
Reads a frequency file from Plink , and find markers wit... | maf_0_set = set ( )
na_set = set ( )
try :
with open ( freqFileName , "r" ) as inputFile :
headerIndex = None
for i , line in enumerate ( inputFile ) :
row = createRowFromPlinkSpacedOutput ( line )
if i == 0 : # We have the header
headerIndex = dict ( [ ( row ... |
def pipe_to_process ( self , payload ) :
"""Send something to stdin of a specific process .""" | message = payload [ 'input' ]
key = payload [ 'key' ]
if not self . process_handler . is_running ( key ) :
return { 'message' : 'No running process for this key' , 'status' : 'error' }
self . process_handler . send_to_process ( message , key )
return { 'message' : 'Message sent' , 'status' : 'success' } |
def peek_stack_data ( self , size = 128 , offset = 0 ) :
"""Tries to read the contents of the top of the stack .
@ type size : int
@ param size : Number of bytes to read .
@ type offset : int
@ param offset : Offset from the stack pointer to begin reading .
@ rtype : str
@ return : Stack data .
Return... | aProcess = self . get_process ( )
return aProcess . peek ( self . get_sp ( ) + offset , size ) |
def throw_if_parsable ( resp ) :
"""Try to parse the content of the response and raise an exception
if neccessary .""" | e = None
try :
e = parse_response ( resp )
except : # Error occurred during parsing the response . We ignore it and delegate
# the situation to caller to handle .
LOG . debug ( utils . stringify_expt ( ) )
if e is not None :
raise e
if resp . status_code == 404 :
raise NoSuchObject ( 'No such object.' )... |
def data ( self ) :
"""Data used to render slice in templates""" | d = { }
self . token = ''
try :
d = self . viz . data
self . token = d . get ( 'token' )
except Exception as e :
logging . exception ( e )
d [ 'error' ] = str ( e )
return { 'datasource' : self . datasource_name , 'description' : self . description , 'description_markeddown' : self . description_markedd... |
def validate ( schema ) :
"""Validate that a supposed schema is in fact a Table Schema .""" | try :
tableschema . validate ( schema )
click . echo ( "Schema is valid" )
sys . exit ( 0 )
except tableschema . exceptions . ValidationError as exception :
click . echo ( "Schema is not valid" )
click . echo ( exception . errors )
sys . exit ( 1 ) |
def provider ( cls , note , provider = None , name = False ) :
"""Register a provider , either a Provider class or a generator .
Provider class : :
from jeni import Injector as BaseInjector
from jeni import Provider
class Injector ( BaseInjector ) :
pass
@ Injector . provider ( ' hello ' )
class Hello... | def decorator ( provider ) :
if inspect . isgeneratorfunction ( provider ) : # Automatically adapt generator functions
provider = cls . generator_provider . bind ( provider , support_name = name )
return decorator ( provider )
cls . register ( note , provider )
return provider
if provider is... |
def config_vars ( profiles , advance_access ) :
"""Utility method to fetch config vars using ini section profile
: param profiles : profile name .
: param advance _ access : advance _ access flag .
: return :""" | for profile in profiles :
try :
config = Config ( profile , advance_access = advance_access )
url = config . api_endpoint
token = config . auth_token
proxies = config . proxies
aa = config . advance_access
return url , token , proxies , aa
except Exception :
... |
def requirement_args ( argv , want_paths = False , want_other = False ) :
"""Return an iterable of filtered arguments .
: arg argv : Arguments , starting after the subcommand
: arg want _ paths : If True , the returned iterable includes the paths to any
requirements files following a ` ` - r ` ` or ` ` - - re... | was_r = False
for arg in argv : # Allow for requirements files named " - r " , don ' t freak out if there ' s a
# trailing " - r " , etc .
if was_r :
if want_paths :
yield arg
was_r = False
elif arg in [ '-r' , '--requirement' ] :
was_r = True
else :
if want_other... |
def asset_versions ( self ) :
"""Access the asset _ versions
: returns : twilio . rest . serverless . v1 . service . asset . asset _ version . AssetVersionList
: rtype : twilio . rest . serverless . v1 . service . asset . asset _ version . AssetVersionList""" | if self . _asset_versions is None :
self . _asset_versions = AssetVersionList ( self . _version , service_sid = self . _solution [ 'service_sid' ] , asset_sid = self . _solution [ 'sid' ] , )
return self . _asset_versions |
def removeSpecfile ( self , specfiles ) :
"""Completely removes the specified specfiles from the ` ` SiiContainer ` ` .
: param specfiles : the name of an ms - run file or a list of names .""" | for specfile in aux . toList ( specfiles ) :
del self . container [ specfile ]
del self . info [ specfile ] |
def delete ( self ) :
"""Remove from database .""" | if not self . id :
return
self . collection . remove ( { '_id' : self . _id } )
self . on_delete ( self ) |
def mv_connect_stations ( mv_grid_district , graph , debug = False ) :
"""Connect LV stations to MV grid
Args
mv _ grid _ district : MVGridDistrictDing0
MVGridDistrictDing0 object for which the connection process has to be done
graph : : networkx : ` NetworkX Graph Obj < > `
NetworkX graph object with nod... | # WGS84 ( conformal ) to ETRS ( equidistant ) projection
proj1 = partial ( pyproj . transform , pyproj . Proj ( init = 'epsg:4326' ) , # source coordinate system
pyproj . Proj ( init = 'epsg:3035' ) )
# destination coordinate system
# ETRS ( equidistant ) to WGS84 ( conformal ) projection
proj2 = partial ( pyproj . tra... |
def velocity_embedding_stream ( adata , basis = None , vkey = 'velocity' , density = None , smooth = None , linewidth = None , n_neighbors = None , X = None , V = None , X_grid = None , V_grid = None , color = None , use_raw = None , layer = None , color_map = None , colorbar = True , palette = None , size = None , alp... | basis = default_basis ( adata ) if basis is None else basis
colors , layers , vkeys = make_unique_list ( color , allow_array = True ) , make_unique_list ( layer ) , make_unique_list ( vkey )
for key in vkeys :
if key + '_' + basis not in adata . obsm_keys ( ) and V is None :
velocity_embedding ( adata , bas... |
def select ( self , template_name ) :
"""Select a specific family from the party .
: type template _ name : str
: param template _ name : Template name of Family to select from a party .
: returns : Family""" | return [ fam for fam in self . families if fam . template . name == template_name ] [ 0 ] |
def phi_effect_mip ( self , mechanism , purview ) :
"""Return the | small _ phi | of the effect MIP .
This is the distance between the unpartitioned effect repertoire and
the MIP cause repertoire .""" | mip = self . effect_mip ( mechanism , purview )
return mip . phi if mip else 0 |
def update ( self , updict ) :
"""Updates key / value pairs in dictionary from _ updict _ .""" | with self . lock :
for ( key , value ) in updict . items ( ) :
self . setitem ( key , value ) |
def _to_args ( x ) :
"""Convert to args representation""" | if not isinstance ( x , ( list , tuple , np . ndarray ) ) :
x = [ x ]
return x |
def disp ( self , modulo = None ) : # TODO : rather assign opt [ ' verb _ disp ' ] as default ?
"""prints some single - line infos according to ` disp _ annotation ( ) ` ,
if ` ` iteration _ counter % modulo = = 0 ` `""" | if modulo is None :
modulo = self . opts [ 'verb_disp' ]
# console display
if modulo :
if ( self . countiter - 1 ) % ( 10 * modulo ) < 1 :
self . disp_annotation ( )
if self . countiter > 0 and ( self . stop ( ) or self . countiter < 4 or self . countiter % modulo < 1 ) :
if self . opts [ 'v... |
def _FormatUsername ( self , event ) :
"""Formats the username .
Args :
event ( EventObject ) : event .
Returns :
str : formatted username field .""" | username = self . _output_mediator . GetUsername ( event )
return self . _SanitizeField ( username ) |
def get_vcenter_data_model ( self , api , vcenter_name ) :
""": param api :
: param str vcenter _ name :
: rtype : VMwarevCenterResourceModel""" | if not vcenter_name :
raise ValueError ( 'VMWare vCenter name is empty' )
vcenter_instance = api . GetResourceDetails ( vcenter_name )
vcenter_resource_model = self . resource_model_parser . convert_to_vcenter_model ( vcenter_instance )
return vcenter_resource_model |
def find_components_without_annotation ( model , components ) :
"""Find model components with empty annotation attributes .
Parameters
model : cobra . Model
A cobrapy metabolic model .
components : { " metabolites " , " reactions " , " genes " }
A string denoting ` cobra . Model ` components .
Returns
... | return [ elem for elem in getattr ( model , components ) if elem . annotation is None or len ( elem . annotation ) == 0 ] |
def viewbox_mouse_event ( self , event ) :
"""The SubScene received a mouse event ; update transform
accordingly .
Parameters
event : instance of Event
The event .""" | if event . handled or not self . interactive :
return
# Scrolling
BaseCamera . viewbox_mouse_event ( self , event )
if event . type == 'mouse_wheel' :
center = self . _scene_transform . imap ( event . pos )
self . zoom ( ( 1 + self . zoom_factor ) ** ( - event . delta [ 1 ] * 30 ) , center )
event . han... |
def sys_info ( fname = None , overwrite = False ) :
"""Get relevant system and debugging information
Parameters
fname : str | None
Filename to dump info to . Use None to simply print .
overwrite : bool
If True , overwrite file ( if it exists ) .
Returns
out : str
The system information as a string .... | if fname is not None and op . isfile ( fname ) and not overwrite :
raise IOError ( 'file exists, use overwrite=True to overwrite' )
out = ''
try : # Nest all imports here to avoid any circular imports
from . . app import use_app , Canvas
from . . app . backends import BACKEND_NAMES
from . . gloo import ... |
def _set_stream_parameters ( self , ** kwargs ) :
"""Sets the stream parameters which are expected to be declared
constant .""" | with util . disable_constant ( self ) :
self . param . set_param ( ** kwargs ) |
def registration ( uri ) :
"""Responses handler registration .
Registers a handler for a given URI with Responses
so that it can be intercepted and handed to
Stack - In - A - Box .
: param uri : URI used for the base of the HTTP requests
: returns : n / a""" | # log the URI that is used to access the Stack - In - A - Box services
logger . debug ( 'Registering Stack-In-A-Box at {0} under Python Responses' . format ( uri ) )
# tell Stack - In - A - Box what URI to match with
StackInABox . update_uri ( uri )
# Build the regex for the URI and register all HTTP verbs
# with Respo... |
def _return_tables ( self , mag , imt , val_type ) :
"""Returns the vector of ground motions or standard deviations
corresponding to the specific magnitude and intensity measure type .
: param val _ type :
String indicating the type of data { " IMLs " , " Total " , " Inter " etc }""" | if imt . name in 'PGA PGV' : # Get scalar imt
if val_type == "IMLs" :
iml_table = self . imls [ imt . name ] [ : ]
else :
iml_table = self . stddevs [ val_type ] [ imt . name ] [ : ]
n_d , n_s , n_m = iml_table . shape
iml_table = iml_table . reshape ( [ n_d , n_m ] )
else :
if val_t... |
def get_available_versions ( self , project_name ) :
"""Query PyPI to see if package has any available versions .
Args :
project _ name ( str ) : The name the project on PyPI .
Returns :
dict : Where keys are tuples of parsed versions and values are the
versions returned by PyPI .""" | available_versions = self . pypi_client . package_releases ( project_name )
if not available_versions :
available_versions = self . pypi_client . package_releases ( project_name . capitalize ( ) )
# ` ` dict ( ) ` ` for Python 2.6 syntax .
return dict ( ( self . _parse_version ( version ) , version ) for version in... |
def from_block ( cls , block ) :
"""Instantiate this class given a raw block ( see parse _ raw ) .""" | rseqs = cma . realign_seqs ( block )
records = ( SeqRecord ( Seq ( rseq , extended_protein ) , id = bseq [ 'id' ] , description = bseq [ 'description' ] , dbxrefs = bseq [ 'dbxrefs' ] . values ( ) , # list of strings
annotations = dict ( index = bseq [ 'index' ] , length = bseq [ 'length' ] , dbxrefs = bseq [ 'dbxrefs'... |
def colstack ( seq , mode = 'abort' , returnnaming = False ) :
"""Horizontally stack a sequence of numpy ndarrays with structured dtypes
Analog of numpy . hstack for recarrays .
Implemented by the tabarray method
: func : ` tabular . tab . tabarray . colstack ` which uses
: func : ` tabular . tabarray . tab... | assert mode in [ 'first' , 'drop' , 'abort' , 'rename' ] , 'mode argument must take on value "first","drop", "rename", or "abort".'
AllNames = utils . uniqify ( utils . listunion ( [ list ( l . dtype . names ) for l in seq ] ) )
NameList = [ ( x , [ i for i in range ( len ( seq ) ) if x in seq [ i ] . dtype . names ] )... |
def get_definition ( self , info ) :
"""Find the definition for an object within a set of source code
This is used to find the path of python - like modules
( e . g . cython and enaml ) for a goto definition""" | if not info [ 'is_python_like' ] :
return
token = info [ 'obj' ]
lines = info [ 'lines' ]
source_code = info [ 'source_code' ]
filename = info [ 'filename' ]
line_nr = None
if token is None :
return
if '.' in token :
token = token . split ( '.' ) [ - 1 ]
line_nr = get_definition_with_regex ( source_code , t... |
def symlink_remove ( link ) :
"""Remove a symlink . Used for model shortcut links .
link ( unicode / Path ) : The path to the symlink .""" | # https : / / stackoverflow . com / q / 26554135/6400719
if os . path . isdir ( path2str ( link ) ) and is_windows : # this should only be on Py2.7 and windows
os . rmdir ( path2str ( link ) )
else :
os . unlink ( path2str ( link ) ) |
def get_tfidf ( self , term , document , normalized = False ) :
"""Returns the Term - Frequency Inverse - Document - Frequency value for the given
term in the specified document . If normalized is True , term frequency will
be divided by the document length .""" | tf = self . get_term_frequency ( term , document )
# Speeds up performance by avoiding extra calculations
if tf != 0.0 : # Add 1 to document frequency to prevent divide by 0
# ( Laplacian Correction )
df = 1 + self . get_document_frequency ( term )
n = 2 + len ( self . _documents )
if normalized :
t... |
def validate ( self , value ) :
"""Validate value .
: param value : Value which should be validated .
: raises : : class : ` halogen . exception . ValidationError ` exception when either if value less than min in case when
min is not None or if value greater than max in case when max is not None .""" | if self . min is not None :
min_value = self . min ( ) if callable ( self . min ) else self . min
if value < min_value :
raise exceptions . ValidationError ( self . min_err . format ( val = value , min = min_value ) )
if self . max is not None :
max_value = self . max ( ) if callable ( self . max ) ... |
def GetNodes ( r , bulk = False ) :
"""Gets all nodes in the cluster .
@ type bulk : bool
@ param bulk : whether to return all information about all instances
@ rtype : list of dict or str
@ return : if bulk is true , info about nodes in the cluster ,
else list of nodes in the cluster""" | if bulk :
return r . request ( "get" , "/2/nodes" , query = { "bulk" : 1 } )
else :
nodes = r . request ( "get" , "/2/nodes" )
return r . applier ( itemgetters ( "id" ) , nodes ) |
def accepts_contributor_roles ( func ) :
"""Decorator that accepts only contributor roles
: param func :
: return :""" | if inspect . isclass ( func ) :
apply_function_to_members ( func , accepts_contributor_roles )
return func
else :
@ functools . wraps ( func )
def decorator ( * args , ** kwargs ) :
return accepts_roles ( * ROLES_CONTRIBUTOR ) ( func ) ( * args , ** kwargs )
return decorator |
def _parse_record ( data , duration_format = 'seconds' ) :
"""Parse a raw data dictionary and return a Record object .""" | def _map_duration ( s ) :
if s == '' :
return None
elif duration_format . lower ( ) == 'seconds' :
return int ( s )
else :
t = time . strptime ( s , duration_format )
return 3600 * t . tm_hour + 60 * t . tm_min + t . tm_sec
def _map_position ( data ) :
antenna = Position ... |
def _set_scan_parameters ( self , interval = 2100 , window = 2100 , active = False ) :
"""Set the scan interval and window in units of ms and set whether active scanning is performed""" | active_num = 0
if bool ( active ) :
active_num = 1
interval_num = int ( interval * 1000 / 625 )
window_num = int ( window * 1000 / 625 )
payload = struct . pack ( "<HHB" , interval_num , window_num , active_num )
try :
response = self . _send_command ( 6 , 7 , payload )
if response . payload [ 0 ] != 0 :
... |
def lookup ( self , label ) :
'''take a field _ name _ label and return the id''' | if self . is_child :
try :
return self . _children [ label ]
except KeyError :
self . _children [ label ] = ChildFieldPicklist ( self . parent , label , self . field_name )
return self . _children [ label ]
else :
return get_label_value ( label , self . _picklist ) |
def frange ( start , end , step ) :
"""Like range ( ) , but with floats .""" | val = start
while val < end :
yield val
val += step |
def pipeline ( names , steps ) :
"""Reconstruct a Pipeline from names and steps""" | steps , times = zip ( * map ( _maybe_timed , steps ) )
fit_time = sum ( times )
if any ( s is FIT_FAILURE for s in steps ) :
fit_est = FIT_FAILURE
else :
fit_est = Pipeline ( list ( zip ( names , steps ) ) )
return fit_est , fit_time |
def exists ( self , filename ) :
"""Check for the existence of a package or script .
Unlike other DistributionPoint types , JDS and CDP types have no
documented interface for checking whether the server and its
children have a complete copy of a file . The best we can do is
check for an object using the API... | # Technically , the results of the casper . jxml page list the
# package files on the server . This is an undocumented
# interface , however .
result = False
if is_package ( filename ) :
packages = self . connection [ "jss" ] . Package ( ) . retrieve_all ( )
for package in packages :
if package . findte... |
def disable_auth_method ( self , path ) :
"""Disable the auth method at the given auth path .
Supported methods :
DELETE : / sys / auth / { path } . Produces : 204 ( empty body )
: param path : The path the method was mounted on . If not provided , defaults to the value of the " method _ type "
argument .
... | api_path = '/v1/sys/auth/{path}' . format ( path = path )
return self . _adapter . delete ( url = api_path , ) |
async def enable_user ( self , username ) :
"""Re - enable a previously disabled user .""" | user_facade = client . UserManagerFacade . from_connection ( self . connection ( ) )
entity = client . Entity ( tag . user ( username ) )
return await user_facade . EnableUser ( [ entity ] ) |
def format_citations ( zid , url = 'https://zenodo.org/' , hits = 10 , tag_prefix = 'v' ) :
"""Query and format a citations page from Zenodo entries
Parameters
zid : ` int ` , ` str `
the Zenodo ID of the target record
url : ` str ` , optional
the base URL of the Zenodo host , defaults to ` ` https : / / ... | # query for metadata
url = ( '{url}/api/records/?' 'page=1&' 'size={hits}&' 'q=conceptrecid:"{id}"&' 'sort=-version&' 'all_versions=True' . format ( id = zid , url = url , hits = hits ) )
metadata = requests . get ( url ) . json ( )
lines = [ ]
for i , hit in enumerate ( metadata [ 'hits' ] [ 'hits' ] ) :
version =... |
def remove_choice_language ( self , language_type , choice_id , inline_region ) :
"""stub""" | if len ( self . my_osid_object_form . _my_map [ 'choices' ] [ inline_region ] ) == 0 :
raise IllegalState ( 'there are currently no choices defined for this region' )
if self . get_choices_metadata ( ) . is_read_only ( ) :
raise NoAccess ( )
choices = [ c for c in self . my_osid_object_form . _my_map [ 'choices... |
def temp_files ( self ) :
"""Return a list of the temporary files produced by this link .
This returns all files that were explicitly marked for removal .""" | ret_list = [ ]
for key , val in self . file_dict . items ( ) : # For temp files we only want files that were marked for removal
if val & FileFlags . rm_mask :
ret_list . append ( key )
return ret_list |
def register ( self , user_dict ) :
"""Send an user _ dict to NApps server using POST request .
Args :
user _ dict ( dict ) : Dictionary with user attributes .
Returns :
result ( string ) : Return the response of Napps server .""" | endpoint = os . path . join ( self . _config . get ( 'napps' , 'api' ) , 'users' , '' )
res = self . make_request ( endpoint , method = 'POST' , json = user_dict )
return res . content . decode ( 'utf-8' ) |
def delete ( self , table , keyset ) :
"""Delete one or more table rows .
: type table : str
: param table : Name of the table to be modified .
: type keyset : : class : ` ~ google . cloud . spanner _ v1 . keyset . Keyset `
: param keyset : Keys / ranges identifying rows to delete .""" | delete = Mutation . Delete ( table = table , key_set = keyset . _to_pb ( ) )
self . _mutations . append ( Mutation ( delete = delete ) ) |
def _Open ( self , path_spec , mode = 'rb' ) :
"""Opens the file system object defined by path specification .
Args :
path _ spec ( PathSpec ) : path specification .
mode ( Optional [ str ] ) : file access mode . The default is ' rb ' which
represents read - only binary .
Raises :
AccessError : if the a... | if not path_spec . HasParent ( ) :
raise errors . PathSpecError ( 'Unsupported path specification without parent.' )
file_object = resolver . Resolver . OpenFileObject ( path_spec . parent , resolver_context = self . _resolver_context )
try :
fsnfts_volume = pyfsntfs . volume ( )
fsnfts_volume . open_file_o... |
def _enforce_ttl_key ( self , key ) :
'''Enforce the TTL to a specific key , delete if its past TTL''' | if key not in self . _key_cache_time or self . _ttl == 0 :
return
if time . time ( ) - self . _key_cache_time [ key ] > self . _ttl :
del self . _key_cache_time [ key ]
dict . __delitem__ ( self , key ) |
def bulk_add_units ( unit_list , ** kwargs ) :
"""Save all the units contained in the passed list , with the name of their dimension .""" | # for unit in unit _ list :
# add _ unit ( unit , * * kwargs )
added_units = [ ]
for unit in unit_list :
added_units . append ( add_unit ( unit , ** kwargs ) )
return JSONObject ( { "units" : added_units } ) |
def summarizeResults ( expName , suite ) :
"""Summarize the totalCorrect value from the last iteration for each experiment
in the directory tree .""" | print ( "\n================" , expName , "=====================" )
try : # Retrieve the last totalCorrect from each experiment
# Print them sorted from best to worst
values , params = suite . get_values_fix_params ( expName , 0 , "totalCorrect" , "last" )
v = np . array ( values )
sortedIndices = v . argsor... |
def archive ( self , target_path = None , zip_path = None ) :
"""Writes the Zip - encoded file to a directory .
: param target _ path : The directory path to add .
: type target _ path : str
: param zip _ path : The file path of the ZIP archive .
: type zip _ path : str""" | if target_path :
self . target_path = target_path
if zip_path :
self . zip_path = zip_path
if self . has_path is False or os . path . isdir ( self . target_path ) is False :
raise RuntimeError ( "" )
zip = zipfile . ZipFile ( self . zip_path , 'w' , zipfile . ZIP_DEFLATED )
for root , _ , files in os . walk... |
def lookup ( path , cache = True , scope = None , safe = False ) :
"""Get element reference from input element .
The element can be a builtin / globals / scope object or is resolved from the
current execution stack .
: limitations : it does not resolve class methods or static values such as
True , False , n... | result = None
found = path and cache and path in __LOOKUP_CACHE
if found :
result = __LOOKUP_CACHE [ path ]
elif path :
_eval = safe_eval if safe else eval
try : # search among scope
result = _eval ( path , scope )
except ( NameError , SyntaxError ) : # we generate a result in order to accept th... |
def read_samples ( self , sr = None , offset = 0 , duration = None ) :
"""Return the samples from the file .
Uses librosa for loading
( see http : / / librosa . github . io / librosa / generated / librosa . core . load . html ) .
Args :
sr ( int ) : If ` ` None ` ` , uses the sampling rate given by the file... | samples , __ = librosa . core . load ( self . path , sr = sr , offset = offset , duration = duration )
return samples |
def convert2wavenumber ( rsr ) :
"""Take rsr data set with all channels and detectors for an instrument
each with a set of wavelengths and normalised responses and
convert to wavenumbers and responses
: rsr : Relative Spectral Response function ( all bands )
Returns :
: retv : Relative Spectral Responses ... | retv = { }
for chname in rsr . keys ( ) : # Go through bands / channels
retv [ chname ] = { }
for det in rsr [ chname ] . keys ( ) : # Go through detectors
retv [ chname ] [ det ] = { }
if 'wavenumber' in rsr [ chname ] [ det ] . keys ( ) : # Make a copy . Data are already in wave number space
... |
def calc_bca_interval ( bootstrap_replicates , jackknife_replicates , mle_params , conf_percentage ) :
"""Calculate ' bias - corrected and accelerated ' bootstrap confidence intervals .
Parameters
bootstrap _ replicates : 2D ndarray .
Each row should correspond to a different bootstrap parameter sample .
Ea... | # Check validity of arguments
check_conf_percentage_validity ( conf_percentage )
ensure_samples_is_ndim_ndarray ( bootstrap_replicates , ndim = 2 )
ensure_samples_is_ndim_ndarray ( jackknife_replicates , name = 'jackknife' , ndim = 2 )
# Calculate the alpha * 100 % value
alpha_percent = get_alpha_from_conf_percentage (... |
def get_usb_serial ( self , port_num ) :
"""Get the device serial number
Args :
port _ num : port number on the Cambrionix unit
Return :
usb device serial number""" | port = self . port_map [ str ( port_num ) ]
arg = '' . join ( [ 'DEVICE INFO,' , self . _addr , '.' , port ] )
cmd = ( [ 'esuit64' , '-t' , arg ] )
info = subprocess . check_output ( cmd , stderr = subprocess . STDOUT )
serial = None
if "SERIAL" in info :
serial_info = info . split ( 'SERIAL:' ) [ 1 ]
serial = ... |
def run_queue ( self , options , todo ) :
"""Actually run the _ todo _ tasklet .""" | utils . logging_debug ( 'AutoBatcher(%s): %d items' , self . _todo_tasklet . __name__ , len ( todo ) )
batch_fut = self . _todo_tasklet ( todo , options )
self . _running . append ( batch_fut )
# Add a callback when we ' re done .
batch_fut . add_callback ( self . _finished_callback , batch_fut , todo ) |
def safe_makedir ( dname ) :
"""Make a directory if it doesn ' t exist , handling concurrent race conditions .""" | if not dname :
return dname
num_tries = 0
max_tries = 5
while not os . path . exists ( dname ) : # we could get an error here if multiple processes are creating
# the directory at the same time . Grr , concurrency .
try :
os . makedirs ( dname )
except OSError :
if num_tries > max_tries :
... |
def collection_index ( self ) :
"""Collection index link to self . indexes , the order should be :
1 . command argument
2 . environment
3 . default packages directory""" | indexes = self . options . index
# add current directory to indexes
indexes . insert ( 0 , os . getcwd ( ) )
if 'IDO_INDEXES' in os . environ :
indexes . extend ( os . environ [ 'IDO_INDEXES' ] . split ( ';' ) )
indexes . append ( os . path . join ( os . path . dirname ( __file__ ) , 'packages' ) . replace ( '\\' ,... |
def point_mutation ( self , random_state ) :
"""Perform the point mutation operation on the program .
Point mutation selects random nodes from the embedded program to be
replaced . Terminals are replaced by other terminals and functions are
replaced by other functions that require the same number of arguments... | program = copy ( self . program )
# Get the nodes to modify
mutate = np . where ( random_state . uniform ( size = len ( program ) ) < self . p_point_replace ) [ 0 ]
for node in mutate :
if isinstance ( program [ node ] , _Function ) :
arity = program [ node ] . arity
# Find a valid replacement with ... |
def mode ( self , mode ) :
"""Sets the mode of this BraintreeGateway .
: param mode : The mode of this BraintreeGateway .
: type : str""" | allowed_values = [ "test" , "live" ]
if mode is not None and mode not in allowed_values :
raise ValueError ( "Invalid value for `mode` ({0}), must be one of {1}" . format ( mode , allowed_values ) )
self . _mode = mode |
def parse_api_groups ( self , request_resources = False , update = False ) :
"""Discovers all API groups present in the cluster""" | if not self . _cache . get ( 'resources' ) or update :
self . _cache [ 'resources' ] = self . _cache . get ( 'resources' , { } )
groups_response = load_json ( self . client . request ( 'GET' , '/{}' . format ( DISCOVERY_PREFIX ) ) ) [ 'groups' ]
groups = self . default_groups ( request_resources = request_r... |
def terminate_instance ( self , instance_id , decrement_capacity = True ) :
"""Terminates the specified instance . The desired group size can
also be adjusted , if desired .
: type instance _ id : str
: param instance _ id : The ID of the instance to be terminated .
: type decrement _ capability : bool
: ... | params = { 'InstanceId' : instance_id }
if decrement_capacity :
params [ 'ShouldDecrementDesiredCapacity' ] = 'true'
else :
params [ 'ShouldDecrementDesiredCapacity' ] = 'false'
return self . get_object ( 'TerminateInstanceInAutoScalingGroup' , params , Activity ) |
def confd_state_internal_callpoints_snmp_notification_subscription_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
confd_state = ET . SubElement ( config , "confd-state" , xmlns = "http://tail-f.com/yang/confd-monitoring" )
internal = ET . SubElement ( confd_state , "internal" )
callpoints = ET . SubElement ( internal , "callpoints" )
snmp_notification_subscription = ET . SubElement ( callpoints ,... |
def require_attribute_value ( self , attribute : str , value : Union [ int , str , float , bool , None ] ) -> None :
"""Require an attribute on the node to have a particular value .
This requires the attribute to exist , and to have the given value and corresponding type . Handy for in your yatiml _ recognize ( )... | found = False
for key_node , value_node in self . yaml_node . value :
if ( key_node . tag == 'tag:yaml.org,2002:str' and key_node . value == attribute ) :
found = True
node = Node ( value_node )
if not node . is_scalar ( type ( value ) ) :
raise RecognitionError ( ( '{}{}Incorrec... |
def parse_mutator_settings ( mutator_settings , config : ConfigObject ) :
"""Assigns the mutator settings to the settings object for the dll
: param mutator _ settings :
: param config :""" | mutator_settings . match_length = safe_get_mutator ( match_length_types , config , MUTATOR_MATCH_LENGTH )
mutator_settings . max_score = safe_get_mutator ( max_score_types , config , MUTATOR_MAX_SCORE , { '0' : 'Unlimited' } )
mutator_settings . overtime = safe_get_mutator ( overtime_mutator_types , config , MUTATOR_OV... |
def requestPositionUpdates ( self , subscribe = True ) :
"""Request / cancel request real - time position data for all accounts .""" | if self . subscribePositions != subscribe :
self . subscribePositions = subscribe
if subscribe == True :
self . ibConn . reqPositions ( )
else :
self . ibConn . cancelPositions ( ) |
def maskedNanPercentile ( maskedArray , percentiles , * args , ** kwargs ) :
"""Calculates np . nanpercentile on the non - masked values""" | # https : / / docs . scipy . org / doc / numpy / reference / maskedarray . generic . html # accessing - the - data
awm = ArrayWithMask . createFromMaskedArray ( maskedArray )
maskIdx = awm . maskIndex ( )
validData = awm . data [ ~ maskIdx ]
if len ( validData ) >= 1 :
result = np . nanpercentile ( validData , perc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.