signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_hub ( ) :
"""Return the instance of the hub .""" | try :
hub = _local . hub
except AttributeError : # The Hub can only be instantiated from the root fiber . No other fibers
# can run until the Hub is there , so the root will always be the first
# one to call get _ hub ( ) .
assert fibers . current ( ) . parent is None
hub = _local . hub = Hub ( )
return hub |
def filter ( self , ** kwargs ) :
"""Add a filter to this C { readsAlignments } .
@ param kwargs : Keyword arguments , as accepted by
C { ReadsAlignmentsFilter } .
@ return : C { self }""" | self . _filters . append ( ReadsAlignmentsFilter ( ** kwargs ) . filter )
return self |
def comprehension_walk3 ( self , node , iter_index , code_index = - 5 ) :
"""List comprehensions the way they are done in Python3.
They ' re more other comprehensions , e . g . set comprehensions
See if we can combine code .""" | p = self . prec
self . prec = 27
code = node [ code_index ] . attr
assert iscode ( code ) , node [ code_index ]
code_name = code . co_name
code = Code ( code , self . scanner , self . currentclass )
ast = self . build_ast ( code . _tokens , code . _customize )
self . customize ( code . _customize )
if ast [ 0 ] == 'sst... |
def _get_vcpu_field_and_address ( self , field_name , x , y , p ) :
"""Get the field and address for a VCPU struct field .""" | vcpu_struct = self . structs [ b"vcpu" ]
field = vcpu_struct [ six . b ( field_name ) ]
address = ( self . read_struct_field ( "sv" , "vcpu_base" , x , y ) + vcpu_struct . size * p ) + field . offset
pack_chars = b"<" + field . pack_chars
return field , address , pack_chars |
def parse_structure ( self , node ) :
"""Parses < Structure >
@ param node : Node containing the < Structure > element
@ type node : xml . etree . Element""" | self . current_structure = self . current_component_type . structure
self . process_nested_tags ( node )
self . current_structure = None |
def ui_func ( cls , id_ , name , function_type , avail_fn = always ) :
"""Define a function representing a ui action .""" | return cls ( id_ , name , 0 , 0 , function_type , FUNCTION_TYPES [ function_type ] , avail_fn ) |
def init_model_gaussian1d ( observations , nstates , reversible = True ) :
"""Generate an initial model with 1D - Gaussian output densities
Parameters
observations : list of ndarray ( ( T _ i ) , dtype = float )
list of arrays of length T _ i with observation data
nstates : int
The number of states .
Ex... | ntrajectories = len ( observations )
# Concatenate all observations .
collected_observations = np . array ( [ ] , dtype = config . dtype )
for o_t in observations :
collected_observations = np . append ( collected_observations , o_t )
# Fit a Gaussian mixture model to obtain emission distributions and state station... |
def upload ( self , env , cart , callback = None ) :
"""Nothing special happens here . This method recieves a
destination repo , and a payload of ` cart ` which will be
uploaded into the target repo .
Preparation : To use this method you must pre - process your
cart : Remotes must be fetched and saved local... | for repo in cart . repos ( ) :
if not juicer . utils . repo_exists_p ( repo , self . connectors [ env ] , env ) :
juicer . utils . Log . log_info ( "repo '%s' doesn't exist in %s environment... skipping!" , ( repo , env ) )
continue
repoid = "%s-%s" % ( repo , env )
for item in cart [ repo ]... |
def word_matches ( s1 , s2 , n = 3 ) :
"""Word - level n - grams that match between two strings
Args :
s1 : a string
s2 : another string
n : an int for the n in n - gram
Returns :
set : the n - grams found in both strings""" | return __matches ( s1 , s2 , word_ngrams , n = n ) |
def _get_nadir_pixel ( earth_mask , sector ) :
"""Find the nadir pixel
Args :
earth _ mask : Mask identifying earth and space pixels
sector : Specifies the scanned sector
Returns :
nadir row , nadir column""" | if sector == FULL_DISC :
logger . debug ( 'Computing nadir pixel' )
# The earth is not centered in the image , compute bounding box
# of the earth disc first
rmin , rmax , cmin , cmax = bbox ( earth_mask )
# The nadir pixel is approximately at the centre of the earth disk
nadir_row = rmin + ( rm... |
def get_group_tree_root ( self , page_size = 1000 ) :
r"""Return the root group for this accounts ' group tree
This will return the root group for this tree but with all links
between nodes ( i . e . children starting from root ) populated .
Examples : :
# print the group hierarchy to stdout
dc . deviceco... | # first pass , build mapping
group_map = { }
# map id - > group
page_size = validate_type ( page_size , * six . integer_types )
for group in self . get_groups ( page_size = page_size ) :
group_map [ group . get_id ( ) ] = group
# second pass , find root and populate list of children for each node
root = None
for gr... |
def send_to_cloudshark ( self , id , seq , intf , inline = False ) : # pylint : disable = invalid - name , redefined - builtin
"""Send a capture to a CloudShark Appliance . Both
cloudshark _ appliance _ url and cloudshark _ appliance _ token must
be properly configured via system preferences .
: param id : Re... | schema = CloudSharkSchema ( )
resp = self . service . post ( self . _base ( id , seq ) + str ( intf ) + '/cloudshark/' , params = { 'inline' : inline } )
return self . service . decode ( schema , resp ) |
def get_shape_infos ( df_shapes , shape_i_columns ) :
'''Return a ` pandas . DataFrame ` indexed by ` shape _ i _ columns ` ( i . e . , each row
corresponds to a single shape / polygon ) , containing the following columns :
- ` area ` : The area of the shape .
- ` width ` : The width of the widest part of the... | shape_areas = get_shape_areas ( df_shapes , shape_i_columns )
bboxes = get_bounding_boxes ( df_shapes , shape_i_columns )
return bboxes . join ( pd . DataFrame ( shape_areas ) ) |
async def _base_request ( self , battle_tag : str , endpoint_name : str , session : aiohttp . ClientSession , * , platform = None , handle_ratelimit = None , max_tries = None , request_timeout = None ) :
"""Does a request to some endpoint . This is also where ratelimit logic is handled .""" | # We check the different optional arguments , and if they ' re not passed ( are none ) we set them to the default for the client object
if platform is None :
platform = self . default_platform
if handle_ratelimit is None :
handle_ratelimit = self . default_handle_ratelimit
if max_tries is None :
max_tries =... |
def _load_source_object ( self ) :
"""Loads related object in a dynamic attribute and returns it .""" | if hasattr ( self , "source_obj" ) :
self . source_text = getattr ( self . source_obj , self . field )
return self . source_obj
self . _load_source_model ( )
self . source_obj = self . source_model . objects . get ( id = self . object_id )
return self . source_obj |
def operator_complement ( self ) :
"""Get a ` ` LinearOperator ` ` corresponding to apply _ complement ( ) .
: return : a LinearOperator that calls apply _ complement ( ) .""" | # is projection the zero operator ? - - > complement is identity
if self . V . shape [ 1 ] == 0 :
N = self . V . shape [ 0 ]
return IdentityLinearOperator ( ( N , N ) )
return self . _get_operator ( self . apply_complement , self . apply_complement_adj ) |
def minimize_source ( source ) :
"""Remove comments and docstrings from Python ` source ` , preserving line
numbers and syntax of empty blocks .
: param str source :
The source to minimize .
: returns str :
The minimized source .""" | source = mitogen . core . to_text ( source )
tokens = tokenize . generate_tokens ( StringIO ( source ) . readline )
tokens = strip_comments ( tokens )
tokens = strip_docstrings ( tokens )
tokens = reindent ( tokens )
return tokenize . untokenize ( tokens ) |
def overlay_gateway_gw_type ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
overlay_gateway = ET . SubElement ( config , "overlay-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" )
name_key = ET . SubElement ( overlay_gateway , "name" )
name_key . text = kwargs . pop ( 'name' )
gw_type = ET . SubElement ( overlay_gateway , "gw-type" )
gw_type . text ... |
def degrees_of_freedom ( model ) :
"""Return the degrees of freedom , i . e . , number of " free variables " .
Parameters
model : cobra . Model
The metabolic model under investigation .
Notes
This specifically refers to the dimensionality of the ( right ) null space
of the stoichiometric matrix , as dim... | s_matrix , _ , _ = con_helpers . stoichiometry_matrix ( model . metabolites , model . reactions )
return s_matrix . shape [ 1 ] - matrix_rank ( model ) |
def p_propositional ( self , p ) :
"""propositional : propositional EQUIVALENCE propositional
| propositional IMPLIES propositional
| propositional OR propositional
| propositional AND propositional
| NOT propositional
| FALSE
| TRUE
| ATOM""" | if len ( p ) == 4 :
if p [ 2 ] == Symbols . EQUIVALENCE . value :
p [ 0 ] = PLEquivalence ( [ p [ 1 ] , p [ 3 ] ] )
elif p [ 2 ] == Symbols . IMPLIES . value :
p [ 0 ] = PLImplies ( [ p [ 1 ] , p [ 3 ] ] )
elif p [ 2 ] == Symbols . OR . value :
p [ 0 ] = PLOr ( [ p [ 1 ] , p [ 3 ] ] ... |
def extract_name ( self , data ) :
"""Extract man page name from web page .""" | name = re . search ( '<h1[^>]*>(.+?)</h1>' , data ) . group ( 1 )
name = re . sub ( r'<([^>]+)>' , r'' , name )
name = re . sub ( r'>' , r'>' , name )
name = re . sub ( r'<' , r'<' , name )
return name |
def run ( self , scheduler_schedule_id , ** kwargs ) :
"""Deactivates the schedule specified by the ID ` scheduler _ schedule _ id ` in
the scheduler service .
Arguments :
scheduler _ schedule _ id { str } - - The ID of the schedule to deactivate""" | log = self . get_logger ( ** kwargs )
self . scheduler . update_schedule ( scheduler_schedule_id , { "active" : False } )
log . info ( "Deactivated schedule %s in the scheduler service" , scheduler_schedule_id ) |
def _normalize_sort ( sort = None ) :
"""CONVERT SORT PARAMETERS TO A NORMAL FORM SO EASIER TO USE""" | if sort == None :
return FlatList . EMPTY
output = FlatList ( )
for s in listwrap ( sort ) :
if is_text ( s ) :
output . append ( { "value" : jx_expression ( s ) , "sort" : 1 } )
elif is_expression ( s ) :
output . append ( { "value" : s , "sort" : 1 } )
elif mo_math . is_integer ( s ) :... |
def get_env ( path , ignore_git_branch = False ) :
"""Determine environment name .""" | if 'DEPLOY_ENVIRONMENT' in os . environ :
return os . environ [ 'DEPLOY_ENVIRONMENT' ]
if ignore_git_branch :
LOGGER . info ( 'Skipping environment lookup from current git branch ' '("ignore_git_branch" is set to true in the runway ' 'config)' )
else : # These are not located with the top imports because they t... |
def _create_dicomdir_info ( self ) :
"""Function crates list of all files in dicom dir with all IDs""" | filelist = files_in_dir ( self . dirpath )
files = [ ]
metadataline = { }
for filepath in filelist :
head , teil = os . path . split ( filepath )
dcmdata = None
if os . path . isdir ( filepath ) :
logger . debug ( "Subdirectory found in series dir is ignored: " + str ( filepath ) )
continue
... |
def syllabify ( self , hierarchy ) :
"""> > > stanza = " Ein sat hon úti , \\ nþá er inn aldni kom \\ nyggjungr ása \\ nok í augu leit . \\ nHvers fregnið mik ? \\ nHví freistið mín ? \\ nAllt veit ek , Óðinn , \\ nhvar þú auga falt , \\ ní inum mæra \\ nMímisbrunni . \\ nDrekkr mjöð Mímir \\ nmorgun hv... | syllabifier = Syllabifier ( language = "old_norse" , break_geminants = True )
syllabifier . set_hierarchy ( hierarchy )
syllabified_text = [ ]
for short_line in self . short_lines :
assert isinstance ( short_line , ShortLine )
short_line . syllabify ( syllabifier )
syllabified_text . append ( short_line . s... |
def hoverEnterEvent ( self , event ) :
"""Processes when this hotspot is entered .
: param event | < QHoverEvent >
: return < bool > | processed""" | self . _hovered = True
if self . toolTip ( ) :
QToolTip . showText ( QCursor . pos ( ) , self . toolTip ( ) )
return True
return self . style ( ) == XNodeHotspot . Style . Icon |
def from_dict ( input_dict , data = None ) :
"""Instantiate an SparseGPClassification object using the information
in input _ dict ( built by the to _ dict method ) .
: param data : It is used to provide X and Y for the case when the model
was saved using save _ data = False in to _ dict method .
: type dat... | import GPy
m = GPy . core . model . Model . from_dict ( input_dict , data )
from copy import deepcopy
sparse_gp = deepcopy ( m )
return SparseGPClassification ( sparse_gp . X , sparse_gp . Y , sparse_gp . Z , sparse_gp . kern , sparse_gp . likelihood , sparse_gp . inference_method , sparse_gp . mean_function , name = '... |
def _read_para_hip_cipher ( self , code , cbit , clen , * , desc , length , version ) :
"""Read HIP HIP _ CIPHER parameter .
Structure of HIP HIP _ CIPHER parameter [ RFC 7401 ] :
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
| Type | Length |
| Cipher ID # 1 | Cipher ID # 2 |
... | if clen % 2 != 0 :
raise ProtocolError ( f'HIPv{version}: [Parano {code}] invalid format' )
_cpid = list ( )
for _ in range ( clen // 2 ) :
_cpid . append ( _CIPHER_ID . get ( self . _read_unpack ( 2 ) , 'Unassigned' ) )
hip_cipher = dict ( type = desc , critical = cbit , length = clen , id = _cpid , )
_plen = ... |
def saveAsTable ( self , name , format = None , mode = None , partitionBy = None , ** options ) :
"""Saves the content of the : class : ` DataFrame ` as the specified table .
In the case the table already exists , behavior of this function depends on the
save mode , specified by the ` mode ` function ( default ... | self . mode ( mode ) . options ( ** options )
if partitionBy is not None :
self . partitionBy ( partitionBy )
if format is not None :
self . format ( format )
self . _jwrite . saveAsTable ( name ) |
def load_freesurfer_geometry ( filename , to = 'mesh' , warn = False ) :
'''load _ freesurfer _ geometry ( filename ) yields the data stored at the freesurfer geometry file given
by filename . The optional argument ' to ' may be used to change the kind of data that is
returned .
The following are valid settin... | if not warn :
with warnings . catch_warnings ( ) :
warnings . filterwarnings ( 'ignore' , category = UserWarning , module = 'nibabel' )
( xs , fs , info ) = fsio . read_geometry ( filename , read_metadata = True )
else :
( xs , fs , info ) = fsio . read_geometry ( filename , read_metadata = True... |
def list_calculations ( db , job_type , user_name ) :
"""Yield a summary of past calculations .
: param db : a : class : ` openquake . server . dbapi . Db ` instance
: param job _ type : ' hazard ' or ' risk '
: param user _ name : an user name""" | jobs = db ( 'SELECT *, %s FROM job WHERE user_name=?x ' 'AND job_type=?x ORDER BY start_time' % JOB_TYPE , user_name , job_type )
out = [ ]
if len ( jobs ) == 0 :
out . append ( 'None' )
else :
out . append ( 'job_id | status | start_time | ' ' description' )
for job in jobs :
de... |
def plot_emg_graphical_durations ( max_time , min_time , avg_time , std_time ) :
"""Brief
This plotting function ensures a graphical representation of maximum , minimum and average time
durations of the muscular activation periods .
Description
Function intended to generate a single Bokeh figure graphically... | # List that store the figure handler
list_figures_1 = [ ]
color_1 = "#009EE3"
color_2 = "#00893E"
color_3 = "#E84D0E"
color_4 = "#CF0272"
# Plotting of Burst duration distribution
list_figures_1 . append ( figure ( x_axis_label = 'Time (s)' , ** opensignals_kwargs ( "figure" ) , x_range = [ 0 , max_time ] , y_range = [... |
def stream_logs ( container , timeout = 10.0 , ** logs_kwargs ) :
"""Stream logs from a Docker container within a timeout .
: param ~ docker . models . containers . Container container :
Container who ' s log lines to stream .
: param timeout :
Timeout value in seconds .
: param logs _ kwargs :
Addition... | stream = container . logs ( stream = True , ** logs_kwargs )
return stream_timeout ( stream , timeout , 'Timeout waiting for container logs.' ) |
def get_deep_focus ( self , startfrom = None ) :
"""return the bottom most focussed widget of the widget tree""" | if not startfrom :
startfrom = self . current_buffer
if 'get_focus' in dir ( startfrom ) :
focus = startfrom . get_focus ( )
if isinstance ( focus , tuple ) :
focus = focus [ 0 ]
if isinstance ( focus , urwid . Widget ) :
return self . get_deep_focus ( startfrom = focus )
return startfro... |
def get_sub_commands ( parser : argparse . ArgumentParser ) -> List [ str ] :
"""Get a list of sub - commands for an ArgumentParser""" | sub_cmds = [ ]
# Check if this is parser has sub - commands
if parser is not None and parser . _subparsers is not None : # Find the _ SubParsersAction for the sub - commands of this parser
for action in parser . _subparsers . _actions :
if isinstance ( action , argparse . _SubParsersAction ) :
f... |
def _get_root ( self ) :
"""get root user password .""" | _DEFAULT_USER_DETAILS = { "level" : 20 , "password" : "" , "sshkeys" : [ ] }
root = { }
root_table = junos_views . junos_root_table ( self . device )
root_table . get ( )
root_items = root_table . items ( )
for user_entry in root_items :
username = "root"
user_details = _DEFAULT_USER_DETAILS . copy ( )
user... |
def get_best ( self ) :
"""Finds the optimal number of features
: return : optimal number of features and ranking""" | svc = SVC ( kernel = "linear" )
rfecv = RFECV ( estimator = svc , step = 1 , cv = StratifiedKFold ( self . y_train , 2 ) , scoring = "log_loss" )
rfecv . fit ( self . x_train , self . y_train )
return rfecv . n_features_ , rfecv . ranking_ |
def free_function ( self , name = None , function = None , return_type = None , arg_types = None , header_dir = None , header_file = None , recursive = None ) :
"""Returns reference to free function declaration that matches
a defined criteria .""" | return ( self . _find_single ( scopedef . scopedef_t . _impl_matchers [ namespace_t . free_function ] , name = name , function = function , decl_type = self . _impl_decl_types [ namespace_t . free_function ] , return_type = return_type , arg_types = arg_types , header_dir = header_dir , header_file = header_file , recu... |
def _workdaycount ( self , date1 , date2 ) :
"""( PRIVATE ) Count work days between two dates , ignoring holidays .""" | assert date2 >= date1
date1wd = date1 . weekday ( )
date2wd = date2 . weekday ( )
if not self . weekdaymap [ date2wd ] . isworkday :
date2 += datetime . timedelta ( days = self . weekdaymap [ date2wd ] . offsetprev )
date2wd = self . weekdaymap [ date2wd ] . prevworkday
if date2 <= date1 :
return 0
nw , nd ... |
def scan_aggs ( search , source_aggs , inner_aggs = { } , size = 10 ) :
"""Helper function used to iterate over all possible bucket combinations of
` ` source _ aggs ` ` , returning results of ` ` inner _ aggs ` ` for each . Uses the
` ` composite ` ` aggregation under the hood to perform this .""" | def run_search ( ** kwargs ) :
s = search [ : 0 ]
s . aggs . bucket ( 'comp' , 'composite' , sources = source_aggs , size = size , ** kwargs )
for agg_name , agg in inner_aggs . items ( ) :
s . aggs [ 'comp' ] [ agg_name ] = agg
return s . execute ( )
response = run_search ( )
while response . a... |
def get_user_info ( remote ) :
"""Get user information from Globus .
See the docs here for v2 / oauth / userinfo :
https : / / docs . globus . org / api / auth / reference /""" | response = remote . get ( GLOBUS_USER_INFO_URL )
user_info = get_dict_from_response ( response )
response . data [ 'username' ] = response . data [ 'preferred_username' ]
if '@' in response . data [ 'username' ] :
user_info [ 'username' ] , _ = response . data [ 'username' ] . split ( '@' )
return user_info |
def list_solvers ( args = None ) :
"""Entry point for listing available solvers .""" | parser = argparse . ArgumentParser ( description = '''List LP solver available in PSAMM. This will produce a
list of all of the available LP solvers in prioritized
order. Addtional requirements can be imposed with the
arguments (e.g. integer=yes to se... |
def get_api_publisher ( self , social_user ) :
"""owner _ id - VK user or group
from _ group - 1 by group , 0 by user
message - text
attachments - comma separated links or VK resources ID ' s
and other https : / / vk . com / dev . php ? method = wall . post""" | def _post ( ** kwargs ) :
api = self . get_api ( social_user )
response = api . wall . post ( ** kwargs )
return response
return _post |
def get_language ( ) :
"""Returns an active language code that is guaranteed to be in
settings . SUPPORTED _ LANGUAGES .""" | lang = _get_language ( )
if not lang :
return get_fallback_language ( )
langs = [ l [ 0 ] for l in settings . SUPPORTED_LANGUAGES ]
if lang not in langs and "-" in lang :
lang = lang . split ( "-" ) [ 0 ]
if lang in langs :
return lang
return settings . DEFAULT_LANGUAGE |
def __get_fault ( self , replyroot ) :
"""Extract fault information from a SOAP reply .
Returns an I { unmarshalled } fault L { Object } or None in case the given
XML document does not contain a SOAP < Fault > element .
@ param replyroot : A SOAP reply message root XML element or None .
@ type replyroot : L... | envns = suds . bindings . binding . envns
soapenv = replyroot and replyroot . getChild ( "Envelope" , envns )
soapbody = soapenv and soapenv . getChild ( "Body" , envns )
fault = soapbody and soapbody . getChild ( "Fault" , envns )
return fault is not None and UmxBasic ( ) . process ( fault ) |
def get_supported_boot_mode ( self ) :
"""Get the system supported boot modes .
: return : any one of the following proliantutils . ilo . constants :
SUPPORTED _ BOOT _ MODE _ LEGACY _ BIOS _ ONLY ,
SUPPORTED _ BOOT _ MODE _ UEFI _ ONLY ,
SUPPORTED _ BOOT _ MODE _ LEGACY _ BIOS _ AND _ UEFI
: raises : Ilo... | sushy_system = self . _get_sushy_system ( PROLIANT_SYSTEM_ID )
try :
return SUPPORTED_BOOT_MODE_MAP . get ( sushy_system . supported_boot_mode )
except sushy . exceptions . SushyError as e :
msg = ( self . _ ( 'The Redfish controller failed to get the ' 'supported boot modes. Error: %s' ) % e )
LOG . debug ... |
def _get_normalized_columns ( cls , list_ ) :
""": param list _ : list of dict
: return : list of string of every key in all the dictionaries""" | ret = [ ]
for row in list_ :
if len ( row . keys ( ) ) > len ( ret ) :
ret = cls . _ordered_keys ( row )
for row in list_ :
for key in row . keys ( ) :
if key not in ret :
ret . append ( key )
if not isinstance ( row , OrderedDict ) :
ret . sort ( )
return... |
def _unscramble_regressor_columns ( parent_data , data ) :
"""Reorder the columns of a confound matrix such that the columns are in
the same order as the input data with any expansion columns inserted
immediately after the originals .""" | matches = [ '_power[0-9]+' , '_derivative[0-9]+' ]
var = OrderedDict ( ( c , deque ( ) ) for c in parent_data . columns )
for c in data . columns :
col = c
for m in matches :
col = re . sub ( m , '' , col )
if col == c :
var [ col ] . appendleft ( c )
else :
var [ col ] . append ... |
def extant_item ( arg , arg_type ) :
"""Determine if parser argument is an existing file or directory .
This technique comes from http : / / stackoverflow . com / a / 11541450/95592
and from http : / / stackoverflow . com / a / 11541495/95592
Args :
arg : parser argument containing filename to be checked
... | if arg_type == "file" :
if not os . path . isfile ( arg ) :
raise argparse . ArgumentError ( None , "The file {arg} does not exist." . format ( arg = arg ) )
else : # File exists so return the filename
return arg
elif arg_type == "directory" :
if not os . path . isdir ( arg ) :
raise... |
def namedb_select_count_rows ( cur , query , args , count_column = 'COUNT(*)' ) :
"""Execute a SELECT COUNT ( * ) . . . query
and return the number of rows .""" | count_rows = namedb_query_execute ( cur , query , args )
count = 0
for r in count_rows :
count = r [ count_column ]
break
return count |
def bmgs ( ctx , event ) :
"""[ bookie ] List betting market groups for an event
: param str event : Event id""" | eg = Event ( event , peerplays_instance = ctx . peerplays )
click . echo ( pretty_print ( eg . bettingmarketgroups , ctx = ctx ) ) |
def runner ( name , arg = None , kwarg = None , full_return = False , saltenv = 'base' , jid = None , asynchronous = False , ** kwargs ) :
'''Execute a runner function . This function must be run on the master ,
either by targeting a minion running on a master or by using
salt - call on a master .
. . version... | if arg is None :
arg = [ ]
if kwarg is None :
kwarg = { }
jid = kwargs . pop ( '__orchestration_jid__' , jid )
saltenv = kwargs . pop ( '__env__' , saltenv )
kwargs = salt . utils . args . clean_kwargs ( ** kwargs )
if kwargs :
kwarg . update ( kwargs )
if 'master_job_cache' not in __opts__ :
master_con... |
def _build ( self , inputs ) :
"""Connects the LayerNorm module into the graph .
Args :
inputs : a Tensor of dimensionality > = 2.
Returns :
normalized : layer normalized outputs with same shape as inputs .
Raises :
base . NotSupportedError : If ` inputs ` has less than 2 dimensions .""" | if self . _axis is None :
axis = list ( range ( 1 , inputs . shape . ndims ) )
else :
axis = self . _axis
original_dtype = inputs . dtype
if original_dtype in [ tf . float16 , tf . bfloat16 ] :
inputs = tf . cast ( inputs , tf . float32 )
if inputs . get_shape ( ) . ndims < 2 :
raise base . NotSupported... |
def get_nets_other ( self , response ) :
"""The function for parsing network blocks from generic whois data .
Args :
response ( : obj : ` str ` ) : The response from the whois / rwhois server .
Returns :
list of dict : Mapping of networks with start and end positions .
' cidr ' ( str ) - The network routi... | nets = [ ]
# Iterate through all of the networks found , storing the CIDR value
# and the start and end positions .
for match in re . finditer ( r'^(inetnum|inet6num|route):[^\S\n]+((.+?)[^\S\n]-[^\S\n](.+)|' '.+)$' , response , re . MULTILINE ) :
try :
net = copy . deepcopy ( BASE_NET )
net_range =... |
def cmd ( send , msg , args ) :
"""Nukes somebody .
Syntax : { command } < target >""" | c , nick = args [ 'handler' ] . connection , args [ 'nick' ]
channel = args [ 'target' ] if args [ 'target' ] != 'private' else args [ 'config' ] [ 'core' ] [ 'channel' ]
if not msg :
send ( "Nuke who?" )
return
with args [ 'handler' ] . data_lock :
users = args [ 'handler' ] . channels [ channel ] . users ... |
def queueStream ( self , rdds , oneAtATime = True , default = None ) :
"""Create stream iterable over RDDs .
: param rdds : Iterable over RDDs or lists .
: param oneAtATime : Process one at a time or all .
: param default : If no more RDDs in ` ` rdds ` ` , return this . Can be None .
: rtype : DStream
Ex... | deserializer = QueueStreamDeserializer ( self . _context )
if default is not None :
default = deserializer ( default )
if Queue is False :
log . error ( 'Run "pip install tornado" to install tornado.' )
q = Queue ( )
for i in rdds :
q . put ( i )
qstream = QueueStream ( q , oneAtATime , default )
return DSt... |
def md5 ( self ) :
"""Return md5 from meta , or compute it if absent .""" | md5 = self . meta . get ( "md5" )
if md5 is None :
md5 = str ( hashlib . md5 ( self . value ) . hexdigest ( ) )
return md5 |
import re
def validate_decimal ( decimal_str ) :
"""Uses regular expressions to check whether a given number is a decimal with two decimal places .
Examples :
> > > validate _ decimal ( ' 123.11 ' )
True
> > > validate _ decimal ( ' 0.21 ' )
True
> > > validate _ decimal ( ' 123.1214 ' )
False
Args ... | pattern = re . compile ( '^[0-9]+(\.[0-9]{1,2})?$' )
match_result = pattern . search ( decimal_str )
return bool ( match_result ) |
def get_container_stop_kwargs ( self , action , container_name , kwargs = None ) :
"""Generates keyword arguments for the Docker client to stop a container .
: param action : Action configuration .
: type action : ActionConfig
: param container _ name : Container name or id .
: type container _ name : unico... | c_kwargs = dict ( container = container_name , )
stop_timeout = action . config . stop_timeout
if stop_timeout is NotSet :
timeout = action . client_config . get ( 'stop_timeout' )
if timeout is not None :
c_kwargs [ 'timeout' ] = timeout
elif stop_timeout is not None :
c_kwargs [ 'timeout' ] = stop... |
def unshift ( self , chunk ) :
"""Pushes a chunk of data back into the internal buffer . This is useful
in certain situations where a stream is being consumed by code that
needs to " un - consume " some amount of data that it has optimistically
pulled out of the source , so that the data can be passed on to s... | if chunk :
self . _pos -= len ( chunk )
self . _unconsumed . append ( chunk ) |
def detectWebOSTablet ( self ) :
"""Return detection of an HP WebOS tablet
Detects if the current browser is on an HP tablet running WebOS .""" | return UAgentInfo . deviceWebOShp in self . __userAgent and UAgentInfo . deviceTablet in self . __userAgent |
def _rename_node ( self , name , new_name ) :
"""Rename node private method .
No argument validation and usage of getter / setter private methods is
used for speed""" | # Update parent
if not self . is_root ( name ) :
parent = self . _db [ name ] [ "parent" ]
self . _db [ parent ] [ "children" ] . remove ( name )
self . _db [ parent ] [ "children" ] = sorted ( self . _db [ parent ] [ "children" ] + [ new_name ] )
# Update children
iobj = self . _get_subtree ( name ) if nam... |
def static_url ( context , static_file_path ) :
"""Filter for generating urls for static files .
NOTE : you ' ll need
to set app [ ' static _ root _ url ' ] to be used as the root for the urls returned .
Usage : { { static ( ' styles . css ' ) } } might become
" / static / styles . css " or " http : / / myc... | app = context [ 'app' ]
try :
static_url = app [ 'static_root_url' ]
except KeyError :
raise RuntimeError ( "app does not define a static root url " "'static_root_url', you need to set the url root " "with app['static_root_url'] = '<static root>'." ) from None
return '{}/{}' . format ( static_url . rstrip ( '/'... |
def get_default_mimetype ( self ) :
"""Returns the default mimetype""" | mimetype = self . default_mimetype
if mimetype is None : # class inherits from module default
mimetype = DEFAULT_MIMETYPE
if mimetype is None : # module is set to None ?
mimetype = 'application/rdf+xml'
return mimetype |
def legion_create_handler ( obj ) :
"""Signal handlers can ' t be standard class methods because the signal
callback does not include the object reference ( self ) . To work
around this we use a closure the carry the object reference .""" | def _handler ( sig , frame ) :
obj . _sig_handler ( sig , frame )
if '_sig_handler' not in dir ( obj ) : # pragma : no cover
raise Excecption ( "Object instance has no _sig_handler method" )
return _handler |
def download ( self , force = False , silent = False ) :
"""Download from URL .""" | def _download ( ) :
if self . url . startswith ( "http" ) :
self . _download_http ( silent = silent )
elif self . url . startswith ( "ftp" ) :
self . _download_ftp ( silent = silent )
else :
raise ValueError ( "Invalid URL %s" % self . url )
logger . debug ( "Moving %s to %s" % (... |
def get_form ( self , form_class ) :
"""Returns an instance of the form to be used in this view .""" | if not hasattr ( self , '_form' ) :
kwargs = self . get_form_kwargs ( )
self . _form = form_class ( instance = self . object , ** kwargs )
return self . _form |
def get_openshift_base_uri ( self ) :
"""https : / / < host > [ : < port > ] /
: return : str""" | deprecated_key = "openshift_uri"
key = "openshift_url"
val = self . _get_value ( deprecated_key , self . conf_section , deprecated_key )
if val is not None :
warnings . warn ( "%r is deprecated, use %r instead" % ( deprecated_key , key ) )
return val
return self . _get_value ( key , self . conf_section , key ) |
def _route ( self , mapper ) :
"""Set up the route ( s ) corresponding to the limit . This controls
which limits are checked against the request .
: param mapper : The routes . Mapper object to add the route to .""" | # Build up the keyword arguments to feed to connect ( )
kwargs = dict ( conditions = dict ( function = self . _filter ) )
# Restrict the verbs
if self . verbs :
kwargs [ 'conditions' ] [ 'method' ] = self . verbs
# Add requirements , if provided
if self . requirements :
kwargs [ 'requirements' ] = self . requir... |
def collapse_substrings ( variant_sequences ) :
"""Combine shorter sequences which are fully contained in longer sequences .
Parameters
variant _ sequences : list
List of VariantSequence objects
Returns a ( potentially shorter ) list without any contained subsequences .""" | if len ( variant_sequences ) <= 1 : # if we don ' t have at least two VariantSequences then just
# return your input
return variant_sequences
# dictionary mapping VariantSequence objects to lists of reads
# they absorb from substring VariantSequences
extra_reads_from_substrings = defaultdict ( set )
result_list = [... |
def account_data ( self , address , key ) :
"""This endpoint represents a single data associated with a given
account .
` GET / accounts / { account } / data / { key }
< https : / / www . stellar . org / developers / horizon / reference / endpoints / data - for - account . html > ` _
: param str address : T... | endpoint = '/accounts/{account_id}/data/{data_key}' . format ( account_id = address , data_key = key )
return self . query ( endpoint ) |
def _refresh_grains_watcher ( self , refresh_interval_in_minutes ) :
'''Create a loop that will fire a pillar refresh to inform a master about a change in the grains of this minion
: param refresh _ interval _ in _ minutes :
: return : None''' | if '__update_grains' not in self . opts . get ( 'schedule' , { } ) :
if 'schedule' not in self . opts :
self . opts [ 'schedule' ] = { }
self . opts [ 'schedule' ] . update ( { '__update_grains' : { 'function' : 'event.fire' , 'args' : [ { } , 'grains_refresh' ] , 'minutes' : refresh_interval_in_minutes... |
def parse_var ( var ) :
"""Returns a tuple consisting of a string and a tag , or None , if none is
specified .""" | bits = var . split ( "<" , 1 )
if len ( bits ) < 2 :
tag = None
else :
tag = bits [ 1 ]
return ucn_to_unicode ( bits [ 0 ] ) , tag |
def delete_session_entity_type ( self , name , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None ) :
"""Deletes the specified session entity type .
Example :
> > > import dialogflow _ v2
> > > client = dialogflow _ v2 . Sessio... | # Wrap the transport method to add retry and timeout logic .
if 'delete_session_entity_type' not in self . _inner_api_calls :
self . _inner_api_calls [ 'delete_session_entity_type' ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . delete_session_entity_type , default_retry = self . _metho... |
def duration ( self ) :
"""Return the duration in seconds .""" | with self . container . open_if_needed ( mode = 'r' ) as cnt :
samples , sr = cnt . get ( self . key )
return samples . shape [ 0 ] / sr |
def whitelist ( ctx , whitelist_account , account ) :
"""Add an account to a whitelist""" | account = Account ( account , blockchain_instance = ctx . blockchain )
print_tx ( account . whitelist ( whitelist_account ) ) |
def makedirs ( path ) :
"""Equivalent to mkdir - p .
Args :
path ( str ) : the path to mkdir - p
Raises :
ScriptWorkerException : if path exists already and the realpath is not a dir .""" | if path :
if not os . path . exists ( path ) :
log . debug ( "makedirs({})" . format ( path ) )
os . makedirs ( path )
else :
realpath = os . path . realpath ( path )
if not os . path . isdir ( realpath ) :
raise ScriptWorkerException ( "makedirs: {} already exists an... |
def build_path ( entities , path_patterns , strict = False ) :
"""Constructs a path given a set of entities and a list of potential
filename patterns to use .
Args :
entities ( dict ) : A dictionary mapping entity names to entity values .
path _ patterns ( str , list ) : One or more filename patterns to wri... | path_patterns = listify ( path_patterns )
# Loop over available patherns , return first one that matches all
for pattern in path_patterns : # If strict , all entities must be contained in the pattern
if strict :
defined = re . findall ( r'\{(.*?)(?:<[^>]+>)?\}' , pattern )
if set ( entities . keys (... |
def upgrade_available ( pkg , bin_env = None , user = None , cwd = None ) :
'''. . versionadded : : 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example :
. . code - block : : bash
salt ' * ' pip . upgrade _ available < package name >''' | return pkg in list_upgrades ( bin_env = bin_env , user = user , cwd = cwd ) |
def _check_devices ( self ) :
"Enumerate OpenVR tracked devices and check whether any need to be initialized" | for i in range ( 1 , len ( self . poses ) ) :
pose = self . poses [ i ]
if not pose . bDeviceIsConnected :
continue
if not pose . bPoseIsValid :
continue
if self . show_controllers_only :
device_class = openvr . VRSystem ( ) . getTrackedDeviceClass ( i )
if not device_cla... |
def describe_numeric_1d ( series , ** kwargs ) :
"""Compute summary statistics of a numerical ( ` TYPE _ NUM ` ) variable ( a Series ) .
Also create histograms ( mini an full ) of its distribution .
Parameters
series : Series
The variable to describe .
Returns
Series
The description of the variable as... | # Format a number as a percentage . For example 0.25 will be turned to 25 % .
_percentile_format = "{:.0%}"
stats = dict ( )
stats [ 'type' ] = base . TYPE_NUM
stats [ 'mean' ] = series . mean ( )
stats [ 'std' ] = series . std ( )
stats [ 'variance' ] = series . var ( )
stats [ 'min' ] = series . min ( )
stats [ 'max'... |
async def async_set_summary ( program ) :
'''Set a program ' s summary''' | import aiohttp
async with aiohttp . ClientSession ( ) as session :
resp = await session . get ( program . get ( 'url' ) )
text = await resp . text ( )
summary = extract_program_summary ( text )
program [ 'summary' ] = summary
return program |
def get_threads_where_participant_is_active ( self , participant_id ) :
"""Gets all the threads in which the current participant is involved . The method excludes threads where the participant has left .""" | participations = Participation . objects . filter ( participant__id = participant_id ) . exclude ( date_left__lte = now ( ) ) . distinct ( ) . select_related ( 'thread' )
return Thread . objects . filter ( id__in = [ p . thread . id for p in participations ] ) . distinct ( ) |
def reset ( self ) :
'''Reset the histogram to a pristine state''' | for index in range ( self . counts_len ) :
self . counts [ index ] = 0
self . total_count = 0
self . min_value = sys . maxsize
self . max_value = 0
self . start_time_stamp_msec = sys . maxsize
self . end_time_stamp_msec = 0 |
def add_number_parameters ( self , number ) :
"""Add given number parameters to the internal list .
Args :
number ( list of int or list of float ) : A number or list of numbers to add to the parameters .""" | if isinstance ( number , list ) :
for x in number :
self . add_number_parameters ( x )
return
self . _parameters . append ( "{ \"value\": " + str ( number ) + " }" ) |
def packages ( state , host , packages = None , present = True , latest = False , update = False , cache_time = None , upgrade = False , force = False , no_recommends = False , allow_downgrades = False , ) :
'''Install / remove / update packages & update apt .
+ packages : list of packages to ensure
+ present :... | if update :
yield _update ( state , host , cache_time = cache_time )
if upgrade :
yield _upgrade ( state , host )
install_command = 'install'
if no_recommends is True :
install_command += ' --no-install-recommends'
if allow_downgrades :
install_command += ' --allow-downgrades'
# Compare / ensure package... |
def ReplaceItem ( self , document_link , new_document , options = None ) :
"""Replaces a document and returns it .
: param str document _ link :
The link to the document .
: param dict new _ document :
: param dict options :
The request options for the request .
: return :
The new Document .
: rtype... | CosmosClient . __ValidateResource ( new_document )
path = base . GetPathFromLink ( document_link )
document_id = base . GetResourceIdOrFullNameFromLink ( document_link )
# Python ' s default arguments are evaluated once when the function is defined , not each time the function is called ( like it is in say , Ruby ) .
#... |
def request ( self , action ) :
"""Request an action to be performed , in case one .""" | ev = threading . Event ( )
first = False
with self . __lock :
if len ( self . __events ) == 0 :
first = True
self . __events . append ( ev )
if first :
action ( )
return ev |
def is_vertex_cover ( G , vertex_cover ) :
"""Determines whether the given set of vertices is a vertex cover of graph G .
A vertex cover is a set of vertices such that each edge of the graph
is incident with at least one vertex in the set .
Parameters
G : NetworkX graph
The graph on which to check the ver... | cover = set ( vertex_cover )
return all ( u in cover or v in cover for u , v in G . edges ) |
def dict_to_hdf5 ( dic , endpoint ) :
"""Dump a dict to an HDF5 file .""" | filename = gen_filename ( endpoint )
with h5py . File ( filename , 'w' ) as handler :
walk_dict_to_hdf5 ( dic , handler )
print ( 'dumped to' , filename ) |
def is_valid_input_meshgrid ( x , ndim ) :
"""Test if ` ` x ` ` is a ` meshgrid ` sequence for points in R ^ d .""" | # This case is triggered in FunctionSpaceElement . _ _ call _ _ if the
# domain does not have an ' ndim ' attribute . We return False and
# continue .
if ndim is None :
return False
if not isinstance ( x , tuple ) :
return False
if ndim > 1 :
try :
np . broadcast ( * x )
except ( ValueError , Ty... |
def save ( self , filename , compressed = True ) :
"""Save a tensor to disk .""" | # check for data
if not self . has_data :
return False
# read ext and save accordingly
_ , file_ext = os . path . splitext ( filename )
if compressed :
if file_ext != COMPRESSED_TENSOR_EXT :
raise ValueError ( 'Can only save compressed tensor with %s extension' % ( COMPRESSED_TENSOR_EXT ) )
np . sav... |
def dump ( args ) :
"""% prog dump fastbfile
Export ALLPATHS fastb file to fastq file . Use - - dir to indicate a previously
run allpaths folder .""" | p = OptionParser ( dump . __doc__ )
p . add_option ( "--dir" , help = "Working directory [default: %default]" )
p . add_option ( "--nosim" , default = False , action = "store_true" , help = "Do not simulate qual to 50 [default: %default]" )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( n... |
def is_deletion ( self ) :
"""Does this variant represent the deletion of nucleotides from the
reference genome ?""" | # A deletion would appear in a VCF like CT > C , so that the
# reference allele starts with the alternate nucleotides .
# This is true even in the normalized case , where the alternate
# nucleotides are an empty string .
return ( len ( self . ref ) > len ( self . alt ) ) and self . ref . startswith ( self . alt ) |
def cbpdn_setdict ( ) :
"""Set the dictionary for the cbpdn stage . There are no parameters
or return values because all inputs and outputs are from and to
global variables .""" | global mp_DSf
# Set working dictionary for cbpdn step and compute DFT of dictionary
# D and of D ^ T S
mp_Df [ : ] = sl . rfftn ( mp_D_Y , mp_cri . Nv , mp_cri . axisN )
if mp_cri . Cd == 1 :
mp_DSf [ : ] = np . conj ( mp_Df ) * mp_Sf
else :
mp_DSf [ : ] = sl . inner ( np . conj ( mp_Df [ np . newaxis , ... ] )... |
def output_tray_status ( self ) -> Dict [ int , Dict [ str , str ] ] :
"""Return the state of all output trays .""" | tray_status = { }
try :
tray_stat = self . data . get ( 'outputTray' , [ ] )
for i , stat in enumerate ( tray_stat ) :
tray_status [ i ] = { 'name' : stat [ 0 ] , 'capacity' : stat [ 1 ] , 'status' : stat [ 2 ] , }
except ( KeyError , AttributeError ) :
tray_status = { }
return tray_status |
def reset ( self ) :
"""Factory reset all of Vent ' s user data , containers , and images""" | status = ( True , None )
error_message = ''
# remove containers
try :
c_list = set ( self . d_client . containers . list ( filters = { 'label' : 'vent' } , all = True ) )
for c in c_list :
c . remove ( force = True )
except Exception as e : # pragma : no cover
error_message += 'Error removing Vent c... |
def cleanup ( self ) :
'''Terminate this client if it has not already terminated .''' | if self . state == ClientState . WAITING_FOR_RESULT : # There is an ongoing call to execute ( )
# Not sure what to do here
logger . warn ( 'cleanup() called while state is WAITING_FOR_RESULT: ignoring' )
elif self . state == ClientState . TERMINATING : # terminate ( ) has been called but we have not recieved SIGCHL... |
def _load_data ( self ) :
"""Loads the data into this instance""" | url = self . parent . build_url ( self . parent . _endpoints . get ( 'format' ) )
response = self . parent . session . get ( url )
if not response :
return False
data = response . json ( )
self . _bold = data . get ( 'bold' , False )
self . _color = data . get ( 'color' , '#000000' )
# default black
self . _italic ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.