signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def p_line_label_asm ( p ) :
"""line : LABEL asms NEWLINE""" | p [ 0 ] = p [ 2 ]
__DEBUG__ ( "Declaring '%s%s' (value %04Xh) in %i" % ( NAMESPACE , p [ 1 ] , MEMORY . org , p . lineno ( 1 ) ) )
MEMORY . declare_label ( p [ 1 ] , p . lineno ( 1 ) ) |
def _updateRtiInfo ( self ) :
"""Updates the _ rtiInfo property when a new RTI is set or the comboboxes value change .""" | logger . debug ( "Updating self._rtiInfo" )
# Info about the dependent dimension
rti = self . rti
if rti is None :
info = { 'slices' : '' , 'name' : '' , 'path' : '' , 'file-name' : '' , 'dir-name' : '' , 'base-name' : '' , 'unit' : '' , 'raw-unit' : '' }
else :
dirName , baseName = os . path . split ( rti . fi... |
def password ( self , value = None ) :
"""Return or set the password
: param string value : the new password to use
: returns : string or new : class : ` URL ` instance""" | if value is not None :
return URL . _mutate ( self , password = value )
return unicode_unquote ( self . _tuple . password ) |
def _save ( self , objects , old_pos , new_pos ) :
"""WARNING : Intensive giggery - pokery zone .""" | to_shift = objects . exclude ( pk = self . pk ) if self . pk else objects
# If not set , insert at end .
if self . sort_order is None :
self . _move_to_end ( objects )
# New insert .
elif not self . pk and not old_pos : # Increment ` sort _ order ` on objects with :
# sort _ order > new _ pos .
to_shift = to_sh... |
def collaborators ( self ) :
"""| Comment : Who are currently CC ' ed on the ticket""" | if self . api and self . collaborator_ids :
return self . api . _get_users ( self . collaborator_ids ) |
def gatk ( args ) :
"""% prog gatk bamfile reference . fasta
Call SNPs based on GATK best practices .""" | p = OptionParser ( gatk . __doc__ )
p . add_option ( "--indelrealign" , default = False , action = "store_true" , help = "Perform indel realignment" )
p . set_home ( "gatk" )
p . set_home ( "picard" )
p . set_phred ( )
p . set_cpus ( cpus = 24 )
opts , args = p . parse_args ( args )
if len ( args ) != 2 :
sys . exi... |
def overlay_gateway_attach_rbridge_id_rb_add ( 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' )
attach = ET . SubElement ( overlay_gateway , "attach" )
rbridge_id = ET .... |
def call ( self , iface_name , func_name , params ) :
"""Makes a single RPC request and returns the result .
: Parameters :
iface _ name
Interface name to call
func _ name
Function to call on the interface
params
List of parameters to pass to the function""" | req = self . to_request ( iface_name , func_name , params )
if self . log . isEnabledFor ( logging . DEBUG ) :
self . log . debug ( "Request: %s" % str ( req ) )
resp = self . transport . request ( req )
if self . log . isEnabledFor ( logging . DEBUG ) :
self . log . debug ( "Response: %s" % str ( resp ) )
retu... |
def iperf_version ( self ) :
"""Returns the version of the libiperf library
: rtype : string""" | # TODO : Is there a better way to get the const char than allocating 30?
VersionType = c_char * 30
return VersionType . in_dll ( self . lib , "version" ) . value . decode ( 'utf-8' ) |
def from_auto_dict ( values , source = 'auto' ) :
'''Pass an entire dictionary to from _ auto
. . note : :
The key will be passed as the name''' | for name , value in values . items ( ) :
values [ name ] = from_auto ( name , value , source )
return values |
def HSL_to_RGB ( cobj , target_rgb , * args , ** kwargs ) :
"""HSL to RGB conversion .""" | H = cobj . hsl_h
S = cobj . hsl_s
L = cobj . hsl_l
if L < 0.5 :
var_q = L * ( 1.0 + S )
else :
var_q = L + S - ( L * S )
var_p = 2.0 * L - var_q
# H normalized to range [ 0,1]
h_sub_k = ( H / 360.0 )
t_sub_R = h_sub_k + ( 1.0 / 3.0 )
t_sub_G = h_sub_k
t_sub_B = h_sub_k - ( 1.0 / 3.0 )
rgb_r = __Calc_HSL_to_RGB_... |
def show ( self ) :
"""Show state .""" | msg = ''
if self . _process :
msg += 'server pid: {}\n' . format ( self . _process . pid )
msg += 'server poll: {}\n' . format ( self . _process . poll ( ) )
msg += 'server running: {}\n' . format ( self . running ( ) )
msg += 'server port: {}\n' . format ( self . _port )
msg += 'server root url: {}\n' . format... |
def metadata ( self , delete = False ) :
"""Gets the metadata .""" | if delete :
return self . _session . delete ( self . __v1 ( ) + "/metadata" ) . json ( )
else :
return self . _session . get ( self . __v1 ( ) + "/metadata" ) . json ( ) |
def set_max_order_count ( self , max_count , on_error = 'fail' ) :
"""Set a limit on the number of orders that can be placed in a single
day .
Parameters
max _ count : int
The maximum number of orders that can be placed on any single day .""" | control = MaxOrderCount ( on_error , max_count )
self . register_trading_control ( control ) |
def delete_external_link ( self , id , ** kwargs ) : # noqa : E501
"""Delete a specific external link # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . delete _ external _ link ( id... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . delete_external_link_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . delete_external_link_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def convert ( word ) :
"""This method converts given ` word ` to UTF - 8 encoding and ` bytes ` type for the
SWIG wrapper .""" | if six . PY2 :
if isinstance ( word , unicode ) :
return word . encode ( 'utf-8' )
else :
return word . decode ( 'utf-8' ) . encode ( 'utf-8' )
# make sure it is real utf8 , otherwise complain
else : # = = > Py3
if isinstance ( word , bytes ) :
return word . decode ( 'utf-8' ... |
def get_version ( ) :
"""Reads the version ( MAJOR . MINOR ) from this module .""" | _release = get_release ( )
split_version = _release . split ( "." )
if len ( split_version ) == 3 :
return "." . join ( split_version [ : 2 ] )
return _release |
def _unescape_str ( value ) :
"""Unescape a TS3 compatible string into a normal string
@ param value : Value
@ type value : string / int""" | if isinstance ( value , int ) :
return "%d" % value
value = value . replace ( r"\\" , "\\" )
for i , j in ts3_escape . items ( ) :
value = value . replace ( j , i )
return value |
def res_belongs_to_bs ( self , res , cutoff , ligcentroid ) :
"""Check for each residue if its centroid is within a certain distance to the ligand centroid .
Additionally checks if a residue belongs to a chain restricted by the user ( e . g . by defining a peptide chain )""" | rescentroid = centroid ( [ ( atm . x ( ) , atm . y ( ) , atm . z ( ) ) for atm in pybel . ob . OBResidueAtomIter ( res ) ] )
# Check geometry
near_enough = True if euclidean3d ( rescentroid , ligcentroid ) < cutoff else False
# Check chain membership
restricted_chain = True if res . GetChain ( ) in config . PEPTIDES el... |
def subnet_group_exists ( name , tags = None , region = None , key = None , keyid = None , profile = None ) :
'''Check to see if an ElastiCache subnet group exists .
CLI example : :
salt myminion boto _ elasticache . subnet _ group _ exists my - param - group region = us - east - 1''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
if not conn :
return False
try :
ec = conn . describe_cache_subnet_groups ( cache_subnet_group_name = name )
if not ec :
msg = ( 'ElastiCache subnet group does not exist in region {0}' . format ( region ) )
... |
def _parse_args ( self , args ) :
"""Parses any supplied command - line args and provides help text .""" | parser = ArgumentParser ( description = "Runs pylint recursively on a directory" )
parser . add_argument ( "-v" , "--verbose" , dest = "verbose" , action = "store_true" , default = False , help = "Verbose mode (report which files were found for testing)." , )
parser . add_argument ( "--rcfile" , dest = "rcfile" , actio... |
def EndOfEventAction ( self , event ) :
"""At the end of an event , grab sensitive detector hits then run processor loop""" | self . log . debug ( 'Processesing simulated event %d' , event . GetEventID ( ) )
docs = self . sd . getDocs ( )
self . sd . clearDocs ( )
for processor in self . processors :
docs = processor . process ( docs )
if not docs :
self . log . warning ( '%s did not return documents in process()!' , processor... |
def getcallparams ( self , target , conf = None , args = None , kwargs = None , exec_ctx = None ) :
"""Get target call parameters .
: param list args : target call arguments .
: param dict kwargs : target call keywords .
: return : args , kwargs
: rtype : tuple""" | if args is None :
args = [ ]
if kwargs is None :
kwargs = { }
if conf is None :
conf = self . conf
params = conf . params
try :
argspec = getargspec ( target )
except TypeError as tex :
argspec = None
callargs = { }
else :
try :
callargs = getcallargs ( target , * args , ** kwargs )
... |
def get_plugin_spec ( self , name ) :
"""Get the specification attributes for plugin with name ` name ` .""" | l_name = name . lower ( )
for spec in self . plugins :
name = spec . get ( 'name' , spec . get ( 'klass' , spec . module ) )
if name . lower ( ) == l_name :
return spec
raise KeyError ( name ) |
def order_categories ( unordered_cats ) :
'''If categories are strings , then simple ordering is fine .
If categories are values then I ' ll need to order based on their values .
The final ordering is given as the original categories ( including titles ) in a
ordered list .''' | no_titles = remove_titles ( unordered_cats )
all_are_numbers = check_all_numbers ( no_titles )
if all_are_numbers :
ordered_cats = order_cats_based_on_values ( unordered_cats , no_titles )
else :
ordered_cats = sorted ( unordered_cats )
return ordered_cats |
def create_toc ( doctree , depth = 9223372036854775807 , writer_name = 'html' , exclude_first_section = True , href_prefix = None , id_prefix = 'toc-ref-' ) :
"""Create a Table of Contents ( TOC ) from the given doctree
Returns : ( docutils . core . Publisher instance , output string )
` writer _ name ` : repre... | # copy the doctree since Content alters some settings on the original
# document
doctree = doctree . deepcopy ( )
# we want to be able to customize ids to avoid clashes if needed
doctree . settings . auto_id_prefix = id_prefix
details = { 'depth' : depth , }
# Assuming the document has one primary heading and then sub ... |
def _run_grid_multithread ( self , func , iterables ) :
'''running case with mutil process to support selenium grid - mode ( multiple web ) and appium grid - mode ( multiple devices ) .
@ param func : function object
@ param iterables : iterable objects''' | f = lambda x : threading . Thread ( target = func , args = ( x , ) )
threads = map ( f , iterables )
for thread in threads :
thread . setDaemon ( True )
thread . start ( )
thread . join ( ) |
def send_and_match_output ( self , send , matches , shutit_pexpect_child = None , retry = 3 , strip = True , note = None , echo = None , loglevel = logging . DEBUG ) :
"""Returns true if the output of the command matches any of the strings in
the matches list of regexp strings . Handles matching on a per - line b... | shutit_global . shutit_global_object . yield_to_draw ( )
shutit_pexpect_child = shutit_pexpect_child or self . get_current_shutit_pexpect_session ( ) . pexpect_child
shutit_pexpect_session = self . get_shutit_pexpect_session_from_child ( shutit_pexpect_child )
return shutit_pexpect_session . send_and_match_output ( sen... |
def observe_root_state_assignments ( self , model , prop_name , info ) :
"""The method relieves observed root _ state models and observes newly assigned root _ state models .""" | if info [ 'old' ] :
self . relieve_model ( info [ 'old' ] )
if info [ 'new' ] :
self . observe_model ( info [ 'new' ] )
self . logger . info ( "Exchange observed old root_state model with newly assigned one. sm_id: {}" "" . format ( info [ 'new' ] . state . parent . state_machine_id ) ) |
def import_symbol ( name = None , path = None , typename = None , base_path = None ) :
"""Import a module , or a typename within a module from its name .
Arguments :
name : An absolute or relative ( starts with a . ) Python path
path : If name is relative , path is prepended to it .
base _ path : ( DEPRECAT... | _ , symbol = _import ( name or typename , path or base_path )
return symbol |
def inverted ( values , input_min = 0 , input_max = 1 ) :
"""Returns the inversion of the supplied values ( * input _ min * becomes
* input _ max * , * input _ max * becomes * input _ min * , ` input _ min + 0.1 ` becomes
` input _ max - 0.1 ` , etc . ) . All items in * values * are assumed to be between
* in... | values = _normalize ( values )
if input_min >= input_max :
raise ValueError ( 'input_min must be smaller than input_max' )
for v in values :
yield input_min + input_max - v |
def optimum_periodic_value ( A : int , B : int , N : int ) -> int :
"""A Python function to calculate the maximum possible value of a given periodic function .
Args :
A , B , N : Integer parameters of the function .
Returns :
The maximum integer value that the function can reach .
Examples :
> > > optim... | x = min ( B - 1 , N )
return A * x // B |
def unbind ( self , dependency , svc , svc_ref ) : # type : ( Any , Any , ServiceReference ) - > None
"""Called by a dependency manager to remove an injected service and to
update the component life cycle .""" | with self . _lock : # Invalidate first ( if needed )
self . check_lifecycle ( )
# Call unbind ( ) and remove the injection
self . __unset_binding ( dependency , svc , svc_ref )
# Try a new configuration
if self . update_bindings ( ) :
self . check_lifecycle ( ) |
def p_arg_list ( p ) :
"""arg _ list : ident _ init _ opt
| arg _ list COMMA ident _ init _ opt""" | if len ( p ) == 2 :
p [ 0 ] = node . expr_list ( [ p [ 1 ] ] )
elif len ( p ) == 4 :
p [ 0 ] = p [ 1 ]
p [ 0 ] . append ( p [ 3 ] )
else :
assert 0
assert isinstance ( p [ 0 ] , node . expr_list ) |
def sinkhorn ( w1 , w2 , M , reg , k ) :
"""Sinkhorn algorithm with fixed number of iteration ( autograd )""" | K = np . exp ( - M / reg )
ui = np . ones ( ( M . shape [ 0 ] , ) )
vi = np . ones ( ( M . shape [ 1 ] , ) )
for i in range ( k ) :
vi = w2 / ( np . dot ( K . T , ui ) )
ui = w1 / ( np . dot ( K , vi ) )
G = ui . reshape ( ( M . shape [ 0 ] , 1 ) ) * K * vi . reshape ( ( 1 , M . shape [ 1 ] ) )
return G |
def open ( self ) :
"""Open the Sender using the supplied conneciton .
If the handler has previously been redirected , the redirect
context will be used to create a new handler before opening it .
: param connection : The underlying client shared connection .
: type : connection : ~ uamqp . connection . Con... | self . running = True
if self . redirected :
self . target = self . redirected . address
self . _handler = SendClient ( self . target , auth = self . client . get_auth ( ) , debug = self . client . debug , msg_timeout = self . timeout , error_policy = self . retry_policy , keep_alive_interval = self . keep_aliv... |
def set_created_date ( self , created_date = None ) :
"""Sets the created date .
: param created _ date : the new created date
: type created _ date : ` ` osid . calendaring . DateTime ` `
: raise : ` ` InvalidArgument ` ` - - ` ` created _ date ` ` is invalid
: raise : ` ` NoAccess ` ` - - ` ` Metadata . i... | if created_date is None :
raise NullArgument ( )
metadata = Metadata ( ** settings . METADATA [ 'created_date' ] )
if metadata . is_read_only ( ) :
raise NoAccess ( )
if self . _is_valid_input ( created_date , metadata , array = False ) :
self . _my_map [ 'createdDate' ] = created_date
# This is probabl... |
def create_skel ( role ) :
'''Create the skeleton of a dictionary or JSON file
A dictionary is returned that contains the " molssi _ bse _ schema "
key and other required keys , depending on the role
role can be either ' component ' , ' element ' , or ' table ' ''' | role = role . lower ( )
if not role in _skeletons :
raise RuntimeError ( "Role {} not found. Should be 'component', 'element', 'table', or 'metadata'" )
return copy . deepcopy ( _skeletons [ role ] ) |
def apply_cc ( self , cc , distribution_skip = False , ** kwargs ) :
"""Apply contrast - curve constraint to population .
Only works if object has ` ` Rsky ` ` , ` ` dmag ` ` attributes
: param cc :
Contrast curve .
: type cc :
: class : ` ContrastCurveConstraint `
: param distribution _ skip :
This i... | rs = self . Rsky . to ( 'arcsec' ) . value
dmags = self . dmag ( cc . band )
self . apply_constraint ( ContrastCurveConstraint ( rs , dmags , cc , name = cc . name ) , distribution_skip = distribution_skip , ** kwargs ) |
def children ( self ) :
"""~ TermList : The direct children of the ` Term ` .""" | if self . _children is None :
topdowns = tuple ( Relationship . topdown ( ) )
self . _children = TermList ( )
self . _children . extend ( [ other for rship , others in six . iteritems ( self . relations ) for other in others if rship in topdowns ] )
return self . _children |
def _rank_tags ( tagged_paired_aligns ) :
'''Return the list of tags ranked from most to least popular .''' | tag_count_dict = defaultdict ( int )
for paired_align in tagged_paired_aligns :
tag_count_dict [ paired_align . umt ] += 1
tags_by_count = utils . sort_dict ( tag_count_dict )
ranked_tags = [ tag_count [ 0 ] for tag_count in tags_by_count ]
return ranked_tags |
def _switch ( name , # pylint : disable = C0103
on , # pylint : disable = C0103
** kwargs ) :
'''Switch on / off service start at boot .
. . versionchanged : : 2016.3.4
Support for jail ( representing jid or jail name ) and chroot keyword argument
in kwargs . chroot should be used when jail ' s / etc is mount... | jail = kwargs . get ( 'jail' , '' )
chroot = kwargs . get ( 'chroot' , '' ) . rstrip ( '/' )
if not available ( name , jail ) :
return False
rcvar = _get_rcvar ( name , jail )
if not rcvar :
log . error ( 'rcvar for service %s not found' , name )
return False
if jail and not chroot : # prepend the jail ' s ... |
def _yield_week_day ( self , enumeration = False ) :
"""A helper function to reduce the number of nested loops .
Parameters
enumeration
Whether or not to wrap the days in enumerate ( ) .
Yields
tuple
A tuple with ( week , day _ index , day ) or ( week , day ) ,
depending on ' enumeration ' parameter .... | if enumeration : # Iterate over all weeks
for week in range ( 1 , self . duration + 1 ) : # Iterate over all days
for day_index , day in enumerate ( self . days ) :
yield ( week , day_index , day )
else : # Iterate over all weeks
for week in range ( 1 , self . duration + 1 ) : # Iterate over... |
def ttl_cache ( maxsize = 128 , ttl = 600 , timer = default_timer , typed = False ) :
"""Decorator to wrap a function with a memoizing callable that saves
up to ` maxsize ` results based on a Least Recently Used ( LRU )
algorithm with a per - item time - to - live ( TTL ) value .""" | if maxsize is None :
return _cache ( _UnboundTTLCache ( ttl , timer ) , typed )
else :
return _cache ( TTLCache ( maxsize , ttl , timer ) , typed ) |
def hessian ( L , Y , U , adj = False , inv = False , factored_updates = False ) :
"""Supernodal multifrontal Hessian mapping .
The mapping
. . math : :
\mathcal H_X(U) = P(X^{-1}UX^{-1})
is the Hessian of the log - det barrier at a positive definite chordal
matrix : math : ` X ` , applied to a symmetric ... | assert L . symb == Y . symb , "Symbolic factorization mismatch"
assert isinstance ( L , cspmatrix ) and L . is_factor is True , "L must be a cspmatrix factor"
assert isinstance ( Y , cspmatrix ) and Y . is_factor is False , "Y must be a cspmatrix"
if isinstance ( U , cspmatrix ) :
assert U . is_factor is False , "U... |
def process_messages_loop_internal ( self ) :
"""Busy loop that processes incoming WorkRequest messages via functions specified by add _ command .
Terminates if a command runs shutdown method""" | logging . info ( "Starting work queue loop." )
self . connection . receive_loop_with_callback ( self . queue_name , self . process_message ) |
def click ( self , pos ) :
"""Perform click ( touch , tap , etc . ) action on target device at given coordinates .
The coordinates ( x , y ) are either a 2 - list or 2 - tuple . The coordinates values for x and y must be in the
interval between 0 ~ 1 to represent the percentage of the screen . For example , the... | if not ( 0 <= pos [ 0 ] <= 1 ) or not ( 0 <= pos [ 1 ] <= 1 ) :
raise InvalidOperationException ( 'Click position out of screen. pos={}' . format ( repr ( pos ) ) )
ret = self . agent . input . click ( pos [ 0 ] , pos [ 1 ] )
self . wait_stable ( )
return ret |
def get_form ( self , request , obj = None , ** kwargs ) :
"""Patched method for PageAdmin . get _ form .
Returns a page form without the base field ' meta _ description ' which is
overridden in djangocms - page - meta .
This is triggered in the page add view and in the change view if
the meta description o... | language = get_language_from_request ( request , obj )
form = _BASE_PAGEADMIN__GET_FORM ( self , request , obj , ** kwargs )
if not obj or not obj . get_meta_description ( language = language ) :
form . base_fields . pop ( 'meta_description' , None )
return form |
def add_mdisks ( self , userid , disk_list , start_vdev = None ) :
"""Add disks for the userid
: disks : A list dictionary to describe disk info , for example :
disk : [ { ' size ' : ' 1g ' ,
' format ' : ' ext3 ' ,
' disk _ pool ' : ' ECKD : eckdpool1 ' } ]""" | for idx , disk in enumerate ( disk_list ) :
if 'vdev' in disk : # this means user want to create their own device number
vdev = disk [ 'vdev' ]
else :
vdev = self . generate_disk_vdev ( start_vdev = start_vdev , offset = idx )
self . _add_mdisk ( userid , disk , vdev )
disk [ 'vdev' ] = ... |
def date ( name = None ) :
"""Creates the grammar for a Date ( D ) field , accepting only numbers in a
certain pattern .
: param name : name for the field
: return : grammar for the date field""" | if name is None :
name = 'Date Field'
# Basic field
# This regex allows values from 00000101 to 99991231
field = pp . Regex ( '[0-9][0-9][0-9][0-9](0[1-9]|1[0-2])' '(0[1-9]|[1-2][0-9]|3[0-1])' )
# Parse action
field . setParseAction ( lambda d : datetime . datetime . strptime ( d [ 0 ] , '%Y%m%d' ) . date ( ) )
# N... |
def _get_cache_dir ( candidate ) :
"""Get the current cache directory .""" | if candidate :
return candidate
import distutils . dist
# suppress ( import - error )
import distutils . command . build
# suppress ( import - error )
build_cmd = distutils . command . build . build ( distutils . dist . Distribution ( ) )
build_cmd . finalize_options ( )
cache_dir = os . path . abspath ( build_cmd ... |
def do_uninstall ( ctx , verbose , fake ) :
"""Uninstalls legit git aliases , including deprecated legit sub - commands .""" | aliases = cli . list_commands ( ctx )
# Add deprecated aliases
aliases . extend ( [ 'graft' , 'harvest' , 'sprout' , 'resync' , 'settings' , 'install' , 'uninstall' ] )
for alias in aliases :
system_command = 'git config --global --unset-all alias.{0}' . format ( alias )
verbose_echo ( system_command , verbose ... |
def path_to_ls ( fn ) :
"""Converts an absolute path to an entry resembling the output of
the ls command on most UNIX systems .""" | st = os . stat ( fn )
full_mode = 'rwxrwxrwx'
mode = ''
file_time = ''
d = ''
for i in range ( 9 ) : # Incrementally builds up the 9 character string , using characters from the
# fullmode ( defined above ) and mode bits from the stat ( ) system call .
mode += ( ( st . st_mode >> ( 8 - i ) ) & 1 ) and full_mode [ i... |
def index ( self , * args , ** kwargs ) :
"""Index documents , in the current session""" | self . check_session ( )
result = self . session . index ( * args , ** kwargs )
if self . autosession :
self . commit ( )
return result |
def elementwise_modulo ( tuple1 , tuple2 ) :
"""This function calculates the modulo ( remainder of division ) of corresponding elements in two input tuples .
For each pair of elements , the first element is divided by the second , and the remainder is stored .
> > > elementwise _ modulo ( ( 10 , 4 , 5 , 6 ) , (... | result = tuple ( ( ele1 % ele2 ) for ( ele1 , ele2 ) in zip ( tuple1 , tuple2 ) )
return result |
def get_raw_history ( self , item = None , nb = 0 ) :
"""Return the history ( RAW format ) .
- the stats history ( dict of list ) if item is None
- the stats history for the given item ( list ) instead
- None if item did not exist in the history""" | s = self . stats_history . get ( nb = nb )
if item is None :
return s
else :
if item in s :
return s [ item ]
else :
return None |
def deparse_code2str ( code , out = sys . stdout , version = None , debug_opts = DEFAULT_DEBUG_OPTS , code_objects = { } , compile_mode = 'exec' , is_pypy = IS_PYPY , walker = SourceWalker ) :
"""Return the deparsed text for a Python code object . ` out ` is where any intermediate
output for assembly or tree outp... | return deparse_code ( version , code , out , showasm = debug_opts . get ( 'asm' , None ) , showast = debug_opts . get ( 'tree' , None ) , showgrammar = debug_opts . get ( 'grammar' , None ) , code_objects = code_objects , compile_mode = compile_mode , is_pypy = is_pypy , walker = walker ) . text |
def coerceType ( self , ftype , value ) :
"""Returns unicode ( value ) after trying to coerce it into the SOLR field type .
@ param ftype ( string ) The SOLR field type for the value
@ param value ( any ) The value that is to be represented as Unicode text .""" | if value is None :
return None
if ftype == 'string' :
return str ( value )
elif ftype == 'text' :
return str ( value )
elif ftype == 'int' :
try :
v = int ( value )
return str ( v )
except Exception :
return None
elif ftype == 'float' :
try :
v = float ( value )
... |
def download_file_from_url ( self , source_app , url ) :
"""Download file from source app or url , and return local filename .""" | if source_app :
source_name = source_app
else :
source_name = urlparse . urlparse ( url ) . netloc . replace ( '.' , '_' )
filename = self . create_file_name ( source_name )
self . download_file ( url , filename )
return filename |
def erase_sector ( self , address ) :
"""@ brief Erase one sector .
@ exception FlashEraseFailure""" | assert self . _active_operation == self . Operation . ERASE
# update core register to execute the erase _ sector subroutine
result = self . _call_function_and_wait ( self . flash_algo [ 'pc_erase_sector' ] , address )
# check the return code
if result != 0 :
raise FlashEraseFailure ( 'erase_sector(0x%x) error: %i' ... |
def remove ( self , element ) :
"""Remove an element from the bag .
> > > s = pbag ( [ 1 , 1 , 2 ] )
> > > s2 = s . remove ( 1)
> > > s3 = s . remove ( 2)
> > > s2
pbag ( [ 1 , 2 ] )
> > > s3
pbag ( [ 1 , 1 ] )""" | if element not in self . _counts :
raise KeyError ( element )
elif self . _counts [ element ] == 1 :
newc = self . _counts . remove ( element )
else :
newc = self . _counts . set ( element , self . _counts [ element ] - 1 )
return PBag ( newc ) |
def reset_all_full ( self , force = False ) :
"""Removes all accounts that can be recalculated ( IOSystem and extensions )
This calls reset _ full for the core system and all extension .
Parameters
force : boolean , optional
If True , reset to flows although the system can not be
recalculated . Default : ... | self . reset_full ( )
[ ee . reset_full ( ) for ee in self . get_extensions ( data = True ) ]
self . meta . _add_modify ( "Reset all calculated data" )
return self |
def get_tokens_unprocessed ( self , text ) :
"""Since ERB doesn ' t allow " < % " and other tags inside of ruby
blocks we have to use a split approach here that fails for
that too .""" | tokens = self . _block_re . split ( text )
tokens . reverse ( )
state = idx = 0
try :
while True : # text
if state == 0 :
val = tokens . pop ( )
yield idx , Other , val
idx += len ( val )
state = 1
# block starts
elif state == 1 :
t... |
def add_openmp_flags_if_available ( extension ) :
"""Add OpenMP compilation flags , if supported ( if not a warning will be
printed to the console and no flags will be added . )
Returns ` True ` if the flags were added , ` False ` otherwise .""" | if _ASTROPY_DISABLE_SETUP_WITH_OPENMP_ :
log . info ( "OpenMP support has been explicitly disabled." )
return False
openmp_flags = get_openmp_flags ( )
using_openmp = check_openmp_support ( openmp_flags = openmp_flags )
if using_openmp :
compile_flags = openmp_flags . get ( 'compiler_flags' )
link_flags... |
def add_child_to_self ( self , tree ) :
'''Adds given * tree * as a child of the current tree .''' | assert isinstance ( tree , Tree ) , '(!) Unexpected type of argument for ' + argName + '! Should be Tree.'
if ( not self . children ) :
self . children = [ ]
tree . parent = self
self . children . append ( tree ) |
def kxtrct ( keywd , terms , nterms , instring , termlen = _default_len_out , stringlen = _default_len_out , substrlen = _default_len_out ) :
"""Locate a keyword in a string and extract the substring from
the beginning of the first word following the keyword to the
beginning of the first subsequent recognized t... | assert nterms <= len ( terms )
# Python strings and string arrays = > to C char pointers
keywd = stypes . stringToCharP ( keywd )
terms = stypes . listToCharArrayPtr ( [ s [ : termlen - 1 ] for s in terms [ : nterms ] ] , xLen = termlen , yLen = nterms )
instring = stypes . stringToCharP ( instring [ : stringlen - 1 ] ... |
def train_hmm ( self , observation_list , iterations , quantities ) :
"""Runs the Baum Welch Algorithm and finds the new model parameters
* * Arguments * * :
: param observation _ list : A nested list , or a list of lists
: type observation _ list : Contains a list multiple observation sequences .
: param i... | obs_size = len ( observation_list )
prob = float ( 'inf' )
q = quantities
# Train the model ' iteration ' number of times
# store em _ prob and trans _ prob copies since you should use same values for one loop
for i in range ( iterations ) :
emProbNew = np . asmatrix ( np . zeros ( ( self . em_prob . shape ) ) )
... |
def add_shot ( self , shot ) :
"""Add a Shot to : attr : ` shots ` , applying our survey ' s : attr : ` declination ` to it .""" | shot . declination = self . declination
if shot . is_splay :
self . splays [ shot [ 'FROM' ] ] . append ( shot )
self . shots . append ( shot ) |
def list_occupied_adb_ports ( ) :
"""Lists all the host ports occupied by adb forward .
This is useful because adb will silently override the binding if an attempt
to bind to a port already used by adb was made , instead of throwing binding
error . So one should always check what ports adb is using before try... | out = AdbProxy ( ) . forward ( '--list' )
clean_lines = str ( out , 'utf-8' ) . strip ( ) . split ( '\n' )
used_ports = [ ]
for line in clean_lines :
tokens = line . split ( ' tcp:' )
if len ( tokens ) != 3 :
continue
used_ports . append ( int ( tokens [ 1 ] ) )
return used_ports |
def to_json ( self ) :
"""Return a JSON - serializable representation .""" | return { 'network' : self . network , 'before_state' : self . before_state , 'after_state' : self . after_state , 'cause_indices' : self . cause_indices , 'effect_indices' : self . effect_indices , 'cut' : self . cut } |
def _check_engine ( engine ) :
"""Make sure a valid engine is passed .
Parameters
engine : str
Raises
KeyError
* If an invalid engine is passed
ImportError
* If numexpr was requested but doesn ' t exist
Returns
string engine""" | from pandas . core . computation . check import _NUMEXPR_INSTALLED
if engine is None :
if _NUMEXPR_INSTALLED :
engine = 'numexpr'
else :
engine = 'python'
if engine not in _engines :
valid = list ( _engines . keys ( ) )
raise KeyError ( 'Invalid engine {engine!r} passed, valid engines ar... |
def drop_all ( self , queue_name ) :
"""Drops all the task in the queue .
: param queue _ name : The name of the queue . Usually handled by the
` ` Gator ` ` instance .
: type queue _ name : string""" | task_ids = self . conn . lrange ( queue_name , 0 , - 1 )
for task_id in task_ids :
self . conn . delete ( task_id )
self . conn . delete ( queue_name ) |
def show ( only_path = False ) :
"""Show the current config .""" | logger . setLevel ( logging . INFO )
infos = [ "\n" , f'Instance path: "{current_app.instance_path}"' ]
logger . info ( "\n " . join ( infos ) )
if not only_path :
log_config ( current_app . config ) |
def connect ( database : str , loop : asyncio . BaseEventLoop = None , executor : concurrent . futures . Executor = None , timeout : int = 5 , echo : bool = False , isolation_level : str = '' , check_same_thread : bool = False , ** kwargs : dict ) :
"""把async方法执行后的对象创建为async上下文模式""" | coro = _connect ( database , loop = loop , executor = executor , timeout = timeout , echo = echo , isolation_level = isolation_level , check_same_thread = check_same_thread , ** kwargs )
return _ContextManager ( coro ) |
def parse ( path ) :
"""Parses xml and returns a formatted dict .
Example :
wpparser . parse ( " . / blog . wordpress . 2014-09-26 . xml " )
Will return :
" blog " : {
" tagline " : " Tagline " ,
" site _ url " : " http : / / marteinn . se / blog " ,
" blog _ url " : " http : / / marteinn . se / blog ... | doc = ET . parse ( path ) . getroot ( )
channel = doc . find ( "./channel" )
blog = _parse_blog ( channel )
authors = _parse_authors ( channel )
categories = _parse_categories ( channel )
tags = _parse_tags ( channel )
posts = _parse_posts ( channel )
return { "blog" : blog , "authors" : authors , "categories" : catego... |
def send ( self ) :
"""this handles the message transmission""" | # print ( ' sending message to ' + self . receiver )
if self . prepare ( ) : # # TODO - send message via library
print ( 'sending message' )
lg . record_process ( 'comms.py' , 'Sending message ' + self . title )
return True
else :
return False |
def p_union ( self , p ) :
'''union : UNION IDENTIFIER ' { ' field _ seq ' } ' annotations''' | p [ 0 ] = ast . Union ( name = p [ 2 ] , fields = p [ 4 ] , annotations = p [ 6 ] , lineno = p . lineno ( 2 ) ) |
def save ( self , expected_value = None , return_values = None ) :
"""Commits pending updates to Amazon DynamoDB .
: type expected _ value : dict
: param expected _ value : A dictionary of name / value pairs that
you expect . This dictionary should have name / value pairs
where the name is the name of the a... | return self . table . layer2 . update_item ( self , expected_value , return_values ) |
def formfield_for_dbfield ( self , db_field , ** kwargs ) :
'''Offer grading choices from the assignment definition as potential form
field values for ' grading ' .
When no object is given in the form , the this is a new manual submission''' | if db_field . name == "grading" :
submurl = kwargs [ 'request' ] . path
try : # Does not work on new submission action by admin or with a change of URLs . The former is expectable .
submid = [ int ( s ) for s in submurl . split ( '/' ) if s . isdigit ( ) ] [ 0 ]
kwargs [ "queryset" ] = Submissio... |
def focusin ( event ) :
"""Change style on focus in events .""" | w = event . widget . spinbox
w . old_value = w . get ( )
bc = w . style . lookup ( "TEntry" , "bordercolor" , ( "focus" , ) )
dc = w . style . lookup ( "TEntry" , "darkcolor" , ( "focus" , ) )
lc = w . style . lookup ( "TEntry" , "lightcolor" , ( "focus" , ) )
w . style . configure ( "%s.spinbox.TFrame" % event . widge... |
def _parse_rmw_row_response ( row_response ) :
"""Parses the response to a ` ` ReadModifyWriteRow ` ` request .
: type row _ response : : class : ` . data _ v2 _ pb2 . Row `
: param row _ response : The response row ( with only modified cells ) from a
` ` ReadModifyWriteRow ` ` request .
: rtype : dict
: ... | result = { }
for column_family in row_response . row . families :
column_family_id , curr_family = _parse_family_pb ( column_family )
result [ column_family_id ] = curr_family
return result |
def _load_cwr_defaults ( self ) :
"""Loads the CWR default values file , creating a matrix from it , and then
returns this data .
The file will only be loaded once .
: return : the CWR default values matrix""" | if self . _cwr_defaults is None :
self . _cwr_defaults = self . _reader . read_yaml_file ( self . _file_defaults )
return self . _cwr_defaults |
def version ( self ) :
"""RPM vesion string .""" | stdout = Cmd . sh_e_out ( '{0} --version' . format ( self . rpm_path ) )
rpm_version = stdout . split ( ) [ 2 ]
return rpm_version |
def create ( self , ** kwargs ) :
"""Create an alarm definition .""" | resp = self . client . create ( url = self . base_url , json = kwargs )
return resp |
def xy_databoxes ( ds , xscript = 0 , yscript = 'd[1]' , eyscript = None , exscript = None , g = None , ** kwargs ) :
"""Use databoxes and scripts to generate and plot ydata versus xdata .
Parameters
ds
List of databoxes
xscript = 0
Script for x data
yscript = ' d [ 1 ] '
Script for y data
eyscript ... | databoxes ( ds , xscript , yscript , eyscript , exscript , plotter = xy_data , g = g , ** kwargs ) |
def block ( context_name , parent_block_func , view_func = None ) :
"""A decorator that is used for inserting the decorated block function in
the block template hierarchy .
The : func : ` block ` decorator accepts the following arguments :
: param context _ name : key in the ` g . blocks ` dictionary in which... | def decorator ( block_func ) :
block = Block ( block_func , view_func )
parent_block = Block . block_mapping [ parent_block_func ]
parent_block . append_context_block ( context_name , block )
return block_func
return decorator |
def _get_type ( cls , ptr ) :
"""Get the subtype class for a pointer""" | # fall back to the base class if unknown
return cls . __types . get ( lib . g_base_info_get_type ( ptr ) , cls ) |
def get_shared_file ( self , sharekey = None ) :
"""Returns a SharedFile object given by the sharekey .
Args :
sharekey ( str ) : Sharekey of the SharedFile you want to retrieve .
Returns :
SharedFile""" | if not sharekey :
raise Exception ( "You must specify a sharekey." )
endpoint = '/api/sharedfile/{0}' . format ( sharekey )
data = self . _make_request ( 'GET' , endpoint )
return SharedFile . NewFromJSON ( data ) |
def cli ( * , worker_settings , burst , check , watch , verbose ) :
"""Job queues in python with asyncio and redis .
CLI to run the arq worker .""" | sys . path . append ( os . getcwd ( ) )
worker_settings = import_string ( worker_settings )
logging . config . dictConfig ( default_log_config ( verbose ) )
if check :
exit ( check_health ( worker_settings ) )
else :
kwargs = { } if burst is None else { 'burst' : burst }
if watch :
loop = asyncio . ... |
def initAddons ( cls , recurse = True ) :
"""Loads different addon modules for this class . This method
should not be overloaded in a subclass as it also manages the loaded
state to avoid duplicate loads . Instead , you can re - implement the
_ initAddons method for custom loading .
: param recurse | < bool... | key = '_{0}__addons_loaded' . format ( cls . __name__ )
if getattr ( cls , key , False ) :
return
cls . _initAddons ( recurse )
setattr ( cls , key , True ) |
def trunk_origin_radii ( nrn , neurite_type = NeuriteType . all ) :
'''radii of the trunk sections of neurites in a neuron''' | neurite_filter = is_type ( neurite_type )
return [ s . root_node . points [ 0 ] [ COLS . R ] for s in nrn . neurites if neurite_filter ( s ) ] |
def receive_message ( self , message : Message ) :
"""Handle a Raiden protocol message .
The protocol requires durability of the messages . The UDP transport
relies on the node ' s WAL for durability . The message will be converted
to a state change , saved to the WAL , and * processed * before the
durabili... | self . raiden . on_message ( message )
# Sending Delivered after the message is decoded and * processed *
# gives a stronger guarantee than what is required from a
# transport .
# Alternatives are , from weakest to strongest options :
# - Just save it on disk and asynchronously process the messages
# - Decode it , save... |
def _to_datalibrary ( fname , gi , folder_name , sample_info , config ) :
"""Upload a file to a Galaxy data library in a project specific folder .""" | library = _get_library ( gi , sample_info , config )
libitems = gi . libraries . show_library ( library . id , contents = True )
folder = _get_folder ( gi , folder_name , library , libitems )
_file_to_folder ( gi , fname , sample_info , libitems , library , folder ) |
def print_stack ( pid , include_greenlet = False , debugger = None , verbose = False ) :
"""Executes a file in a running Python process .""" | # TextIOWrapper of Python 3 is so strange .
sys_stdout = getattr ( sys . stdout , 'buffer' , sys . stdout )
sys_stderr = getattr ( sys . stderr , 'buffer' , sys . stderr )
make_args = make_gdb_args
environ = dict ( os . environ )
if ( debugger == 'lldb' or ( debugger is None and platform . system ( ) . lower ( ) == 'da... |
def writer ( path ) :
"""Creates a compressed file writer from for a path with a specified
compression type .""" | filename , extension = extract_extension ( path )
if extension in FILE_WRITERS :
writer_func = FILE_WRITERS [ extension ]
return writer_func ( path )
else :
raise RuntimeError ( "Output compression {0} not supported. Type {1}" . format ( extension , tuple ( FILE_WRITERS . keys ( ) ) ) ) |
def subscribing_strategy ( self ) :
"""订阅一个策略
Returns :
[ type ] - - [ description ]""" | res = self . subscribed_strategy . assign ( remains = self . subscribed_strategy . end . apply ( lambda x : pd . Timestamp ( x ) - pd . Timestamp ( datetime . date . today ( ) ) ) )
# res [ ' left ' ] = res [ ' end _ time ' ]
# res [ ' remains ' ]
res . assign ( status = res [ 'remains' ] . apply ( lambda x : 'running'... |
def subscriber_has_active_subscription ( subscriber , plan = None ) :
"""Helper function to check if a subscriber has an active subscription .
Throws improperlyConfigured if the subscriber is an instance of AUTH _ USER _ MODEL
and get _ user _ model ( ) . is _ anonymous = = True .
Activate subscription rules ... | if isinstance ( subscriber , AnonymousUser ) :
raise ImproperlyConfigured ( ANONYMOUS_USER_ERROR_MSG )
if isinstance ( subscriber , get_user_model ( ) ) :
if subscriber . is_superuser or subscriber . is_staff :
return True
from . models import Customer
customer , created = Customer . get_or_create ( sub... |
def parts_to_url ( parts = None , scheme = None , netloc = None , path = None , query = None , fragment = None ) :
"""Build url urlunsplit style , but optionally handle path as a list and / or query as a dict""" | if isinstance ( parts , _urllib_parse . SplitResult ) :
scheme , netloc , path , query , fragment = parts
elif parts and isinstance ( parts , dict ) :
scheme = parts . get ( 'scheme' , 'http' )
netloc = parts . get ( 'netloc' , '' )
path = parts . get ( 'path' , [ ] )
query = parts . get ( 'query' ,... |
def serialize ( self , pyobj , typecode = None , root = None , header_pyobjs = ( ) , ** kw ) :
'''Serialize a Python object to the output stream .
pyobj - - python instance to serialize in body .
typecode - - typecode describing body
root - - SOAP - ENC : root
header _ pyobjs - - list of pyobj for soap head... | self . body = None
if self . envelope :
soap_env = _reserved_ns [ 'SOAP-ENV' ]
self . dom . createDocument ( soap_env , 'Envelope' )
for prefix , nsuri in _reserved_ns . items ( ) :
self . dom . setNamespaceAttribute ( prefix , nsuri )
self . writeNSdict ( self . nsdict )
if self . encodingS... |
def get_schema_descendant ( self , route : SchemaRoute ) -> Optional [ SchemaNode ] :
"""Return descendant schema node or ` ` None ` ` if not found .
Args :
route : Schema route to the descendant node
( relative to the receiver ) .""" | node = self
for p in route :
node = node . get_child ( * p )
if node is None :
return None
return node |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.