signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def remove_security_group ( self , name ) :
"""Remove a security group from container""" | for group in self . security_groups :
if group . isc_name == name :
group . delete ( ) |
def HandleVersion ( self , payload ) :
"""Process the response of ` self . RequestVersion ` .""" | self . Version = IOHelper . AsSerializableWithType ( payload , "neo.Network.Payloads.VersionPayload.VersionPayload" )
if not self . Version :
return
if self . incoming_client :
if self . Version . Nonce == self . nodeid :
self . Disconnect ( )
self . SendVerack ( )
else :
self . nodeid = self . ... |
def form_group_wrapped ( f ) :
"""Wrap a field within a bootstrap form - group . Additionally sets has - error
This decorator sets has - error if the field has any errors .""" | @ wraps ( f )
def wrapped ( self , field , * args , ** kwargs ) :
classes = [ 'form-group' ]
if field . errors :
classes . append ( 'has-error' )
html = """<div class="{classes}">{rendered_field}</div>""" . format ( classes = ' ' . join ( classes ) , rendered_field = f ( self , field , * args , ** k... |
def toArray ( self ) :
"""Returns a copy of this SparseVector as a 1 - dimensional NumPy array .""" | arr = np . zeros ( ( self . size , ) , dtype = np . float64 )
arr [ self . indices ] = self . values
return arr |
def request ( self , api_call , data = None , api_version = None , http_method = None , concurrent_scans_retries = 0 , concurrent_scans_retry_delay = 0 ) :
"""Return QualysGuard API response .""" | logger . debug ( 'api_call =\n%s' % api_call )
logger . debug ( 'api_version =\n%s' % api_version )
logger . debug ( 'data %s =\n %s' % ( type ( data ) , str ( data ) ) )
logger . debug ( 'http_method =\n%s' % http_method )
logger . debug ( 'concurrent_scans_retries =\n%s' % str ( concurrent_scans_retries ) )
logger . ... |
def clean_dateobject_to_string ( x ) :
"""Convert a Pandas Timestamp object or datetime object
to ' YYYY - MM - DD ' string
Parameters
x : str , list , tuple , numpy . ndarray , pandas . DataFrame
A Pandas Timestamp object or datetime object ,
or an array of these objects
Returns
y : str , list , tupl... | import numpy as np
import pandas as pd
def proc_elem ( e ) :
try :
return e . strftime ( "%Y-%m-%d" )
except Exception as e :
print ( e )
return None
def proc_list ( x ) :
return [ proc_elem ( e ) for e in x ]
def proc_ndarray ( x ) :
tmp = proc_list ( list ( x . reshape ( ( x . ... |
async def getNodeByBuid ( self , buid ) :
'''Retrieve a node tuple by binary id .
Args :
buid ( bytes ) : The binary ID for the node .
Returns :
Optional [ s _ node . Node ] : The node object or None .''' | node = self . livenodes . get ( buid )
if node is not None :
return node
props = { }
proplayr = { }
for layr in self . layers :
layerprops = await layr . getBuidProps ( buid )
props . update ( layerprops )
proplayr . update ( { k : layr for k in layerprops } )
node = s_node . Node ( self , buid , props ... |
def printPolicy ( policy ) :
"""Print out a policy vector as a table to console
Let ` ` S ` ` = number of states .
The output is a table that has the population class as rows , and the years
since a fire as the columns . The items in the table are the optimal action
for that population class and years since... | p = np . array ( policy ) . reshape ( POPULATION_CLASSES , FIRE_CLASSES )
range_F = range ( FIRE_CLASSES )
print ( " " + " " . join ( "%2d" % f for f in range_F ) )
print ( " " + "---" * FIRE_CLASSES )
for x in range ( POPULATION_CLASSES ) :
print ( " %2d|" % x + " " . join ( "%2d" % p [ x , f ] for f in rang... |
def helical_laminar_fd_Schmidt ( Re , Di , Dc ) :
r'''Calculates Darcy friction factor for a fluid flowing inside a curved
pipe such as a helical coil under laminar conditions , using the method of
Schmidt [ 1 ] _ as shown in [ 2 ] _ and [ 3 ] _ .
. . math : :
f _ { curved } = f _ { \ text { straight , lami... | fd = friction_laminar ( Re )
D_ratio = Di / Dc
return fd * ( 1. + 0.14 * D_ratio ** 0.97 * Re ** ( 1. - 0.644 * D_ratio ** 0.312 ) ) |
def blockhash_from_blocknumber ( self , block_number : BlockSpecification ) -> BlockHash :
"""Given a block number , query the chain to get its corresponding block hash""" | block = self . get_block ( block_number )
return BlockHash ( bytes ( block [ 'hash' ] ) ) |
def make_job ( job_name , ** kwargs ) :
"""Decorator to create a Job from a function .
Give a job name and add extra fields to the job .
@ make _ job ( " ExecuteDecJob " ,
command = mongoengine . StringField ( required = True ) ,
output = mongoengine . StringField ( default = None ) )
def execute ( job : ... | def wraps ( func ) :
kwargs [ 'process' ] = func
job = type ( job_name , ( Job , ) , kwargs )
globals ( ) [ job_name ] = job
return job
return wraps |
def intern_atom ( self , name , only_if_exists = 0 ) :
"""Intern the string name , returning its atom number . If
only _ if _ exists is true and the atom does not already exist , it
will not be created and X . NONE is returned .""" | r = request . InternAtom ( display = self . display , name = name , only_if_exists = only_if_exists )
return r . atom |
def _get_rsa_key ( self ) :
'''get steam RSA key , build and return cipher''' | url = 'https://steamcommunity.com/mobilelogin/getrsakey/'
values = { 'username' : self . _username , 'donotcache' : self . _get_donotcachetime ( ) , }
req = self . post ( url , data = values )
data = req . json ( )
if not data [ 'success' ] :
raise SteamWebError ( 'Failed to get RSA key' , data )
# Construct RSA an... |
def flexifunction_directory_ack_send ( self , target_system , target_component , directory_type , start_index , count , result , force_mavlink1 = False ) :
'''Acknowldge sucess or failure of a flexifunction command
target _ system : System ID ( uint8 _ t )
target _ component : Component ID ( uint8 _ t )
direc... | return self . send ( self . flexifunction_directory_ack_encode ( target_system , target_component , directory_type , start_index , count , result ) , force_mavlink1 = force_mavlink1 ) |
def create_string ( self , value : str ) -> String :
"""Creates a new : class : ` ConstantString ` , adding it to the pool and
returning it .
: param value : The value of the new string as a UTF8 string .""" | self . append ( ( 8 , self . create_utf8 ( value ) . index ) )
return self . get ( self . raw_count - 1 ) |
def create ( self , name , plugin_name , plugin_version , cluster_template_id = None , default_image_id = None , is_transient = None , description = None , cluster_configs = None , node_groups = None , user_keypair_id = None , anti_affinity = None , net_id = None , count = None , use_autoconfig = None , shares = None ,... | data = { 'name' : name , 'plugin_name' : plugin_name , 'plugin_version' : plugin_version , }
return self . _do_create ( data , cluster_template_id , default_image_id , is_transient , description , cluster_configs , node_groups , user_keypair_id , anti_affinity , net_id , count , use_autoconfig , shares , is_public , is... |
def open ( self , path , delimiter = None , mode = 'r' , buffering = - 1 , encoding = None , errors = None , newline = None ) :
"""Reads and parses input files as defined .
If delimiter is not None , then the file is read in bulk then split on it . If it is None
( the default ) , then the file is parsed as sequ... | if not re . match ( '^[rbt]{1,3}$' , mode ) :
raise ValueError ( 'mode argument must be only have r, b, and t' )
file_open = get_read_function ( path , self . disable_compression )
file = file_open ( path , mode = mode , buffering = buffering , encoding = encoding , errors = errors , newline = newline )
if delimite... |
def add_page ( self , page , process_id , wit_ref_name ) :
"""AddPage .
[ Preview API ] Adds a page to the work item form .
: param : class : ` < Page > < azure . devops . v5_0 . work _ item _ tracking _ process . models . Page > ` page : The page .
: param str process _ id : The ID of the process .
: param... | route_values = { }
if process_id is not None :
route_values [ 'processId' ] = self . _serialize . url ( 'process_id' , process_id , 'str' )
if wit_ref_name is not None :
route_values [ 'witRefName' ] = self . _serialize . url ( 'wit_ref_name' , wit_ref_name , 'str' )
content = self . _serialize . body ( page , ... |
def delete_item_list ( self , item_list_url ) :
"""Delete an Item List on the server
: type item _ list _ url : String or ItemList
: param item _ list _ url : the URL of the list to which to add the items ,
or an ItemList object
: rtype : Boolean
: returns : True if the item list was deleted
: raises : ... | try :
resp = self . api_request ( str ( item_list_url ) , method = "DELETE" )
# all good if it says success
if 'success' in resp :
return True
else :
raise APIError ( '200' , 'Operation Failed' , 'Delete operation failed' )
except APIError as e :
if e . http_status_code == 302 :
... |
def change_wavelength ( self , wavelength ) :
'''Changes the wavelength of the structure .
This will affect the mode solver and potentially
the refractive indices used ( provided functions
were provided as refractive indices ) .
Args :
wavelength ( float ) : The new wavelength .''' | for axis in self . axes :
if issubclass ( type ( axis ) , Slabs ) :
axis . change_wavelength ( wavelength )
self . xx , self . xy , self . yx , self . yy , self . zz = self . axes
self . _wl = wavelength |
def ngettext_lazy ( singular , plural , n , domain = DEFAULT_DOMAIN ) :
"""Mark a message with plural forms translateable , and delay the translation
until the message is used .
Works the same was a ` ngettext ` , with a delaying functionality similiar to ` gettext _ lazy ` .
Args :
singular ( unicode ) : T... | return LazyProxy ( ngettext , singular , plural , n , domain = domain , enable_cache = False ) |
def Colebrook ( Re , eD , tol = None ) :
r'''Calculates Darcy friction factor using the Colebrook equation
originally published in [ 1 ] _ . Normally , this function uses an exact
solution to the Colebrook equation , derived with a CAS . A numerical can
also be used .
. . math : :
\ frac { 1 } { \ sqrt { ... | if tol == - 1 :
if Re > 10.0 :
return Clamond ( Re , eD )
else :
tol = None
elif tol == 0 : # from sympy import LambertW , Rational , log , sqrt
# Re = Rational ( Re )
# eD _ Re = Rational ( eD ) * Re
# sub = 1 / Rational ( ' 6.3001 ' ) * 10 * * ( 1 / Rational ( ' 9.287 ' ) * eD _ Re ) * Re * Re... |
def _file_dict ( self , fn_ ) :
'''Take a path and return the contents of the file as a string''' | if not os . path . isfile ( fn_ ) :
err = 'The referenced file, {0} is not available.' . format ( fn_ )
sys . stderr . write ( err + '\n' )
sys . exit ( 42 )
with salt . utils . files . fopen ( fn_ , 'r' ) as fp_ :
data = fp_ . read ( )
return { fn_ : data } |
def _2ndDerivInt ( x , y , z , dens , densDeriv , b2 , c2 , i , j , glx = None , glw = None ) :
"""Integral that gives the 2nd derivative of the potential in x , y , z""" | def integrand ( s ) :
t = 1 / s ** 2. - 1.
m = numpy . sqrt ( x ** 2. / ( 1. + t ) + y ** 2. / ( b2 + t ) + z ** 2. / ( c2 + t ) )
return ( densDeriv ( m ) * ( x / ( 1. + t ) * ( i == 0 ) + y / ( b2 + t ) * ( i == 1 ) + z / ( c2 + t ) * ( i == 2 ) ) * ( x / ( 1. + t ) * ( j == 0 ) + y / ( b2 + t ) * ( j == ... |
def replay_config ( self , switch_ip ) :
"""Sends pending config data in OpenStack to Nexus .""" | LOG . debug ( "Replaying config for switch ip %(switch_ip)s" , { 'switch_ip' : switch_ip } )
# Before replaying all config , initialize trunk interfaces
# to none as required . If this fails , the switch may not
# be up all the way . Quit and retry later .
try :
self . _initialize_trunk_interfaces_to_none ( switch_... |
def _writeToTransport ( self , data ) :
'''Frame the array - like thing and write it .''' | self . transport . writeData ( data )
self . heartbeater . schedule ( ) |
def uniform_random_global_points ( n = 100 ) :
"""Returns an array of ` n ` uniformally distributed ` shapely . geometry . Point ` objects . Points are coordinates
distributed equivalently across the Earth ' s surface .""" | xs = np . random . uniform ( - 180 , 180 , n )
ys = np . random . uniform ( - 90 , 90 , n )
return [ shapely . geometry . Point ( x , y ) for x , y in zip ( xs , ys ) ] |
def main ( * args ) :
"""Enter point .""" | args = args or sys . argv [ 1 : ]
params = PARSER . parse_args ( args )
from . log import setup_logging
setup_logging ( params . level . upper ( ) )
from . core import Starter
starter = Starter ( params )
if not starter . params . TEMPLATES or starter . params . list :
setup_logging ( 'WARN' )
for t in sorted (... |
def codebox ( msg = "" , title = " " , text = "" ) :
"""Display some text in a monospaced font , with no line wrapping .
This function is suitable for displaying code and text that is
formatted using spaces .
The text parameter should be a string , or a list or tuple of lines to be
displayed in the textbox ... | return tb . textbox ( msg , title , text , codebox = 1 ) |
def _detect_loop ( self ) :
"""detect loops in flow table , raise error if being present""" | for source , dests in self . flowtable . items ( ) :
if source in dests :
raise conferr ( 'Loops detected: %s --> %s' % ( source , source ) ) |
def _set_gre_ttl ( self , v , load = False ) :
"""Setter method for gre _ ttl , mapped from YANG variable / interface / tunnel / gre _ ttl ( uint32)
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ gre _ ttl is considered as a private
method . Backends looking to popul... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = RestrictedClassType ( base_type = long , restriction_dict = { 'range' : [ '0..4294967295' ] } , int_size = 32 ) , restriction_dict = { 'range' : [ u'1 .. 255' ] } ) , is_leaf = True , yang_na... |
def make_worker_pool ( processes = None , initializer = None , initializer_kwargs_per_process = None , max_tasks_per_worker = None ) :
"""Convenience wrapper to create a multiprocessing . Pool .
This function adds support for per - worker initializer arguments , which are
not natively supported by the multiproc... | if not processes :
processes = cpu_count ( )
pool_kwargs = { 'processes' : processes , }
if max_tasks_per_worker :
pool_kwargs [ "maxtasksperchild" ] = max_tasks_per_worker
if initializer :
if initializer_kwargs_per_process :
assert len ( initializer_kwargs_per_process ) == processes
kwargs_... |
def return_hdr ( self ) :
"""Return the header for further use .
Returns
subj _ id : str
subject identification code
start _ time : datetime
start time of the dataset
s _ freq : float
sampling frequency
chan _ name : list of str
list of all the channels
n _ samples : int
number of samples in t... | orig = { }
orig = _read_header ( self . filename )
nchan = int ( orig [ 'SourceCh' ] )
chan_name = [ 'ch{:03d}' . format ( i + 1 ) for i in range ( nchan ) ]
chan_dtype = dtype ( orig [ 'DataFormat' ] )
self . statevector_len = int ( orig [ 'StatevectorLen' ] )
s_freq = orig [ 'Parameter' ] [ 'SamplingRate' ]
if s_freq... |
def add_arguments ( self , parser ) :
"""Entry point for subclassed commands to add custom arguments .""" | subparsers = parser . add_subparsers ( help = 'sub-command help' , dest = 'command' )
add_parser = partial ( _add_subparser , subparsers , parser )
add_parser ( 'list' , help = "list concurrency triggers" )
add_parser ( 'drop' , help = "drop concurrency triggers" )
add_parser ( 'create' , help = "create concurrency tr... |
def distances ( self , points ) :
"""Computes the distances from the plane to each of the points . Positive distances are on the side of the
normal of the plane while negative distances are on the other side
: param points : Points for which distances are computed
: return : Distances from the plane to the po... | return [ np . dot ( self . normal_vector , pp ) + self . d for pp in points ] |
def import_lv_load_areas ( self , session , mv_grid_district , lv_grid_districts , lv_stations ) :
"""Imports load _ areas ( load areas ) from database for a single MV grid _ district
Parameters
session : sqlalchemy . orm . session . Session
Database session
mv _ grid _ district : MV grid _ district / stati... | # get ding0s ' standard CRS ( SRID )
srid = str ( int ( cfg_ding0 . get ( 'geo' , 'srid' ) ) )
# SET SRID 3035 to achieve correct area calculation of lv _ grid _ district
# srid = ' 3035'
# threshold : load area peak load , if peak load < threshold = > disregard
# load area
lv_loads_threshold = cfg_ding0 . get ( 'mv_ro... |
def add_clients ( session , verbose ) :
"""Add clients to the ATVS Keystroke database .""" | for ctype in [ 'Genuine' , 'Impostor' ] :
for cdid in userid_clients :
cid = ctype + '_%d' % cdid
if verbose > 1 :
print ( " Adding user '%s' of type '%s'..." % ( cid , ctype ) )
session . add ( Client ( cid , ctype , cdid ) ) |
def remove_stage_from_deployed_values ( key , filename ) : # type : ( str , str ) - > None
"""Delete a top level key from the deployed JSON file .""" | final_values = { }
# type : Dict [ str , Any ]
try :
with open ( filename , 'r' ) as f :
final_values = json . load ( f )
except IOError : # If there is no file to delete from , then this funciton is a noop .
return
try :
del final_values [ key ]
with open ( filename , 'wb' ) as f :
data... |
def atomic ( connection_name : Optional [ str ] = None ) -> Callable :
"""Transaction decorator .
You can wrap your function with this decorator to run it into one transaction .
If error occurs transaction will rollback .
: param connection _ name : name of connection to run with , optional if you have only
... | def wrapper ( func ) :
@ wraps ( func )
async def wrapped ( * args , ** kwargs ) :
connection = _get_connection ( connection_name )
async with connection . _in_transaction ( ) :
return await func ( * args , ** kwargs )
return wrapped
return wrapper |
def _pipeline_needs_fastq ( config , data ) :
"""Determine if the pipeline can proceed with a BAM file , or needs fastq conversion .""" | aligner = config [ "algorithm" ] . get ( "aligner" )
support_bam = aligner in alignment . metadata . get ( "support_bam" , [ ] )
return aligner and not support_bam |
def v_reference_choice ( ctx , stmt ) :
"""Make sure that the default case exists""" | d = stmt . search_one ( 'default' )
if d is not None :
m = stmt . search_one ( 'mandatory' )
if m is not None and m . arg == 'true' :
err_add ( ctx . errors , stmt . pos , 'DEFAULT_AND_MANDATORY' , ( ) )
ptr = attrsearch ( d . arg , 'arg' , stmt . i_children )
if ptr is None :
err_add ( ... |
def _updateTargetFromNode ( self ) :
"""Applies the configuration to the target axis it monitors .
The axis label will be set to the configValue . If the configValue equals
PgAxisLabelCti . NO _ LABEL , the label will be hidden .""" | rtiInfo = self . collector . rtiInfo
self . plotItem . setLabel ( self . axisPosition , self . configValue . format ( ** rtiInfo ) )
self . plotItem . showLabel ( self . axisPosition , self . configValue != self . NO_LABEL ) |
def set_computer_name ( name ) :
'''Set the computer name
: param str name : The new computer name
: return : True if successful , False if not
: rtype : bool
CLI Example :
. . code - block : : bash
salt ' * ' system . set _ computer _ name " Mike ' s Mac "''' | cmd = 'systemsetup -setcomputername "{0}"' . format ( name )
__utils__ [ 'mac_utils.execute_return_success' ] ( cmd )
return __utils__ [ 'mac_utils.confirm_updated' ] ( name , get_computer_name , ) |
def write ( self , basename = None , write_separate_manifests = True ) :
"""Write one or more dump files to complete this dump .
Returns the number of dump / archive files written .""" | self . check_files ( )
n = 0
for manifest in self . partition_dumps ( ) :
dumpbase = "%s%05d" % ( basename , n )
dumpfile = "%s.%s" % ( dumpbase , self . format )
if ( write_separate_manifests ) :
manifest . write ( basename = dumpbase + '.xml' )
if ( self . format == 'zip' ) :
self . wr... |
def evaluate_js ( script , uid = 'master' ) :
"""Evaluate given JavaScript code and return the result
: param script : The JavaScript code to be evaluated
: param uid : uid of the target instance
: return : Return value of the evaluated code""" | escaped_script = 'JSON.stringify(eval("{0}"))' . format ( escape_string ( script ) )
return gui . evaluate_js ( escaped_script , uid ) |
def rsdl_sn ( self , U ) :
"""Compute dual residual normalisation term .
Overriding this method is required if methods : meth : ` cnst _ A ` ,
: meth : ` cnst _ AT ` , : meth : ` cnst _ B ` , and : meth : ` cnst _ c ` are not
overridden .""" | return self . rho * np . linalg . norm ( self . cnst_AT ( U ) ) |
def scrypt ( password , salt , N = SCRYPT_N , r = SCRYPT_r , p = SCRYPT_p , olen = 64 ) :
"""Returns a key derived using the scrypt key - derivarion function
N must be a power of two larger than 1 but no larger than 2 * * 63 ( insane )
r and p must be positive numbers such that r * p < 2 * * 30
The default va... | check_args ( password , salt , N , r , p , olen )
if _scrypt_ll :
out = ctypes . create_string_buffer ( olen )
if _scrypt_ll ( password , len ( password ) , salt , len ( salt ) , N , r , p , out , olen ) :
raise ValueError
return out . raw
if len ( salt ) != _scrypt_salt or r != 8 or ( p & ( p - 1 )... |
def on_view_not_found ( self , environ : Dict [ str , Any ] , start_response : Callable ) -> Iterable [ bytes ] : # pragma : nocover
"""called when view is not found""" | raise NotImplementedError ( ) |
def read_candidates ( candsfile , snrmin = 0 , snrmax = 999 , returnstate = False ) :
"""Reads candidate file and returns data as python object .
candsfile is pkl file ( for now ) with ( 1 ) state dict and ( 2 ) cands object .
cands object can either be a dictionary or tuple of two numpy arrays .
Return tuple... | # read in pickle file of candidates
assert os . path . exists ( candsfile )
try :
with open ( candsfile , 'rb' ) as pkl :
d = pickle . load ( pkl )
cands = pickle . load ( pkl )
except IOError :
logger . error ( 'Trouble parsing candsfile' )
loc = np . array ( [ ] )
prop = np . array ( [... |
def start_task ( self , func ) :
"""Start up a task""" | task = self . loop . create_task ( func ( self ) )
self . _started_tasks . append ( task )
def done_callback ( done_task ) :
self . _started_tasks . remove ( done_task )
task . add_done_callback ( done_callback )
return task |
def horizontals ( self ) :
"""All horizontal squares from the piece ' s point of view .
Returns a list of relative movements up to the board ' s bound .""" | horizontal_shifts = set ( izip_longest ( map ( lambda i : i - self . x , range ( self . board . length ) ) , [ ] , fillvalue = 0 ) )
horizontal_shifts . discard ( ( 0 , 0 ) )
return horizontal_shifts |
def prior_GP_var_inv_gamma ( y_invK_y , n_y , tau_range ) :
"""Imposing an inverse - Gamma prior onto the variance ( tau ^ 2)
parameter of a Gaussian Process , which is in turn a prior
imposed over an unknown function y = f ( x ) .
The inverse - Gamma prior of tau ^ 2 , tau ^ 2 ~ invgamma ( shape , scale )
... | alpha = 2
tau2 = ( y_invK_y + 2 * tau_range ** 2 ) / ( alpha * 2 + 2 + n_y )
log_ptau = scipy . stats . invgamma . logpdf ( tau2 , scale = tau_range ** 2 , a = 2 )
return tau2 , log_ptau |
def handle ( self , * args , ** options ) : # NoQA
"""Execute the command .""" | # Load the settings
self . require_settings ( args , options )
# Load your AWS credentials from ~ / . aws / credentials
self . load_credentials ( )
# Get the Django settings file
self . get_django_settings_file ( )
# Make sure the necessary IAM execution roles are available
self . zappa . create_iam_roles ( )
# Create ... |
def create_output ( stdout = None , true_color = False , ansi_colors_only = None ) :
"""Return an : class : ` ~ prompt _ toolkit . output . Output ` instance for the command
line .
: param true _ color : When True , use 24bit colors instead of 256 colors .
( ` bool ` or : class : ` ~ prompt _ toolkit . filter... | stdout = stdout or sys . __stdout__
true_color = to_simple_filter ( true_color )
if is_windows ( ) :
if is_conemu_ansi ( ) :
return ConEmuOutput ( stdout )
else :
return Win32Output ( stdout )
else :
term = os . environ . get ( 'TERM' , '' )
if PY2 :
term = term . decode ( 'utf-8... |
def create ( example ) :
"""Create a copy of the given example .""" | try :
this_dir = os . path . dirname ( os . path . realpath ( __file__ ) )
example_dir = os . path . join ( this_dir , os . pardir , "examples" , example )
shutil . copytree ( example_dir , os . path . join ( os . getcwd ( ) , example ) )
log ( "Example created." , delay = 0 )
except TypeError :
cli... |
def change_default_radii ( def_map ) :
"""Change the default radii""" | s = current_system ( )
rep = current_representation ( )
rep . radii_state . default = [ def_map [ t ] for t in s . type_array ]
rep . radii_state . reset ( ) |
def add ( self , * destinations ) :
"""Adds new destinations .
A destination should never ever throw an exception . Seriously .
A destination should not mutate the dictionary it is given .
@ param destinations : A list of callables that takes message
dictionaries .""" | buffered_messages = None
if not self . _any_added : # These are first set of messages added , so we need to clear
# BufferingDestination :
self . _any_added = True
buffered_messages = self . _destinations [ 0 ] . messages
self . _destinations = [ ]
self . _destinations . extend ( destinations )
if buffered_... |
def types ( ** typefuncs ) :
"""Decorate a function that takes strings to one that takes typed values .
The decorator ' s arguments are functions to perform type conversion .
The positional and keyword arguments will be mapped to the positional and
keyword arguments of the decoratored function . This allows w... | def wrap ( f ) :
@ functools . wraps ( f )
def typed_func ( * pargs , ** kwargs ) : # Analyze the incoming arguments so we know how to apply the
# type - conversion functions in ` typefuncs ` .
argspec = inspect . getargspec ( f )
# The ` args ` property contains the list of named arguments ... |
def main ( ) :
"""Start main part of the wait script .""" | logger . info ( 'Waiting for database: `%s`' , MYSQL_DB )
connect_mysql ( host = MYSQL_HOST , port = MYSQL_PORT , user = MYSQL_USER , password = MYSQL_PASSWORD , database = MYSQL_DB )
logger . info ( 'Database `%s` found' , MYSQL_DB ) |
def index ( environment , start_response , headers ) :
"""Return the status of this Kronos instance + its backends >
Doesn ' t expect any URL parameters .""" | response = { 'service' : 'kronosd' , 'version' : kronos . __version__ , 'id' : settings . node [ 'id' ] , 'storage' : { } , SUCCESS_FIELD : True }
# Check if each backend is alive
for name , backend in router . get_backends ( ) :
response [ 'storage' ] [ name ] = { 'alive' : backend . is_alive ( ) , 'backend' : set... |
def unblock_signals ( self ) :
"""Let the combos listen for event changes again .""" | self . aggregation_layer_combo . blockSignals ( False )
self . exposure_layer_combo . blockSignals ( False )
self . hazard_layer_combo . blockSignals ( False ) |
def connect ( self ) -> "google.cloud.storage.Bucket" :
"""Connect to the assigned bucket .""" | log = self . _log
log . info ( "Connecting to the bucket..." )
client = self . create_client ( )
return client . lookup_bucket ( self . bucket_name ) |
def lcs_logs ( ) :
"""Pull Retrosheet LCS Game Logs""" | file_name = 'GLLC.TXT'
z = get_zip_file ( lcs_url )
data = pd . read_csv ( z . open ( file_name ) , header = None , sep = ',' , quotechar = '"' )
data . columns = gamelog_columns
return data |
def find_matches ( self , content , file_to_handle ) :
"""Find all matches of an expression in a file""" | # look for all match groups in the content
groups = [ match . groupdict ( ) for match in self . match_expression . finditer ( content ) ]
# filter out content not in the matchgroup
matches = [ group [ 'matchgroup' ] for group in groups if group . get ( 'matchgroup' ) ]
logger . info ( 'Found %s matches in %s' , len ( m... |
def make_directory ( path ) :
"""Make a directory and any intermediate directories that don ' t already
exist . This function handles the case where two threads try to create
a directory at once .""" | if not os . path . exists ( path ) : # concurrent writes that try to create the same dir can fail
try :
os . makedirs ( path )
except OSError as e :
if e . errno == errno . EEXIST :
pass
else :
raise e |
def __list_updates ( update_type , update_list ) :
"""Function used to list package updates by update type in console
: param update _ type : string
: param update _ list : list""" | if len ( update_list ) :
print ( " %s:" % update_type )
for update_item in update_list :
print ( " -- %(version)s on %(upload_time)s" % update_item ) |
async def delete_lease_async ( self , lease ) :
"""Delete the lease info for the given partition from the store .
If there is no stored lease for the given partition , that is treated as success .
: param lease : The stored lease to be deleted .
: type lease : ~ azure . eventprocessorhost . lease . Lease""" | await self . host . loop . run_in_executor ( self . executor , functools . partial ( self . storage_client . delete_blob , self . lease_container_name , lease . partition_id , lease_id = lease . token ) ) |
def invoke_shell ( self , locs , banner ) :
"""Invokes the appropriate flavor of the python shell .
Falls back on the native python shell if the requested
flavor ( ipython , bpython , etc ) is not installed .""" | shell = self . SHELLS [ self . args . shell ]
try :
shell ( ) . invoke ( locs , banner )
except ImportError as e :
warn ( ( "%s is not installed, `%s`, " "falling back to native shell" ) % ( self . args . shell , e ) , RuntimeWarning )
if shell == NativePythonShell :
raise
NativePythonShell ( ) ... |
def parse_db_url ( db_url ) :
"""provided a db url , return a dict with connection properties""" | u = urlparse ( db_url )
db = { }
db [ "database" ] = u . path [ 1 : ]
db [ "user" ] = u . username
db [ "password" ] = u . password
db [ "host" ] = u . hostname
db [ "port" ] = u . port
return db |
def remove_handler ( self , handler : Handler , group : int = 0 ) :
"""Removes a previously - added update handler .
Make sure to provide the right group that the handler was added in . You can use
the return value of the : meth : ` add _ handler ` method , a tuple of ( handler , group ) , and
pass it directl... | if isinstance ( handler , DisconnectHandler ) :
self . disconnect_handler = None
else :
self . dispatcher . remove_handler ( handler , group ) |
def send_scp ( self , * args , ** kwargs ) :
"""Transmit an SCP Packet and return the response .
This function is a thin wrapper around
: py : meth : ` rig . machine _ control . scp _ connection . SCPConnection . send _ scp ` .
This function will attempt to use the SCP connection nearest the
destination of ... | # Retrieve contextual arguments from the keyword arguments . The
# context system ensures that these values are present .
x = kwargs . pop ( "x" )
y = kwargs . pop ( "y" )
p = kwargs . pop ( "p" )
return self . _send_scp ( x , y , p , * args , ** kwargs ) |
def lookup_object ( model , object_id , slug , slug_field ) :
"""Return the ` ` model ` ` object with the passed ` ` object _ id ` ` . If
` ` object _ id ` ` is None , then return the object whose ` ` slug _ field ` `
equals the passed ` ` slug ` ` . If ` ` slug ` ` and ` ` slug _ field ` ` are not passed ,
t... | lookup_kwargs = { }
if object_id :
lookup_kwargs [ '%s__exact' % model . _meta . pk . name ] = object_id
elif slug and slug_field :
lookup_kwargs [ '%s__exact' % slug_field ] = slug
else :
raise GenericViewError ( "Generic view must be called with either an object_id or a" " slug/slug_field." )
try :
re... |
def split_window ( self , attach = False , vertical = True , start_directory = None ) :
"""Split window at pane and return newly created : class : ` Pane ` .
Parameters
attach : bool , optional
Attach / select pane after creation .
vertical : bool , optional
split vertically
start _ directory : str , op... | return self . window . split_window ( target = self . get ( 'pane_id' ) , start_directory = start_directory , attach = attach , vertical = vertical , ) |
def replace ( doc , pointer , value ) :
"""Replace element from sequence , member from mapping .
: param doc : the document base
: param pointer : the path to search in
: param value : the new value
: return : the new object
. . note : :
This operation is functionally identical to a " remove " operation... | return Target ( doc ) . replace ( pointer , value ) . document |
def duration ( self ) :
"""Queries the duration of the call .
If the call has not ended then the current duration will
be returned .
Returns
datetime . timedelta
The timedelta object representing the duration .""" | if self . ended_timestamp is None :
return datetime . datetime . utcnow ( ) - self . message . created_at
else :
return self . ended_timestamp - self . message . created_at |
def evaluate ( ref_intervals , ref_labels , est_intervals , est_labels , ** kwargs ) :
"""Computes weighted accuracy for all comparison functions for the given
reference and estimated annotations .
Examples
> > > ( ref _ intervals ,
. . . ref _ labels ) = mir _ eval . io . load _ labeled _ intervals ( ' ref... | # Append or crop estimated intervals so their span is the same as reference
est_intervals , est_labels = util . adjust_intervals ( est_intervals , est_labels , ref_intervals . min ( ) , ref_intervals . max ( ) , NO_CHORD , NO_CHORD )
# use merged intervals for segmentation evaluation
merged_ref_intervals = merge_chord_... |
def startup_config_content ( self ) :
"""Returns the content of the current startup - config file .""" | config_file = self . startup_config_file
if config_file is None :
return None
try :
with open ( config_file , "rb" ) as f :
return f . read ( ) . decode ( "utf-8" , errors = "replace" )
except OSError as e :
raise IOUError ( "Can't read startup-config file '{}': {}" . format ( config_file , e ) ) |
def consecutive_frame ( self ) :
"""Return a DataFrame with columns cnt , pids , pl . cnt is the number of pids in the sequence . pl is the pl sum""" | if self . _frame . empty :
return pd . DataFrame ( columns = [ 'pids' , 'pl' , 'cnt' , 'is_win' ] )
else :
vals = ( self . _frame [ PC . RET ] >= 0 ) . astype ( int )
seq = ( vals . shift ( 1 ) != vals ) . astype ( int ) . cumsum ( )
def _do_apply ( sub ) :
return pd . Series ( { 'pids' : sub . ... |
def AddFiles ( self , hash_id_metadatas ) :
"""Adds multiple files to the file store .
Args :
hash _ id _ metadatas : A dictionary mapping hash ids to file metadata ( a tuple
of hash client path and blob references ) .""" | for hash_id , metadata in iteritems ( hash_id_metadatas ) :
self . AddFile ( hash_id , metadata ) |
def parse_events ( cls , ev_args , parent_ctx ) :
"""Capture the events sent to : meth : ` . XSO . parse _ events ` ,
including the initial ` ev _ args ` to a list and call
: meth : ` _ set _ captured _ events ` on the result of
: meth : ` . XSO . parse _ events ` .
Like the method it overrides , : meth : `... | dest = [ ( "start" , ) + tuple ( ev_args ) ]
result = yield from capture_events ( super ( ) . parse_events ( ev_args , parent_ctx ) , dest )
result . _set_captured_events ( dest )
return result |
def cli ( env , package_keyname , location , preset , verify , billing , complex_type , quantity , extras , order_items ) :
"""Place or verify an order .
This CLI command is used for placing / verifying an order of the specified package in
the given location ( denoted by a datacenter ' s long name ) . Orders ma... | manager = ordering . OrderingManager ( env . client )
if extras :
try :
extras = json . loads ( extras )
except ValueError as err :
raise exceptions . CLIAbort ( "There was an error when parsing the --extras value: {}" . format ( err ) )
args = ( package_keyname , location , order_items )
kwargs... |
def orientation ( self , value ) :
'''setter of orientation property .''' | for values in self . __orientation :
if value in values : # can not set upside - down until api level 18.
self . server . jsonrpc . setOrientation ( values [ 1 ] )
break
else :
raise ValueError ( "Invalid orientation." ) |
def determine_encoding ( buf ) :
"""Return the appropriate encoding for the given CSS source , according to
the CSS charset rules .
` buf ` may be either a string or bytes .""" | # The ultimate default is utf8 ; bravo , W3C
bom_encoding = 'UTF-8'
if not buf : # What
return bom_encoding
if isinstance ( buf , six . text_type ) : # We got a file that , for whatever reason , produces already - decoded
# text . Check for the BOM ( which is useless now ) and believe
# whatever ' s in the @ charse... |
def create_token ( key , payload ) :
"""Auth token generator
payload should be a json encodable data structure""" | token = hmac . new ( key )
token . update ( json . dumps ( payload ) )
return token . hexdigest ( ) |
def register ( name ) :
"""Return a decorator that registers the decorated class as a
resolver with the given * name * .""" | def decorator ( class_ ) :
if name in known_resolvers :
raise ValueError ( 'duplicate resolver name "%s"' % name )
known_resolvers [ name ] = class_
return decorator |
def transformer_ae_small_noatt ( ) :
"""Set of hyperparameters .""" | hparams = transformer_ae_small ( )
hparams . reshape_method = "slice"
hparams . bottleneck_kind = "dvq"
hparams . hidden_size = 512
hparams . num_blocks = 1
hparams . num_decode_blocks = 1
hparams . z_size = 12
hparams . do_attend_decompress = False
return hparams |
def __insert_data ( postid , userid , rating ) :
'''Inert new record .''' | uid = tools . get_uuid ( )
TabRating . create ( uid = uid , post_id = postid , user_id = userid , rating = rating , timestamp = tools . timestamp ( ) , )
return uid |
def _login ( self , failed = False ) :
"""Login prompt""" | if failed :
content = self . LOGIN_TEMPLATE . format ( failed_message = "Login failed" )
else :
content = self . LOGIN_TEMPLATE . format ( failed_message = "" )
return "200 OK" , content , { "Content-Type" : "text/html" } |
def _get_archive_listing ( self , archive_name ) :
'''Return full document for ` ` { _ id : ' archive _ name ' } ` `
. . note : :
MongoDB specific results - do not expose to user''' | res = self . collection . find_one ( { '_id' : archive_name } )
if res is None :
raise KeyError
return res |
def feincms_render_region ( context , feincms_object , region , request = None , classes = '' , wrapper = True ) :
"""{ % feincms _ render _ region feincms _ page " main " request % }
Support for rendering Page without some regions especialy for modals
this feature is driven by context variable""" | if not feincms_object :
return ''
if not context . get ( 'standalone' , False ) or region in STANDALONE_REGIONS :
region_content = '' . join ( _render_content ( content , request = request , context = context ) for content in getattr ( feincms_object . content , region ) )
else :
region_content = ''
if not ... |
def getattr ( self , path , fh ) :
"""Called by FUSE when the attributes for a file or directory are required .
Returns a dictionary with keys identical to the stat C structure of stat ( 2 ) .
st _ atime , st _ mtime and st _ ctime should be floats . On OSX , st _ nlink should count
all files inside the direc... | self . _raise_error_if_os_special_file ( path )
# log . debug ( u ' getattr ( ) : { 0 } ' . format ( path ) )
attribute = self . _get_attributes_through_cache ( path )
# log . debug ( ' getattr ( ) returned attribute : { 0 } ' . format ( attribute ) )
return self . _stat_from_attributes ( attribute ) |
def check_port ( helper , port ) :
"""check if the port parameter is really a port or " scan " """ | try :
int ( port )
except ValueError :
helper . exit ( summary = "Port (-p) must be a integer value." , exit_code = unknown , perfdata = '' ) |
def get_for_control_var_and_eval_expr ( comm_type , kwargs ) :
"""Returns tuple that consists of control variable name and iterable that is result
of evaluated expression of given for loop .
For example :
- given ' for $ i in $ ( echo " foo bar " ) ' it returns ( [ ' i ' ] , [ ' foo ' , ' bar ' ] )
- given ... | # let possible exceptions bubble up
control_vars , iter_type , expression = parse_for ( comm_type )
eval_expression = evaluate_expression ( expression , kwargs ) [ 1 ]
iterval = [ ]
if len ( control_vars ) == 2 :
if not isinstance ( eval_expression , dict ) :
raise exceptions . YamlSyntaxError ( 'Can\'t exp... |
def set_will ( self , topic , payload , qos = 0 , retain = False ) :
"""Sets up the will message
: param topic : Topic of the will message
: param payload : Content of the message
: param qos : Quality of Service
: param retain : The message will be retained
: raise ValueError : Invalid topic
: raise Ty... | self . __mqtt . will_set ( topic , payload , qos , retain = retain ) |
def replace ( self , key , initial_value , new_value ) :
"""Atomically replace the value of a key with a new value .
This compares the current value of a key , then replaces it with a new
value if it is equal to a specified value . This operation takes place
in a transaction .
: param key : key in etcd to r... | status , _ = self . transaction ( compare = [ self . transactions . value ( key ) == initial_value ] , success = [ self . transactions . put ( key , new_value ) ] , failure = [ ] , )
return status |
def set_title ( self , s , panel = 'top' ) :
"set plot title" | panel = self . get_panel ( panel )
panel . set_title ( s ) |
def continue_object ( self , workflow_object , restart_point = 'restart_task' , task_offset = 1 , stop_on_halt = False ) :
"""Continue workflow for one given object from " restart _ point " .
: param object :
: param stop _ on _ halt :
: param restart _ point : can be one of :
* restart _ prev : will restar... | translate = { 'restart_task' : 'current' , 'continue_next' : 'next' , 'restart_prev' : 'prev' , }
self . state . callback_pos = workflow_object . callback_pos or [ 0 ]
self . restart ( task = translate [ restart_point ] , obj = 'first' , objects = [ workflow_object ] , stop_on_halt = stop_on_halt ) |
def logical_or ( f1 , f2 ) : # function factory
'''Logical or from functions .
Parameters
f1 , f2 : function
Function that takes array and returns true or false for each item in array .
Returns
Function .''' | def f ( value ) :
return np . logical_or ( f1 ( value ) , f2 ( value ) )
f . __name__ = "(" + f1 . __name__ + "_or_" + f2 . __name__ + ")"
return f |
def sequence_length ( fasta ) :
"""return a dict of the lengths of sequences in a fasta file""" | sequences = SeqIO . parse ( fasta , "fasta" )
records = { record . id : len ( record ) for record in sequences }
return records |
def plot_sigma ( corpus , sigma , nodes = None , ** kwargs ) :
"""Plot sigma values for the ` ` topn ` ` most influential nodes .
Parameters
G : : class : ` . GraphCollection `
corpus : : class : ` . Corpus `
feature : str
Name of a featureset in ` corpus ` .
topn : int or float { 0 . - 1 . }
( defaul... | try :
import matplotlib . pyplot as plt
import matplotlib . patches as mpatches
except ImportError :
raise RuntimeError ( 'This method requires the package matplotlib.' )
if nodes == 'all' :
nodes = sigma . keys ( )
# Display parameters .
color = kwargs . get ( 'color' , 'red' )
years = sorted ( corpus ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.