signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def disconnect ( self ) :
"""This method disconnects an IOM session to allow for reconnecting when switching networks""" | if not self . sascfg . reconnect :
return "Disconnecting and then reconnecting to this workspaceserver has been disabled. Did not disconnect"
pgm = b'\n' + b'tom says EOL=DISCONNECT \n'
self . stdin [ 0 ] . send ( pgm )
while True :
try :
log = self . stderr [ 0 ] . recv ( 4096 ) . ... |
def _variants_fields ( fields , exclude_fields , info_ids ) :
"""Utility function to determine which fields to extract when loading
variants .""" | if fields is None : # no fields specified by user
# by default extract all standard and INFO fields
fields = config . STANDARD_VARIANT_FIELDS + info_ids
else : # fields have been specified
for f in fields : # check for non - standard fields not declared in INFO header
if f not in config . STANDARD_VARIA... |
def kogge_stone ( a , b , cin = 0 ) :
"""Creates a Kogge - Stone adder given two inputs
: param WireVector a , b : The two WireVectors to add up ( bitwidths don ' t need to match )
: param cin : An optimal carry in WireVector or value
: return : a Wirevector representing the output of the adder
The Kogge - ... | a , b = libutils . match_bitwidth ( a , b )
prop_orig = a ^ b
prop_bits = [ i for i in prop_orig ]
gen_bits = [ i for i in a & b ]
prop_dist = 1
# creation of the carry calculation
while prop_dist < len ( a ) :
for i in reversed ( range ( prop_dist , len ( a ) ) ) :
prop_old = prop_bits [ i ]
gen_bi... |
def transpose ( self , * args , ** kwargs ) :
"""Transposes this DataManager .
Returns :
Transposed new DataManager .""" | new_data = self . data . transpose ( * args , ** kwargs )
# Switch the index and columns and transpose the
new_manager = self . __constructor__ ( new_data , self . columns , self . index )
# It is possible that this is already transposed
new_manager . _is_transposed = self . _is_transposed ^ 1
return new_manager |
def insert_or_append ( parent , node , next_sibling ) :
"""Insert the node before next _ sibling . If next _ sibling is None , append the node last instead .""" | # simple insert
if next_sibling :
parent . insertBefore ( node , next_sibling )
else :
parent . appendChild ( node ) |
def _get_default_letters ( model_admin = None ) :
"""Returns the set of letters defined in the configuration variable
DEFAULT _ ALPHABET . DEFAULT _ ALPHABET can be a callable , string , tuple , or
list and returns a set .
If a ModelAdmin class is passed , it will look for a DEFAULT _ ALPHABET
attribute and... | from django . conf import settings
import string
default_ltrs = string . digits + string . ascii_uppercase
default_letters = getattr ( settings , 'DEFAULT_ALPHABET' , default_ltrs )
if model_admin and hasattr ( model_admin , 'DEFAULT_ALPHABET' ) :
default_letters = model_admin . DEFAULT_ALPHABET
if callable ( defau... |
def add_callback ( self , callback , msg_type = None ) :
"""Add per message type or global callback .
Parameters
callback : fn
Callback function
msg _ type : int | iterable
Message type to register callback against . Default ` None ` means global callback .
Iterable type adds the callback to all the mes... | cb_keys = self . _to_iter ( msg_type )
if cb_keys is not None :
for msg_type_ in cb_keys :
self . _callbacks [ msg_type_ ] . add ( callback )
else :
self . _callbacks [ msg_type ] . add ( callback ) |
def grant_member ( context , request ) :
"""Grant member roles in the group .""" | mapping = request . json [ 'mapping' ]
for entry in mapping :
user = entry [ 'user' ]
roles = entry [ 'roles' ]
username = user . get ( 'username' , None )
userid = user . get ( 'userid' , None )
if userid :
u = context . get_user_by_userid ( userid )
elif username :
u = context ... |
def _includes_base_class ( self , iter_classes , base_class ) :
"""Returns whether any class in iter _ class is a subclass of the given base _ class .""" | return any ( issubclass ( auth_class , base_class ) for auth_class in iter_classes , ) |
def main ( argString = None ) :
"""The main function .
The purpose of this module is to plot Eigenvectors provided by the
Eigensoft software .
Here are the steps of this module :
1 . Reads the Eigenvector ( : py : func : ` read _ eigenvalues ` ) .
2 . Plots the Scree Plot ( : py : func : ` create _ scree ... | # Getting and checking the options
args = parse_args ( argString )
check_args ( args )
# Reads the eigenvalues
eigenvalues = read_eigenvalues ( args . evec )
# Creates the plot
create_scree_plot ( eigenvalues , args . out , args ) |
def get_state ( self , site ) :
"""Read client status file and return dict .""" | parser = ConfigParser ( )
status_section = 'incremental'
parser . read ( self . status_file )
timestamp = None
try :
timestamp = float ( parser . get ( status_section , self . config_site_to_name ( site ) ) )
except NoSectionError as e :
pass
except NoOptionError as e :
pass
return ( timestamp ) |
def format_commands ( self , ctx , formatter ) :
"""Extra format methods for multi methods that adds all the commands
after the options .""" | commands = [ ]
for subcommand in self . list_commands ( ctx ) :
cmd = self . get_command ( ctx , subcommand )
# What is this , the tool lied about a command . Ignore it
if cmd is None :
continue
if cmd . hidden :
continue
commands . append ( ( subcommand , cmd ) )
# allow for 3 times... |
def _get_included_diff_results ( self ) :
"""Return a list of stages to be included in the diff results .""" | included = [ self . _git_diff_tool . diff_committed ( self . _compare_branch ) ]
if not self . _ignore_staged :
included . append ( self . _git_diff_tool . diff_staged ( ) )
if not self . _ignore_unstaged :
included . append ( self . _git_diff_tool . diff_unstaged ( ) )
return included |
def _after_request ( self , response ) :
"""Set a new ID token cookie if the ID token has changed .""" | # This means that if either the new or the old are False , we set
# insecure cookies .
# We don ' t define OIDC _ ID _ TOKEN _ COOKIE _ SECURE in init _ app , because we
# don ' t want people to find it easily .
cookie_secure = ( current_app . config [ 'OIDC_COOKIE_SECURE' ] and current_app . config . get ( 'OIDC_ID_TO... |
def Chisholm_voidage ( x , rhol , rhog ) :
r'''Calculates void fraction in two - phase flow according to the model of
[1 ] _ , as given in [ 2 ] _ and [ 3 ] _ .
. . math : :
\ alpha = \ left [ 1 + \ left ( \ frac { 1 - x } { x } \ right ) \ left ( \ frac { \ rho _ g }
{ \ rho _ l } \ right ) \ sqrt { 1 - x ... | S = ( 1 - x * ( 1 - rhol / rhog ) ) ** 0.5
alpha = ( 1 + ( 1 - x ) / x * rhog / rhol * S ) ** - 1
return alpha |
def init ( deb1 , deb2 = False ) :
"""Initialize DEBUG and DEBUGALL .
Allows other modules to set DEBUG and DEBUGALL , so their
call to dprint or dprintx generate output .
Args :
deb1 ( bool ) : value of DEBUG to set
deb2 ( bool ) : optional - value of DEBUGALL to set ,
defaults to False .""" | global DEBUG
# pylint : disable = global - statement
global DEBUGALL
# pylint : disable = global - statement
DEBUG = deb1
DEBUGALL = deb2 |
def __check_hash ( self , message ) :
"""return true / false if hash is good
message = dict""" | return message [ W_HASH ] == self . __make_hash ( message [ W_MESSAGE ] , self . __token , message [ W_SEQ ] ) |
def start_dev_session ( self ) :
"""Start a client that attempts to connect to the dev server
running on the host ` app . dev `""" | try :
from . dev import DevServerSession
session = DevServerSession . initialize ( host = self . dev )
session . start ( )
# : Save a reference
self . _dev_session = session
except :
self . show_error ( traceback . format_exc ( ) ) |
def lifetime_report ( args , parser ) :
"""Generates a lifetime report .""" | catalogue = utils . get_catalogue ( args )
tokenizer = utils . get_tokenizer ( args )
results = tacl . Results ( args . results , tokenizer )
output_dir = os . path . abspath ( args . output )
os . makedirs ( output_dir , exist_ok = True )
report = tacl . LifetimeReport ( )
report . generate ( output_dir , catalogue , ... |
def _insertLayer ( self , layer , name , ** kwargs ) :
"""This is the environment implementation of : meth : ` BaseFont . insertLayer ` .
This must return an instance of a : class : ` BaseLayer ` subclass .
* * layer * * will be a layer object with the attributes necessary
for copying as defined in : meth : `... | if name != layer . name and layer . name in self . layerOrder :
layer = layer . copy ( )
layer . name = name
dest = self . newLayer ( name )
dest . copyData ( layer )
return dest |
def edit ( directory = None , revision = 'current' ) :
"""Edit current revision .""" | if alembic_version >= ( 0 , 8 , 0 ) :
config = current_app . extensions [ 'migrate' ] . migrate . get_config ( directory )
command . edit ( config , revision )
else :
raise RuntimeError ( 'Alembic 0.8.0 or greater is required' ) |
def maps_get_rules_input_rbridge_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
maps_get_rules = ET . Element ( "maps_get_rules" )
config = maps_get_rules
input = ET . SubElement ( maps_get_rules , "input" )
rbridge_id = ET . SubElement ( input , "rbridge-id" )
rbridge_id . text = kwargs . pop ( 'rbridge_id' )
callback = kwargs . pop ( 'callback' , self . _callba... |
def crack ( ciphertext , * fitness_functions , ntrials = 30 , nswaps = 3000 ) :
"""Break ` ` ciphertext ` ` using hill climbing .
Note :
Currently ntrails and nswaps default to magic numbers .
Generally the trend is , the longer the text , the lower the number of trials
you need to run , because the hill cl... | if ntrials <= 0 or nswaps <= 0 :
raise ValueError ( "ntrials and nswaps must be positive integers" )
# Find a local maximum by swapping two letters and scoring the decryption
def next_node_inner_climb ( node ) : # Swap 2 characters in the key
a , b = random . sample ( range ( len ( node ) ) , 2 )
node [ a ]... |
def savepoint ( self ) :
"""Copies the last displayed image .""" | if self . _last_image :
self . _savepoints . append ( self . _last_image )
self . _last_image = None |
def date ( fmt = None , timestamp = None ) :
"Manejo de fechas ( simil PHP )" | if fmt == 'U' : # return timestamp
t = datetime . datetime . now ( )
return int ( time . mktime ( t . timetuple ( ) ) )
if fmt == 'c' : # return isoformat
d = datetime . datetime . fromtimestamp ( timestamp )
return d . isoformat ( )
if fmt == 'Ymd' :
d = datetime . datetime . now ( )
return d .... |
def callgraph ( G , stmt_list ) :
"""Build callgraph of func _ list , ignoring
built - in functions""" | func_list = [ ]
for stmt in stmt_list :
try :
G . add_node ( stmt . head . ident . name )
func_list . append ( stmt )
except :
pass
for func in func_list :
assert isinstance ( func , node . function )
func_name = func . head . ident . name
# resolve . resolve ( func )
for... |
def _prnt_min_max_val ( var , text , verb ) :
r"""Print variable ; if more than three , just min / max , unless verb > 3.""" | if var . size > 3 :
print ( text , _strvar ( var . min ( ) ) , "-" , _strvar ( var . max ( ) ) , ":" , _strvar ( var . size ) , " [min-max; #]" )
if verb > 3 :
print ( " : " , _strvar ( var ) )
else :
print ( text , _strvar ( np . atleast_1d ( var ) ) ) |
def read_acceptance_fraction ( self , walkers = None ) :
"""Reads the acceptance fraction .
Parameters
walkers : ( list of ) int , optional
The walker index ( or a list of indices ) to retrieve . If None ,
samples from all walkers will be obtained .
Returns
array
Array of acceptance fractions with sha... | group = self . sampler_group + '/acceptance_fraction'
if walkers is None :
wmask = numpy . ones ( self . nwalkers , dtype = bool )
else :
wmask = numpy . zeros ( self . nwalkers , dtype = bool )
wmask [ walkers ] = True
return self [ group ] [ wmask ] |
def load_raw ( cls , model_fn , schema , * args , ** kwargs ) :
"""Loads a trained classifier from the raw Weka model format .
Must specify the model schema and classifier name , since
these aren ' t currently deduced from the model format .""" | c = cls ( * args , ** kwargs )
c . schema = schema . copy ( schema_only = True )
c . _model_data = open ( model_fn , 'rb' ) . read ( )
return c |
def _mm_pairwise ( n_items , data , params ) :
"""Inner loop of MM algorithm for pairwise data .""" | weights = exp_transform ( params )
wins = np . zeros ( n_items , dtype = float )
denoms = np . zeros ( n_items , dtype = float )
for winner , loser in data :
wins [ winner ] += 1.0
val = 1.0 / ( weights [ winner ] + weights [ loser ] )
denoms [ winner ] += val
denoms [ loser ] += val
return wins , denom... |
def _convert_to_unicode ( string ) :
"""This method should work with both Python 2 and 3 with the caveat
that they need to be compiled with wide unicode character support .
If there isn ' t wide unicode character support it ' ll blow up with a
warning .""" | codepoints = [ ]
for character in string . split ( '-' ) :
if character in BLACKLIST_UNICODE :
next
codepoints . append ( '\U{0:0>8}' . format ( character ) . decode ( 'unicode-escape' ) )
return codepoints |
def build_coordinate_families ( self , paired_aligns ) :
'''Given a stream of paired aligns , return a list of pairs that share
same coordinates ( coordinate family ) . Flushes families in progress
when any of :
a ) incoming right start > family end
b ) incoming chrom ! = current chrom
c ) incoming align ... | rightmost_start = None
current_chrom = None
def _new_coordinate ( pair ) :
return pair . right . reference_start != rightmost_start
def _new_chrom ( pair ) :
return current_chrom != pair . right . reference_name
for pair in paired_aligns :
if rightmost_start is None :
rightmost_start = pair . right ... |
def assert_valid_rule_class ( clazz ) :
"""Asserts that a given rule clazz is valid by checking a number of its properties :
- Rules must extend from LineRule or CommitRule
- Rule classes must have id and name string attributes .
The options _ spec is optional , but if set , it must be a list of gitlint Optio... | # Rules must extend from LineRule or CommitRule
if not ( issubclass ( clazz , rules . LineRule ) or issubclass ( clazz , rules . CommitRule ) ) :
msg = u"User-defined rule class '{0}' must extend from {1}.{2} or {1}.{3}"
raise UserRuleError ( msg . format ( clazz . __name__ , rules . CommitRule . __module__ , r... |
def kw_changelist_view ( self , request : HttpRequest , extra_context = None , ** kw ) :
"""Changelist view which allow key - value arguments .
: param request : HttpRequest
: param extra _ context : Extra context dict
: param kw : Key - value dict
: return : See changelist _ view ( )""" | return self . changelist_view ( request , extra_context ) |
def delete ( self , transport , robj , rw = None , r = None , w = None , dw = None , pr = None , pw = None , timeout = None ) :
"""delete ( robj , rw = None , r = None , w = None , dw = None , pr = None , pw = None , timeout = None )
Deletes an object from Riak .
. . note : : This request is automatically retri... | _validate_timeout ( timeout )
return transport . delete ( robj , rw = rw , r = r , w = w , dw = dw , pr = pr , pw = pw , timeout = timeout ) |
def run_shell ( args : dict ) -> int :
"""Run the shell sub command""" | if args . get ( 'project_directory' ) :
return run_batch ( args )
shell = CauldronShell ( )
if in_project_directory ( ) :
shell . cmdqueue . append ( 'open "{}"' . format ( os . path . realpath ( os . curdir ) ) )
shell . cmdloop ( )
return 0 |
def get_pipeline_stage ( self , pipeline_key , stage_key = None , sort_by = None ) :
'''Gets a list of one / all stage objects in a pipeline . Performs a single GET .
Args :
pipeline _ keykey for pipeline
stage _ key key for stage ( default : None i . e . ALL )
sort _ byin desc order by ' creationTimestamp ... | if not pipeline_key :
return requests . codes . bad_request , None
uri = '/' . join ( [ self . api_uri , self . pipelines_suffix , pipeline_key , self . stages_suffix ] )
if stage_key :
uri = '/' . join ( [ uri , stage_key ] )
if sort_by :
if sort_by in [ 'creationTimestamp' , 'lastUpdatedTimestamp' ] :
... |
def relax_AX ( self ) :
"""Implement relaxation if option ` ` RelaxParam ` ` ! = 1.0.""" | # We need to keep the non - relaxed version of AX since it is
# required for computation of primal residual r
self . AXnr = self . cnst_A ( self . X , self . Xf )
if self . rlx == 1.0 : # If RelaxParam option is 1.0 there is no relaxation
self . AX = self . AXnr
else : # Avoid calling cnst _ c ( ) more than once in... |
def open ( self , auto_commit = None , schema = None ) :
'''Create a context to execute queries''' | if schema is None :
schema = self . schema
ac = auto_commit if auto_commit is not None else schema . auto_commit
exe = ExecutionContext ( self . path , schema = schema , auto_commit = ac )
# setup DB if required
if not os . path . isfile ( self . path ) or os . path . getsize ( self . path ) == 0 :
getLogger ( ... |
def next_page ( self ) :
"""Move the screen page down through the history buffer .""" | if self . history . position < self . history . size and self . history . bottom :
mid = min ( len ( self . history . bottom ) , int ( math . ceil ( self . lines * self . history . ratio ) ) )
self . history . top . extend ( self . buffer [ y ] for y in range ( mid ) )
self . history = self . history . _rep... |
def brightness ( im ) :
'''Return the brightness of an image
Args :
im ( numpy ) : image
Returns :
float , average brightness of an image''' | im_hsv = cv2 . cvtColor ( im , cv2 . COLOR_BGR2HSV )
h , s , v = cv2 . split ( im_hsv )
height , weight = v . shape [ : 2 ]
total_bright = 0
for i in v :
total_bright = total_bright + sum ( i )
return float ( total_bright ) / ( height * weight ) |
def apply_annotation ( self , bo , annotation ) :
"""Apply an annotation on the backend object .
: param BackendObject bo : The backend object .
: param Annotation annotation : The annotation to be applied
: return : A new BackendObject
: rtype : BackendObject""" | # Currently we only support RegionAnnotation
if not isinstance ( annotation , RegionAnnotation ) :
return bo
if not isinstance ( bo , ValueSet ) : # Convert it to a ValueSet first
# Note that the original value is not kept at all . If you want to convert a StridedInterval to a ValueSet ,
# you gotta do the conversi... |
def subscribe_topic ( self , topics = [ ] , pattern = None ) :
"""Subscribe to a list of topics , or a topic regex pattern .
- ` ` topics ` ` ( list ) : List of topics for subscription .
- ` ` pattern ` ` ( str ) : Pattern to match available topics . You must provide either topics or pattern ,
but not both ."... | if not isinstance ( topics , list ) :
topics = [ topics ]
self . consumer . subscribe ( topics , pattern = pattern ) |
def _evaluate_xyz ( self , x , y , z ) :
"""Evaluation of the potential as a function of ( x , y , z ) in the
aligned coordinate frame""" | return 2. * numpy . pi * self . _b * self . _c * _potInt ( x , y , z , self . _psi , self . _b2 , self . _c2 , glx = self . _glx , glw = self . _glw ) |
def step_impl11 ( context , runs ) :
"""Execute multiple runs .
: param runs : number of test runs to perform .
: param context : test context .""" | executor = context . fuzz_executor
executor . run_test ( runs )
stats = executor . stats
count = stats . cumulated_counts ( )
assert count == runs , "VERIFY: stats available." |
def _compose_mro ( cls , types ) : # noqa
"""Calculates the method resolution order for a given class * cls * .
Includes relevant abstract base classes ( with their respective bases ) from
the * types * iterable . Uses a modified C3 linearization algorithm .""" | bases = set ( cls . __mro__ )
# Remove entries which are already present in the _ _ mro _ _ or unrelated .
def is_related ( _type ) :
return ( # : off
_type not in bases and hasattr ( _type , '__mro__' ) and issubclass ( cls , _type ) )
# : on
types = [ n for n in types if is_related ( n ) ]
# Remove entries wh... |
def calc_signal ( self , ff , t = None , ani = None , fkwdargs = { } , Brightness = True , res = 0.005 , DL = None , resMode = 'abs' , method = 'sum' , ind = None , out = object , plot = True , dataname = None , fs = None , dmargin = None , wintit = None , invert = True , units = None , draw = True , connect = True ) :... | msg = "Arg out must be in [object,np.ndarray]"
assert out in [ object , np . ndarray ] , msg
assert type ( Brightness ) is bool , "Arg Brightness must be a bool !"
if Brightness is False and self . Etendues is None :
msg = "Etendue must be set if Brightness is False !"
raise Exception ( msg )
# Preformat ind
in... |
def getSequence ( title , db = 'nucleotide' ) :
"""Get information about a sequence from Genbank .
@ param title : A C { str } sequence title from a BLAST hit . Of the form
' gi | 63148399 | gb | DQ011818.1 | Description . . . ' .
@ param db : The C { str } name of the Entrez database to consult .
NOTE : th... | titleId = title . split ( ' ' , 1 ) [ 0 ]
try :
gi = titleId . split ( '|' ) [ 1 ]
except IndexError : # Assume we have a gi number directly , and make sure it ' s a string .
gi = str ( titleId )
try :
client = Entrez . efetch ( db = db , rettype = 'gb' , retmode = 'text' , id = gi )
except URLError :
r... |
def usage_plan_absent ( name , plan_name , region = None , key = None , keyid = None , profile = None ) :
'''Ensures usage plan identified by name is no longer present
. . versionadded : : 2017.7.0
name
name of the state
plan _ name
name of the plan to remove
. . code - block : : yaml
usage plan absen... | ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } }
try :
common_args = dict ( [ ( 'region' , region ) , ( 'key' , key ) , ( 'keyid' , keyid ) , ( 'profile' , profile ) ] )
existing = __salt__ [ 'boto_apigateway.describe_usage_plans' ] ( name = plan_name , ** common_args )
if 'error... |
def compare ( self , compare_recipe , suffix = '_compare' ) :
"""Adds a comparison recipe to a base recipe .""" | assert isinstance ( compare_recipe , Recipe )
assert isinstance ( suffix , basestring )
self . compare_recipe . append ( compare_recipe )
self . suffix . append ( suffix )
self . dirty = True
return self . recipe |
def path ( self , which = None ) :
"""Extend ` ` nailgun . entity _ mixins . Entity . path ` ` .
The format of the returned path depends on the value of ` ` which ` ` :
smart _ class _ parameters
/ api / puppetclasses / : puppetclass _ id / smart _ class _ parameters
Otherwise , call ` ` super ` ` .""" | if which in ( 'smart_class_parameters' , 'smart_variables' ) :
return '{0}/{1}' . format ( super ( PuppetClass , self ) . path ( which = 'self' ) , which )
return super ( PuppetClass , self ) . path ( which ) |
def add_status_query_managers ( sender , ** kwargs ) :
"""Add a Querymanager for each status item dynamically .""" | if not issubclass ( sender , StatusModel ) :
return
if django . VERSION >= ( 1 , 10 ) : # First , get current manager name . . .
default_manager = sender . _meta . default_manager
for value , display in getattr ( sender , 'STATUS' , ( ) ) :
if _field_exists ( sender , value ) :
raise ImproperlyConfi... |
def write_command_line ( self ) :
"""Writes command line to attributes .
The command line is written to the file ' s ` ` attrs [ ' cmd ' ] ` ` . If this
attribute already exists in the file ( this can happen when resuming
from a checkpoint ) , ` ` attrs [ ' cmd ' ] ` ` will be a list storing the current
com... | cmd = [ " " . join ( sys . argv ) ]
try :
previous = self . attrs [ "cmd" ]
if isinstance ( previous , str ) : # convert to list
previous = [ previous ]
elif isinstance ( previous , numpy . ndarray ) :
previous = previous . tolist ( )
except KeyError :
previous = [ ]
self . attrs [ "cmd"... |
async def list ( source ) :
"""Generate a single list from an asynchronous sequence .""" | result = [ ]
async with streamcontext ( source ) as streamer :
async for item in streamer :
result . append ( item )
yield result |
def _get_minidom_tag_value ( station , tag_name ) :
"""get a value from a tag ( if it exists )""" | tag = station . getElementsByTagName ( tag_name ) [ 0 ] . firstChild
if tag :
return tag . nodeValue
return None |
def run ( self ) :
"""Run task , namely :
* purge existing index , if requested ( ` purge _ existing _ index ` ) ,
* create the index , if missing ,
* apply mappings , if given ,
* set refresh interval to - 1 ( disable ) for performance reasons ,
* bulk index in batches of size ` chunk _ size ` ( 2000 ) ,... | if self . purge_existing_index :
self . delete_index ( )
self . create_index ( )
es = self . _init_connection ( )
if self . mapping :
es . indices . put_mapping ( index = self . index , doc_type = self . doc_type , body = self . mapping )
es . indices . put_settings ( { "index" : { "refresh_interval" : "-1" } }... |
def cli ( env , package_keyname , keyword , category ) :
"""List package items used for ordering .
The item keyNames listed can be used with ` slcli order place ` to specify
the items that are being ordered in the package .
. . Note : :
Items with a numbered category , like disk0 or gpu0 , can be included
... | table = formatting . Table ( COLUMNS )
manager = ordering . OrderingManager ( env . client )
_filter = { 'items' : { } }
if keyword :
_filter [ 'items' ] [ 'description' ] = { 'operation' : '*= %s' % keyword }
if category :
_filter [ 'items' ] [ 'categories' ] = { 'categoryCode' : { 'operation' : '_= %s' % cate... |
def freqpoly_plot ( data ) :
"""make freqpoly plot of merged read lengths""" | rel_data = OrderedDict ( )
for key , val in data . items ( ) :
tot = sum ( val . values ( ) , 0 )
rel_data [ key ] = { k : v / tot for k , v in val . items ( ) }
fplotconfig = { 'data_labels' : [ { 'name' : 'Absolute' , 'ylab' : 'Frequency' , 'xlab' : 'Merged Read Length' } , { 'name' : 'Relative' , 'ylab' : 'R... |
def __store_query ( self , query_items ) :
"""Make where clause
: @ param query _ items
: @ type query _ items : dict""" | temp_index = self . _current_query_index
if len ( self . _queries ) - 1 < temp_index :
self . _queries . append ( [ ] )
self . _queries [ temp_index ] . append ( query_items ) |
def inspect ( item , maxchar = 80 ) :
"""Inspect the attributes of an item .""" | for i in dir ( item ) :
try :
member = str ( getattr ( item , i ) )
if maxchar and len ( member ) > maxchar :
member = member [ : maxchar ] + "..."
except :
member = "[ERROR]"
print ( "{}: {}" . format ( i , member ) , file = sys . stderr ) |
def checkSubstitute ( self , typecode ) :
'''If this is True , allow typecode to be substituted
for " self " typecode .''' | if not isinstance ( typecode , ElementDeclaration ) :
return False
try :
nsuri , ncname = typecode . substitutionGroup
except ( AttributeError , TypeError ) :
return False
if ( nsuri , ncname ) != ( self . schema , self . literal ) : # allow slop with the empty namespace
if not nsuri and not self . sche... |
def _addFilename ( self , filename ) :
"""Add a new file name .
@ param filename : A C { str } file name .
@ raise ValueError : If a file with this name has already been added .
@ return : The C { int } id of the newly added file .""" | cur = self . _connection . cursor ( )
try :
cur . execute ( 'INSERT INTO files(name) VALUES (?)' , ( filename , ) )
except sqlite3 . IntegrityError as e :
if str ( e ) . find ( 'UNIQUE constraint failed' ) > - 1 :
raise ValueError ( 'Duplicate file name: %r' % filename )
else :
raise
else :
... |
def PushEvent ( self , event ) :
"""Pushes an event onto the heap .
Args :
event ( EventObject ) : event .""" | event_string = event . GetAttributeValuesString ( )
heap_values = ( event . timestamp , event . timestamp_desc , event_string , event )
heapq . heappush ( self . _heap , heap_values ) |
def get_private_name ( self , f ) :
"""get private protected name of an attribute
: param str f : name of the private attribute to be accessed .""" | f = self . __swagger_rename__ [ f ] if f in self . __swagger_rename__ . keys ( ) else f
return '_' + self . __class__ . __name__ + '__' + f |
def pad_aes256 ( s ) :
"""Pads an input string to a given block size .
: param s : string
: returns : The padded string .""" | if len ( s ) % AES . block_size == 0 :
return s
return Padding . appendPadding ( s , blocksize = AES . block_size ) |
def heartbeat ( self ) :
"""Send a ping to the websocket periodically .
This is needed so that Heroku won ' t close the connection
from inactivity .""" | while not self . ws . closed :
gevent . sleep ( HEARTBEAT_DELAY )
gevent . spawn ( self . send , "ping" ) |
def up_capture ( returns , factor_returns , ** kwargs ) :
"""Compute the capture ratio for periods when the benchmark return is positive
Parameters
returns : pd . Series or np . ndarray
Returns of the strategy , noncumulative .
- See full explanation in : func : ` ~ empyrical . stats . cum _ returns ` .
f... | return up ( returns , factor_returns , function = capture , ** kwargs ) |
def cancel_subnet ( self , subnet_id ) :
"""Cancels the specified subnet .
: param int subnet _ id : The ID of the subnet to be cancelled .""" | subnet = self . get_subnet ( subnet_id , mask = 'id, billingItem.id' )
if "billingItem" not in subnet :
raise exceptions . SoftLayerError ( "subnet %s can not be cancelled" " " % subnet_id )
billing_id = subnet [ 'billingItem' ] [ 'id' ]
return self . client [ 'Billing_Item' ] . cancelService ( id = billing_id ) |
def get_account_policy ( region = None , key = None , keyid = None , profile = None ) :
'''Get account policy for the AWS account .
. . versionadded : : 2015.8.0
CLI Example :
. . code - block : : bash
salt myminion boto _ iam . get _ account _ policy''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
try :
info = conn . get_account_password_policy ( )
return info . get_account_password_policy_response . get_account_password_policy_result . password_policy
except boto . exception . BotoServerError as e :
log . debug ( e ... |
def quantize_without_scipy ( self , image ) :
"""" This function can be used if no scipy is availabe .
It ' s 7 times slower though .""" | w , h = image . size
px = np . asarray ( image ) . copy ( )
memo = { }
for j in range ( w ) :
for i in range ( h ) :
key = ( px [ i , j , 0 ] , px [ i , j , 1 ] , px [ i , j , 2 ] )
try :
val = memo [ key ]
except KeyError :
val = self . convert ( * key )
... |
def deepvalues ( mapping ) :
"""Iterates over nested mapping , depth - first , in sorted order by key .""" | values = vals_sorted_by_key ( mapping )
for obj in values :
mapping = False
try :
obj . items
except AttributeError :
pass
else :
mapping = True
for subobj in deepvalues ( obj ) :
yield subobj
if not mapping :
yield obj |
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) :
"""See documentation for method ` GroundShakingIntensityModel ` in
: class : ~ ` openquake . hazardlib . gsim . base . GSIM `""" | # This is just used for testing purposes
if len ( stddev_types ) == 0 :
stddev_types = [ StdDev . TOTAL ]
mean , stds = self . _get_mean_and_stddevs ( sites , rup , dists , imt , stddev_types )
stddevs = [ np . ones ( len ( dists . repi ) ) * get_sigma ( imt ) ]
delta = self . _get_delta ( stds , dists )
mean = mea... |
def stream_json_file ( local_file ) :
"""Stream a JSON file ( in JSON - per - line format )
Args :
local _ file ( file - like object ) an open file - handle that contains a
JSON string on each line
Yields :
( dict ) JSON objects""" | for i , line in enumerate ( local_file ) :
try :
data = json . loads ( line . decode ( 'utf-8' ) )
yield data
except ValueError as e :
logging . warning ( "Skipping line %d due to error: %s" , i , e )
continue |
def fit ( self , X , y , sample_weight = None , init_score = None , eval_set = None , eval_names = None , eval_sample_weight = None , eval_class_weight = None , eval_init_score = None , eval_metric = None , early_stopping_rounds = None , verbose = True , feature_name = 'auto' , categorical_feature = 'auto' , callbacks ... | _LGBMAssertAllFinite ( y )
_LGBMCheckClassificationTargets ( y )
self . _le = _LGBMLabelEncoder ( ) . fit ( y )
_y = self . _le . transform ( y )
self . _classes = self . _le . classes_
self . _n_classes = len ( self . _classes )
if self . _n_classes > 2 : # Switch to using a multiclass objective in the underlying LGBM... |
def is_ens_domain ( authority : str ) -> bool :
"""Return false if authority is not a valid ENS domain .""" | # check that authority ends with the tld ' . eth '
# check that there are either 2 or 3 subdomains in the authority
# i . e . zeppelinos . eth or packages . zeppelinos . eth
if authority [ - 4 : ] != ".eth" or len ( authority . split ( "." ) ) not in [ 2 , 3 ] :
return False
return True |
def set_linkage_method ( self , method ) :
"""Sets the method to determine the distance between two clusters .
: param method : The method to use . It can be one of ` ` ' single ' ` ` ,
` ` ' complete ' ` ` , ` ` ' average ' ` ` or ` ` ' uclus ' ` ` , or a callable . The
callable should take two collections a... | if method == 'single' :
self . linkage = single
elif method == 'complete' :
self . linkage = complete
elif method == 'average' :
self . linkage = average
elif method == 'uclus' :
self . linkage = uclus
elif hasattr ( method , '__call__' ) :
self . linkage = method
else :
raise ValueError ( 'dist... |
async def start ( self ) -> None :
"""Process incoming request .
It reads request line , request headers and request payload , then
calls handle _ request ( ) method . Subclass has to override
handle _ request ( ) . start ( ) handles various exceptions in request
or response handling . Connection is being c... | loop = self . _loop
handler = self . _task_handler
assert handler is not None
manager = self . _manager
assert manager is not None
keepalive_timeout = self . _keepalive_timeout
resp = None
assert self . _request_factory is not None
assert self . _request_handler is not None
while not self . _force_close :
if not se... |
def to_e164 ( name , origin = public_enum_domain , want_plus_prefix = True ) :
"""Convert an ENUM domain name into an E . 164 number .
@ param name : the ENUM domain name .
@ type name : dns . name . Name object .
@ param origin : A domain containing the ENUM domain name . The
name is relativized to this do... | if not origin is None :
name = name . relativize ( origin )
dlabels = [ d for d in name . labels if ( d . isdigit ( ) and len ( d ) == 1 ) ]
if len ( dlabels ) != len ( name . labels ) :
raise dns . exception . SyntaxError ( 'non-digit labels in ENUM domain name' )
dlabels . reverse ( )
text = '' . join ( dlabe... |
def create_project ( self , name , description ) :
"""Create a new project with the specified name and description
: param name : str : name of the project to create
: param description : str : description of the project to create
: return : Project""" | return self . _create_item_response ( self . data_service . create_project ( name , description ) , Project ) |
def toggle_concatenate ( self ) :
"""Enable and disable concatenation options .""" | if not ( self . chunk [ 'epoch' ] . isChecked ( ) and self . lock_to_staging . get_value ( ) ) :
for i , j in zip ( [ self . idx_chan , self . idx_cycle , self . idx_stage , self . idx_evt_type ] , [ self . cat [ 'chan' ] , self . cat [ 'cycle' ] , self . cat [ 'stage' ] , self . cat [ 'evt_type' ] ] ) :
if... |
def remove_volume ( self , name , force = False ) :
"""Remove a volume . Similar to the ` ` docker volume rm ` ` command .
Args :
name ( str ) : The volume ' s name
force ( bool ) : Force removal of volumes that were already removed
out of band by the volume driver plugin .
Raises :
: py : class : ` doc... | params = { }
if force :
if utils . version_lt ( self . _version , '1.25' ) :
raise errors . InvalidVersion ( 'force removal was introduced in API 1.25' )
params = { 'force' : force }
url = self . _url ( '/volumes/{0}' , name , params = params )
resp = self . _delete ( url )
self . _raise_for_status ( re... |
def _remove_vm ( name , datacenter , service_instance , placement = None , power_off = None ) :
'''Helper function to remove a virtual machine
name
Name of the virtual machine
service _ instance
vCenter service instance for connection and configuration
datacenter
Datacenter of the virtual machine
plac... | results = { }
if placement :
( resourcepool_object , placement_object ) = salt . utils . vmware . get_placement ( service_instance , datacenter , placement )
else :
placement_object = salt . utils . vmware . get_datacenter ( service_instance , datacenter )
if power_off :
power_off_vm ( name , datacenter , s... |
async def getTriggerToken ( self , * args , ** kwargs ) :
"""Get a trigger token
Retrieve a unique secret token for triggering the specified hook . This
token can be deactivated with ` resetTriggerToken ` .
This method gives output : ` ` v1 / trigger - token - response . json # ` `
This method is ` ` stable... | return await self . _makeApiCall ( self . funcinfo [ "getTriggerToken" ] , * args , ** kwargs ) |
def source_analysis ( source_path , group , encoding = 'automatic' , fallback_encoding = 'cp1252' , generated_regexes = pygount . common . regexes_from ( DEFAULT_GENERATED_PATTERNS_TEXT ) , duplicate_pool = None ) :
"""Analysis for line counts in source code stored in ` ` source _ path ` ` .
: param source _ path... | assert encoding is not None
assert generated_regexes is not None
result = None
lexer = None
source_code = None
source_size = os . path . getsize ( source_path )
if source_size == 0 :
_log . info ( '%s: is empty' , source_path )
result = pseudo_source_analysis ( source_path , group , SourceState . empty )
elif i... |
def __render_videoframe ( self ) :
"""Retrieves a new videoframe from the stream .
Sets the frame as the _ _ current _ video _ frame and passes it on to
_ _ videorenderfunc ( ) if it is set .""" | new_videoframe = self . clip . get_frame ( self . clock . time )
# Pass it to the callback function if this is set
if callable ( self . __videorenderfunc ) :
self . __videorenderfunc ( new_videoframe )
# Set current _ frame to current frame ( . . . )
self . __current_videoframe = new_videoframe |
def get_url_for_id ( client_site_url , apikey , resource_id ) :
"""Return the URL for the given resource ID .
Contacts the client site ' s API to get the URL for the ID and returns it .
: raises CouldNotGetURLError : if getting the URL fails for any reason""" | # TODO : Handle invalid responses from the client site .
url = client_site_url + u"deadoralive/get_url_for_resource_id"
params = { "resource_id" : resource_id }
response = requests . get ( url , headers = dict ( Authorization = apikey ) , params = params )
if not response . ok :
raise CouldNotGetURLError ( u"Couldn... |
def ud_grade_ipix ( ipix , nside_in , nside_out , nest = False ) :
"""Upgrade or degrade resolution of a pixel list .
Parameters :
ipix : array - like
the input pixel ( s )
nside _ in : int
the nside of the input pixel ( s )
nside _ out : int
the desired nside of the output pixel ( s )
order : str
... | if nside_in == nside_out :
return ipix
elif nside_in < nside_out :
return u_grade_ipix ( ipix , nside_in , nside_out , nest )
elif nside_in > nside_out :
return d_grade_ipix ( ipix , nside_in , nside_out , nest ) |
def _getNumberOfRequiredVerificationsVocabulary ( self ) :
"""Returns a DisplayList with the available options for the
multi - verification list : ' system default ' , ' 1 ' , ' 2 ' , ' 3 ' , ' 4'
: returns : DisplayList with the available options for the
multi - verification list""" | bsve = self . bika_setup . getNumberOfRequiredVerifications ( )
bsval = "%s (%s)" % ( _ ( "System default" ) , str ( bsve ) )
items = [ ( - 1 , bsval ) , ( 1 , '1' ) , ( 2 , '2' ) , ( 3 , '3' ) , ( 4 , '4' ) ]
return IntDisplayList ( list ( items ) ) |
def _inner_dataset_template ( cls , dataset ) :
"""Returns a Dataset template used as a wrapper around the data
contained within the multi - interface dataset .""" | from . import Dataset
vdims = dataset . vdims if getattr ( dataset , 'level' , None ) is None else [ ]
return Dataset ( dataset . data [ 0 ] , datatype = cls . subtypes , kdims = dataset . kdims , vdims = vdims ) |
def select_edges_by ( docgraph , layer = None , edge_type = None , data = False ) :
"""get all edges with the given edge type and layer .
Parameters
docgraph : DiscourseDocumentGraph
document graph from which the nodes will be extracted
layer : str
name of the layer
edge _ type : str
Type of the edges... | edge_type_eval = "edge_attribs['edge_type'] == '{}'" . format ( edge_type )
layer_eval = "'{}' in edge_attribs['layers']" . format ( layer )
if layer is not None :
if edge_type is not None :
return select_edges ( docgraph , data = data , conditions = [ edge_type_eval , layer_eval ] )
else : # filter by ... |
def version ( ) :
"""Extracts version from the ` ` _ _ init _ _ . py ` ` file at the module ' s root .
Inspired by : https : / / packaging . python . org / single _ source _ version /""" | global _version
if _version :
return _version
init_file = read_file ( MODULE_NAME , '__init__.py' )
matches = re . search ( r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]' , init_file , re . M )
if not matches :
raise RuntimeError ( "Unable to find version string in __init__.py ." )
_version = matches . group ( 1 )
#... |
def reflected_binary_operator ( op ) :
"""Factory function for making binary operator methods on a Factor .
Returns a function , " reflected _ binary _ operator " suitable for implementing
functions like _ _ radd _ _ .""" | assert not is_comparison ( op )
@ with_name ( method_name_for_op ( op , commute = True ) )
@ coerce_numbers_to_my_dtype
def reflected_binary_operator ( self , other ) :
if isinstance ( self , NumericalExpression ) :
self_expr , other_expr , new_inputs = self . build_binary_op ( op , other )
return N... |
def concatenate ( fname1 , fname2 , dfilter1 = None , dfilter2 = None , has_header1 = True , has_header2 = True , frow1 = 0 , frow2 = 0 , ofname = None , ocols = None , ) :
r"""Concatenate two comma - separated values file .
Data rows from the second file are appended at the end of the data rows
from the first ... | # pylint : disable = R0913 , R0914
iro = pexdoc . exh . addex ( RuntimeError , "Files have different number of columns" )
iom = pexdoc . exh . addex ( RuntimeError , "Number of columns in data files and output columns are different" )
# Read and validate file 1
obj1 = CsvFile ( fname = fname1 , dfilter = dfilter1 , has... |
def generateSequence ( self , text , preprocess = False ) :
"""Return a list of lists representing the text sequence in network data
format . Does not preprocess the text .""" | # TODO : enable text preprocessing ; abstract out the logic in split ( ) into a common method .
tokens = TextPreprocess ( ) . tokenize ( text )
cat = [ - 1 ]
self . sequenceCount += 1
uniqueID = "q"
data = self . _formatSequence ( tokens , cat , self . sequenceCount - 1 , uniqueID )
return data |
def iter_sections ( self , recursive = False , path = None , key = 'path' ) :
"""See : meth : ` . iter _ all ` for standard iterator argument descriptions .
Returns :
iterator : iterator over ` ` ( key , section ) ` ` pairs of all sections
in this section ( and sub - sections if ` ` recursive = True ` ` ) .""... | for x in self . iter_all ( recursive = recursive , path = path , key = key ) :
if key is None :
if x . is_section :
yield x
elif x [ 1 ] . is_section :
yield x |
def _show_or_dump ( self , dump = False , indent = 3 , lvl = "" , label_lvl = "" , first_call = True ) :
"""Reproduced from packet . py""" | ct = AnsiColorTheme ( ) if dump else conf . color_theme
s = "%s%s %s %s \n" % ( label_lvl , ct . punct ( "###[" ) , ct . layer_name ( self . name ) , ct . punct ( "]###" ) )
for f in self . fields_desc [ : - 1 ] :
ncol = ct . field_name
vcol = ct . field_value
fvalue = self . getfieldval ( f . name )
be... |
def get_apod ( cls , date = None , hd = False ) :
"""Returns Astronomy Picture of the Day
Args :
date : date instance ( default = today )
hd : bool if high resolution should be included
Returns :
json""" | instance = cls ( 'planetary/apod' )
filters = { 'date' : date , 'hd' : hd }
return instance . get_resource ( ** filters ) |
def markdown ( doc , title = True , template = 'short_documentation.md' ) :
"""Markdown , specifically for the Notes field in a CKAN dataset""" | from jinja2 import Environment , PackageLoader , select_autoescape
env = Environment ( loader = PackageLoader ( 'metapack' , 'support/templates' ) # autoescape = select _ autoescape ( [ ' html ' , ' xml ' ] )
)
context = display_context ( doc )
return env . get_template ( template ) . render ( ** context ) |
def _un_meta_name ( self , name ) :
"""Reverse of _ meta _ name""" | if name . startswith ( 'HTTP_' ) :
name = name [ 5 : ]
return name . replace ( '_' , '-' ) . title ( ) |
def _GetStat ( self ) :
"""Retrieves information about the file entry .
Returns :
VFSStat : a stat object .""" | stat_object = vfs_stat . VFSStat ( )
if self . _compressed_stream :
stat_object . size = self . _compressed_stream . get_size ( )
stat_object . type = self . entry_type
return stat_object |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.