signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _find_usage_cloudtrail ( self ) :
"""Calculate current usage for CloudTrail related metrics""" | trail_list = self . conn . describe_trails ( ) [ 'trailList' ]
trail_count = len ( trail_list ) if trail_list else 0
for trail in trail_list :
data_resource_count = 0
if self . conn . _client_config . region_name == trail [ 'HomeRegion' ] :
response = self . conn . get_event_selectors ( TrailName = trai... |
def uuid ( self ) :
"""Return UUID of logical volume
: return : str""" | uuid_file = '/sys/block/%s/dm/uuid' % os . path . basename ( os . path . realpath ( self . volume_path ( ) ) )
lv_uuid = open ( uuid_file ) . read ( ) . strip ( )
if lv_uuid . startswith ( 'LVM-' ) is True :
return lv_uuid [ 4 : ]
return lv_uuid |
def book_car ( intent_request ) :
"""Performs dialog management and fulfillment for booking a car .
Beyond fulfillment , the implementation for this intent demonstrates the following :
1 ) Use of elicitSlot in slot validation and re - prompting
2 ) Use of sessionAttributes to pass information that can be used... | slots = intent_request [ 'currentIntent' ] [ 'slots' ]
pickup_city = slots [ 'PickUpCity' ]
pickup_date = slots [ 'PickUpDate' ]
return_date = slots [ 'ReturnDate' ]
driver_age = slots [ 'DriverAge' ]
car_type = slots [ 'CarType' ]
confirmation_status = intent_request [ 'currentIntent' ] [ 'confirmationStatus' ]
sessio... |
def remove_entity_headers ( headers , allowed = ( "content-location" , "expires" ) ) :
"""Removes all the entity headers present in the headers given .
According to RFC 2616 Section 10.3.5,
Content - Location and Expires are allowed as for the
" strong cache validator " .
https : / / tools . ietf . org / ht... | allowed = set ( [ h . lower ( ) for h in allowed ] )
headers = { header : value for header , value in headers . items ( ) if not is_entity_header ( header ) or header . lower ( ) in allowed }
return headers |
def get_configured_rc_input_names ( self , channel ) :
"""find all RC mappings to a given channel and return their names
: param channel : input channel ( 0 = first )
: return : list of strings or None""" | ret_val = [ ]
for key in self . _ulog . initial_parameters :
param_val = self . _ulog . initial_parameters [ key ]
if key . startswith ( 'RC_MAP_' ) and param_val == channel + 1 :
ret_val . append ( key [ 7 : ] . capitalize ( ) )
if len ( ret_val ) > 0 :
return ret_val
return None |
def update_ips ( self ) :
"""Retrieves the public and private ip of the instance by using the
cloud provider . In some cases the public ip assignment takes some
time , but this method is non blocking . To check for a public ip ,
consider calling this method multiple times during a certain timeout .""" | self . ips = self . _cloud_provider . get_ips ( self . instance_id )
return self . ips [ : ] |
def front ( self , n ) :
"""Returns the first n columns .
Args :
n : Integer containing the number of columns to return .
Returns :
DataManager containing the first n columns of the original DataManager .""" | new_dtypes = ( self . _dtype_cache if self . _dtype_cache is None else self . _dtype_cache [ : n ] )
# See head for an explanation of the transposed behavior
if self . _is_transposed :
result = self . __constructor__ ( self . data . transpose ( ) . take ( 0 , n ) . transpose ( ) , self . index , self . columns [ : ... |
def fromBox ( self , name , strings , objects , proto ) :
"""Retreive an attribute from the C { proto } parameter .""" | objects [ name ] = getattr ( proto , self . attr ) |
def sequence_beam_search ( symbols_to_logits_fn , initial_ids , initial_cache , vocab_size , beam_size , alpha , max_decode_length , eos_id ) :
"""Search for sequence of subtoken ids with the largest probability .
Args :
symbols _ to _ logits _ fn : A function that takes in ids , index , and cache as
argument... | batch_size = tf . shape ( initial_ids ) [ 0 ]
sbs = SequenceBeamSearch ( symbols_to_logits_fn , vocab_size , batch_size , beam_size , alpha , max_decode_length , eos_id )
return sbs . search ( initial_ids , initial_cache ) |
def secretbox_encrypt ( data , ** kwargs ) :
'''Encrypt data using a secret key generated from ` nacl . keygen ` .
The same secret key can be used to decrypt the data using ` nacl . secretbox _ decrypt ` .
CLI Examples :
. . code - block : : bash
salt - run nacl . secretbox _ encrypt datatoenc
salt - call... | # ensure data is in bytes
data = salt . utils . stringutils . to_bytes ( data )
sk = _get_sk ( ** kwargs )
b = libnacl . secret . SecretBox ( sk )
return base64 . b64encode ( b . encrypt ( data ) ) |
def nx_gen_node_attrs ( G , key , nodes = None , default = util_const . NoParam , on_missing = 'error' , on_keyerr = 'default' ) :
"""Improved generator version of nx . get _ node _ attributes
Args :
on _ missing ( str ) : Strategy for handling nodes missing from G .
Can be { ' error ' , ' default ' , ' filte... | if on_missing is None :
on_missing = 'error'
if default is util_const . NoParam and on_keyerr == 'default' :
on_keyerr = 'error'
if nodes is None :
nodes = G . nodes ( )
# Generate ` node _ data ` nodes and data dictionary
node_dict = nx_node_dict ( G )
if on_missing == 'error' :
node_data = ( ( n , nod... |
def intersect ( self , other ) :
"""Intersect with ` other ` sorted index .
Parameters
other : array _ like , int
Array of values to intersect with .
Returns
out : SortedIndex
Values in common .
Examples
> > > import allel
> > > idx1 = allel . SortedIndex ( [ 3 , 6 , 11 , 20 , 35 ] )
> > > idx2 ... | loc = self . locate_keys ( other , strict = False )
return self . compress ( loc , axis = 0 ) |
async def lookup ( source_id : str , schema_id : str ) :
"""Create a new schema object from an existing ledger schema
: param source _ id : Institution ' s personal identification for the schema
: param schema _ id : Ledger schema ID for lookup
Example :
source _ id = ' foobar123'
name = ' Address Schema ... | try :
schema = Schema ( source_id , '' , '' , [ ] )
if not hasattr ( Schema . lookup , "cb" ) :
schema . logger . debug ( "vcx_schema_get_attributes: Creating callback" )
Schema . lookup . cb = create_cb ( CFUNCTYPE ( None , c_uint32 , c_uint32 , c_uint32 , c_char_p ) )
c_source_id = c_char_... |
def read ( self , els_client = None ) :
"""Reads the JSON representation of the author from ELSAPI .
Returns True if successful ; else , False .""" | if ElsProfile . read ( self , self . __payload_type , els_client ) :
return True
else :
return False |
def _get_acceleration ( self , data ) :
'''Return acceleration mG''' | if ( data [ 7 : 8 ] == 0x7FFF or data [ 9 : 10 ] == 0x7FFF or data [ 11 : 12 ] == 0x7FFF ) :
return ( None , None , None )
acc_x = twos_complement ( ( data [ 7 ] << 8 ) + data [ 8 ] , 16 )
acc_y = twos_complement ( ( data [ 9 ] << 8 ) + data [ 10 ] , 16 )
acc_z = twos_complement ( ( data [ 11 ] << 8 ) + data [ 12 ]... |
def from_dict ( cls , logical_id , deployment_preference_dict ) :
""": param logical _ id : the logical _ id of the resource that owns this deployment preference
: param deployment _ preference _ dict : the dict object taken from the SAM template
: return :""" | enabled = deployment_preference_dict . get ( 'Enabled' , True )
if not enabled :
return DeploymentPreference ( None , None , None , None , False , None )
if 'Type' not in deployment_preference_dict :
raise InvalidResourceException ( logical_id , "'DeploymentPreference' is missing required Property 'Type'" )
dep... |
def comply ( self , path ) :
"""Issues a chown and chmod to the file paths specified .""" | utils . ensure_permissions ( path , self . user . pw_name , self . group . gr_name , self . mode ) |
def _not_forever ( self , timeout , d ) :
"""If the timer fires first , cancel the deferred . If the deferred fires
first , cancel the timer .""" | t = self . _reactor . callLater ( timeout , d . cancel )
def _done ( res ) :
if t . active ( ) :
t . cancel ( )
return res
d . addBoth ( _done )
return d |
def _pre_tune ( self ) :
'''Set the minion running flag and issue the appropriate warnings if
the minion cannot be started or is already running''' | if self . _running is None :
self . _running = True
elif self . _running is False :
log . error ( 'This %s was scheduled to stop. Not running %s.tune_in()' , self . __class__ . __name__ , self . __class__ . __name__ )
return
elif self . _running is True :
log . error ( 'This %s is already running. Not r... |
def _set_traffic_class_mutation_mappings ( self , v , load = False ) :
"""Setter method for traffic _ class _ mutation _ mappings , mapped from YANG variable / qos / map / traffic _ class _ mutation / traffic _ class _ mutation _ mappings ( list )
If this variable is read - only ( config : false ) in the
source... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "from_traffic_class" , traffic_class_mutation_mappings . traffic_class_mutation_mappings , yang_name = "traffic-class-mutation-mappings" , rest_name = "map" , parent = self , is_container = 'list' , user_ordere... |
def sortByColumn ( self , column , order = QtCore . Qt . AscendingOrder ) :
"""Overloads the default sortByColumn to record the order for later \
reference .
: param column | < int >
order | < QtCore . Qt . SortOrder >""" | super ( XTreeWidget , self ) . sortByColumn ( column , order )
self . _sortOrder = order |
def down ( self , path , link , repo ) :
"""Download files""" | filename = link . split ( "/" ) [ - 1 ]
if not os . path . isfile ( path + filename ) :
Download ( path , link . split ( ) , repo ) . start ( ) |
def open_files ( filenames ) :
"""Call the system ' open ' command on a file .""" | command = [ 'open' ] + filenames
process = Popen ( command , stdout = PIPE , stderr = PIPE )
stdout , stderr = process . communicate ( ) |
def edit ( self , request , id ) :
"""Render a form to edit an object .""" | try :
object = self . model . objects . get ( id = id )
except self . model . DoesNotExist :
return self . _render ( request = request , template = '404' , context = { 'error' : 'The %s could not be found.' % self . model . __name__ . lower ( ) } , status = 404 , prefix_template_path = False )
form = ( self . f... |
def use_plenary_bank_view ( self ) :
"""Pass through to provider ItemBankSession . use _ plenary _ bank _ view""" | self . _bank_view = PLENARY
# self . _ get _ provider _ session ( ' item _ bank _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_plenary_bank_view ( )
except AttributeError :
pass |
def apply ( self , resource ) :
"""Apply filter to resource
: param resource : Image
: return : Image""" | if not isinstance ( resource , Image . Image ) :
raise ValueError ( 'Unknown resource format' )
original_width , original_height = resource . size
if self . start [ 0 ] < original_width or self . start [ 1 ] < original_height :
left = self . start [ 0 ]
upper = self . start [ 1 ]
else :
left = 0
upp... |
def save_current_keywords ( self ) :
"""Save keywords to the layer .
It will write out the keywords for the current layer .
This method is based on the KeywordsDialog class .""" | current_keywords = self . get_keywords ( )
try :
self . keyword_io . write_keywords ( layer = self . layer , keywords = current_keywords )
except InaSAFEError as e :
error_message = get_error_message ( e )
# noinspection PyCallByClass , PyTypeChecker , PyArgumentList
QMessageBox . warning ( self , tr ( ... |
def now ( tzinfo = True ) :
"""Return an aware or naive datetime . datetime , depending on settings . USE _ TZ .""" | if dj_now :
return dj_now ( )
if tzinfo : # timeit shows that datetime . now ( tz = utc ) is 24 % slower
return datetime . utcnow ( ) . replace ( tzinfo = utc )
return datetime . now ( ) |
def run ( self , inputs : Dict [ str , Union [ float , Iterable ] ] , torch_size : Optional [ int ] = None , ) -> Union [ float , Iterable ] :
"""Executes the GrFN over a particular set of inputs and returns the
result .
Args :
inputs : Input set where keys are the names of input nodes in the
GrFN and each ... | # Set input values
for i in self . inputs :
self . nodes [ i ] [ "value" ] = inputs [ i ]
for func_set in self . function_sets :
for func_name in func_set :
lambda_fn = self . nodes [ func_name ] [ "lambda_fn" ]
output_node = list ( self . successors ( func_name ) ) [ 0 ]
signature = sel... |
def pretty_str ( self , indent = 0 ) :
"""Return a human - readable string representation of this object .
Kwargs :
indent ( int ) : The amount of spaces to use as indentation .""" | if self . parenthesis :
return '{}({})' . format ( ' ' * indent , pretty_str ( self . value ) )
return pretty_str ( self . value , indent = indent ) |
def _squeeze ( self , var_tbl : dict ) -> dict :
"""Makes sure no extra dimensions are floating around in the input arrays
Returns inferred dict of variable : val pairs""" | var_names = var_tbl . copy ( )
# squeeze any numpy arrays
for v in var_tbl :
val = var_tbl [ v ]
if isinstance ( val , np . ndarray ) :
var_names [ v ] = val . squeeze ( )
return var_names |
async def _on_response_prepare ( self , request : web . Request , response : web . StreamResponse ) :
"""Non - preflight CORS request response processor .
If request is done on CORS - enabled route , process request parameters
and set appropriate CORS response headers .""" | if ( not self . _router_adapter . is_cors_enabled_on_request ( request ) or self . _router_adapter . is_preflight_request ( request ) ) : # Either not CORS enabled route , or preflight request which is
# handled in its own handler .
return
# Processing response of non - preflight CORS - enabled request .
config = s... |
def sphinx_dir ( self ) :
"""Returns directory with sphinx documentation , if there is such .
Returns :
Full path to sphinx documentation dir inside the archive , or None
if there is no such .""" | # search for sphinx dir doc / or docs / under the first directory in
# archive ( e . g . spam - 1.0.0 / doc )
candidate_dirs = self . archive . get_directories_re ( settings . SPHINX_DIR_RE , full_path = True )
# search for conf . py in the dirs ( TODO : what if more are found ? )
for directory in candidate_dirs :
... |
def adjust ( cols , light ) :
"""Create palette .""" | cols . sort ( key = util . rgb_to_yiq )
raw_colors = [ * cols , * cols ]
raw_colors [ 0 ] = util . lighten_color ( cols [ 0 ] , 0.40 )
return colors . generic_adjust ( raw_colors , light ) |
def add ( name , function_name , cron ) :
"""Create an event""" | lambder . add_event ( name = name , function_name = function_name , cron = cron ) |
def vamp_1_score ( K , C00_train , C0t_train , Ctt_train , C00_test , C0t_test , Ctt_test , k = None ) :
"""Computes the VAMP - 1 score of a kinetic model .
Ranks the kinetic model described by the estimation of covariances C00 , C0t and Ctt ,
defined by :
: math : ` C _ { 0t } ^ { train } = E _ t [ x _ t x _... | from pyemma . _ext . variational . solvers . direct import spd_inv_sqrt
# SVD of symmetrized operator in empirical distribution
U , S , V = _svd_sym_koopman ( K , C00_train , Ctt_train )
if k is not None :
U = U [ : , : k ]
# S = S [ : k ] [ : , : k ]
V = V [ : , : k ]
A = spd_inv_sqrt ( mdot ( U . T , C00_... |
def on_message ( self , headers , message ) :
"""Event method that gets called when this listener has received a JMS
message ( representing an HMC notification ) .
Parameters :
headers ( dict ) : JMS message headers , as described for ` headers ` tuple
item returned by the
: meth : ` ~ zhmcclient . Notifi... | with self . _handover_cond : # Wait until receiver has processed the previous notification
while len ( self . _handover_dict ) > 0 :
self . _handover_cond . wait ( self . _wait_timeout )
# Indicate to receiver that there is a new notification
self . _handover_dict [ 'headers' ] = headers
try :
... |
def wait_message ( self ) :
"""Waits until a connection is available on the wire , or until
the connection is in a state that it can ' t accept messages .
It returns True if a message is available , False otherwise .""" | if self . _state != states [ 'open' ] :
return False
if len ( self . _read_queue ) > 0 :
return True
assert self . _read_waiter is None or self . _read_waiter . cancelled ( ) , "You may only use one wait_message() per connection."
self . _read_waiter = asyncio . Future ( loop = self . _loop )
yield from self . ... |
def compute_distance ( m , l ) :
'''Compute distance between two trajectories
Returns
numpy . ndarray''' | if np . shape ( m ) != np . shape ( l ) :
raise ValueError ( "Input matrices are different sizes" )
if np . array_equal ( m , l ) : # print ( " Trajectory % s and % s are equal " % ( m , l ) )
distance = 0
else :
distance = np . array ( np . sum ( cdist ( m , l ) ) , dtype = np . float32 )
return distance |
def python_lib_rpm_dirs ( self ) :
"""Both arch and non - arch site - packages directories .""" | libs = [ self . python_lib_arch_dir , self . python_lib_non_arch_dir ]
def append_rpm ( path ) :
return os . path . join ( path , 'rpm' )
return map ( append_rpm , libs ) |
def _usage_specific ( raw ) :
'''Parse usage / specific .''' | get_key = lambda val : dict ( [ tuple ( val . split ( ":" ) ) , ] )
raw = raw . split ( "\n" )
section , size , used = raw [ 0 ] . split ( " " )
section = section . replace ( "," , "_" ) . replace ( ":" , "" ) . lower ( )
data = { }
data [ section ] = { }
for val in [ size , used ] :
data [ section ] . update ( get... |
def _compute_mean ( self , C , mag , rrup , hypo_depth , delta_R , delta_S , delta_V , delta_I , vs30 ) :
"""Compute MMI Intensity Value as per Equation in Table 5 and
Table 7 pag 198.""" | # mean is calculated for all the 4 classes using the same equation .
# For DowrickRhoades2005SSlab , the coefficients which don ' t appear in
# Model 3 equationare assigned to zero
mean = ( C [ 'A1' ] + ( C [ 'A2' ] + C [ 'A2R' ] * delta_R + C [ 'A2V' ] * delta_V ) * mag + ( C [ 'A3' ] + C [ 'A3S' ] * delta_S + C [ 'A3... |
def lookups ( self , request , model_admin ) :
"""Returns a list of tuples . The first element in each
tuple is the coded value for the option that will
appear in the URL query . The second element is the
human - readable name for the option that will appear
in the right sidebar .""" | User = get_user_model ( )
output = [ ]
for i in models . Model . objects . values ( 'user__pk' ) . distinct ( ) :
pk = i [ 'user__pk' ]
if pk is not None :
output . append ( [ pk , User . objects . get ( pk = pk ) . __str__ ] )
return output |
def getReferenceSetByName ( self , name ) :
"""Returns the reference set with the specified name .""" | if name not in self . _referenceSetNameMap :
raise exceptions . ReferenceSetNameNotFoundException ( name )
return self . _referenceSetNameMap [ name ] |
def cli ( ctx , dname , site ) :
"""List all domains if no < domain > is provided . If < domain > is provided but < site > is not , lists all sites
hosted under < domain > . If both < domain > and < site > are provided , lists information on the specified site .""" | assert isinstance ( ctx , Context )
if dname :
dname = domain_parse ( dname ) . hostname
domain = Session . query ( Domain ) . filter ( Domain . name == dname ) . first ( )
# No such domain
if not domain :
click . secho ( 'No such domain: {dn}' . format ( dn = dname ) , fg = 'red' , bold = True ... |
def returner ( ret ) :
'''Return data to one of potentially many clustered cassandra nodes''' | query = '''INSERT INTO {keyspace}.salt_returns (
jid, minion_id, fun, alter_time, full_ret, return, success
) VALUES (?, ?, ?, ?, ?, ?, ?)''' . format ( keyspace = _get_keyspace ( ) )
statement_arguments = [ '{0}' . format ( ret [ 'jid' ] ) , '{0}' . format ( ret [ 'id' ] ) , '{0}' . for... |
def _list_from_string ( cls , repo , text ) :
"""Create a Stat object from output retrieved by git - diff .
: return : git . Stat""" | hsh = { 'total' : { 'insertions' : 0 , 'deletions' : 0 , 'lines' : 0 , 'files' : 0 } , 'files' : { } }
for line in text . splitlines ( ) :
( raw_insertions , raw_deletions , filename ) = line . split ( "\t" )
insertions = raw_insertions != '-' and int ( raw_insertions ) or 0
deletions = raw_deletions != '-'... |
def check_padding_around_mutation ( given_padding , epitope_lengths ) :
"""If user doesn ' t provide any padding around the mutation we need
to at least include enough of the surrounding non - mutated
esidues to construct candidate epitopes of the specified lengths .""" | min_required_padding = max ( epitope_lengths ) - 1
if not given_padding :
return min_required_padding
else :
require_integer ( given_padding , "Padding around mutation" )
if given_padding < min_required_padding :
raise ValueError ( "Padding around mutation %d cannot be less than %d " "for epitope le... |
def delete ( self , obj ) :
"""Delete an object in CDSTAR and remove it from the catalog .
: param obj : An object ID or an Object instance .""" | obj = self . api . get_object ( getattr ( obj , 'id' , obj ) )
obj . delete ( )
self . remove ( obj . id ) |
def get_backup_path ( ) :
"""Returns full path and filename of backup file""" | dirname , filename = path . split ( path . splitext ( config ( ) . todotxt ( ) ) [ 0 ] )
filename = '.' + filename + '.bak'
return path . join ( dirname , filename ) |
def fix_queue_critical ( self ) :
"""This function tries to fix critical events originating from the queue submission system .
Returns the number of tasks that have been fixed .""" | count = 0
for task in self . iflat_tasks ( status = self . S_QCRITICAL ) :
logger . info ( "Will try to fix task %s" % str ( task ) )
try :
print ( task . fix_queue_critical ( ) )
count += 1
except FixQueueCriticalError :
logger . info ( "Not able to fix task %s" % task )
return coun... |
def get_as_parameters_with_default ( self , key , default_value ) :
"""Converts map element into an Parameters or returns default value if conversion is not possible .
: param key : a key of element to get .
: param default _ value : the default value
: return : Parameters value of the element or default valu... | result = self . get_as_nullable_parameters ( key )
return result if result != None else default_value |
def _batch ( self , vectors , batch_size , num , show_progressbar , return_names ) :
"""Batched cosine distance .""" | vectors = self . normalize ( vectors )
# Single transpose , makes things faster .
reference_transposed = self . norm_vectors . T
for i in tqdm ( range ( 0 , len ( vectors ) , batch_size ) , disable = not show_progressbar ) :
distances = vectors [ i : i + batch_size ] . dot ( reference_transposed )
# For safety ... |
def get_frames ( self , frames = 'all' , override = False , ** kwargs ) :
"""Extract frames from the trajectory file .
Depending on the passed parameters a frame , a list of particular
frames , a range of frames ( from , to ) , or all frames can be extracted
with this function .
Parameters
frames : : clas... | if override is True :
self . frames = { }
if isinstance ( frames , int ) :
frame = self . _get_frame ( self . trajectory_map [ frames ] , frames , ** kwargs )
if frames not in self . frames . keys ( ) :
self . frames [ frames ] = frame
return frame
if isinstance ( frames , list ) :
for frame... |
def json_response ( func ) :
"""@ json _ response decorator adds response header for content type ,
and json - dumps response object .
Example usage :
@ json _ response
def test ( request ) :
return { " hello " : " world " }""" | @ wraps ( func )
def wrapper ( request , * args , ** kwargs ) :
res = func ( request , * args , ** kwargs )
request . setHeader ( 'Content-Type' , 'application/json' )
return json . dumps ( res )
return wrapper |
def url ( self ) :
"""The concatenation of the ` base _ url ` and ` end _ url ` that make up the
resultant url .
: return : the ` base _ url ` and the ` end _ url ` .
: rtype : str""" | end_url = ( "/accounts/{account_id}/alerts/{alert_id}/mentions/" "{mention_id}/children?" )
def without_keys ( d , keys ) :
return { x : d [ x ] for x in d if x not in keys }
keys = { "access_token" , "account_id" , "alert_id" }
parameters = without_keys ( self . params , keys )
for key , value in list ( parameters... |
def argument ( self , argument_dest , arg_type = None , ** kwargs ) :
"""Register an argument for the given command scope using a knack . arguments . CLIArgumentType
: param argument _ dest : The destination argument to add this argument type to
: type argument _ dest : str
: param arg _ type : Predefined CLI... | self . _check_stale ( )
if not self . _applicable ( ) :
return
deprecate_action = self . _handle_deprecations ( argument_dest , ** kwargs )
if deprecate_action :
kwargs [ 'action' ] = deprecate_action
self . command_loader . argument_registry . register_cli_argument ( self . command_scope , argument_dest , arg_... |
def close ( self ) :
"""Explicitly kill this cursor on the server . Call like ( in Tornado ) :
. . code - block : : python
yield cursor . close ( )""" | if not self . closed :
self . closed = True
yield self . _framework . yieldable ( self . _close ( ) ) |
def Pc ( x , y ) :
r'''Basic helper calculator which accepts a transformed R1 and NTU1 as
inputs for a common term used in the calculation of the P - NTU method for
plate exchangers .
Returns a value which is normally used in other calculations before the
actual P1 is calculated . Nominally used in counterf... | try :
term = exp ( - x * ( 1. - y ) )
return ( 1. - term ) / ( 1. - y * term )
except ZeroDivisionError :
return x / ( 1. + x ) |
def _parse_network_settings ( opts , current ) :
'''Filters given options and outputs valid settings for
the global network settings file .''' | # Normalize keys
opts = dict ( ( k . lower ( ) , v ) for ( k , v ) in six . iteritems ( opts ) )
current = dict ( ( k . lower ( ) , v ) for ( k , v ) in six . iteritems ( current ) )
# Check for supported parameters
retain_settings = opts . get ( 'retain_settings' , False )
result = current if retain_settings else { }
... |
def emd ( a , b , M , numItermax = 100000 , log = False ) :
"""Solves the Earth Movers distance problem and returns the OT matrix
. . math : :
\gamma = arg\min_\gamma <\gamma,M>_F
s . t . \ gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the metric cost matrix
- a and b are the sample weights ... | a = np . asarray ( a , dtype = np . float64 )
b = np . asarray ( b , dtype = np . float64 )
M = np . asarray ( M , dtype = np . float64 )
# if empty array given then use unifor distributions
if len ( a ) == 0 :
a = np . ones ( ( M . shape [ 0 ] , ) , dtype = np . float64 ) / M . shape [ 0 ]
if len ( b ) == 0 :
... |
def set_room_alias ( self , room_id , room_alias ) :
"""Set alias to room id
Args :
room _ id ( str ) : The room id .
room _ alias ( str ) : The room wanted alias name .""" | data = { "room_id" : room_id }
return self . _send ( "PUT" , "/directory/room/{}" . format ( quote ( room_alias ) ) , content = data ) |
def merge_dictionary ( dst , src , extend_lists = False ) :
"""Recursively merge two dicts .
Hashes at the root level are NOT overwritten . This can be used to merge two
dicts using deep key evaluation ( with support for merging lists as well ) .
There is also logic to handle placeholders ( ` None ` ) in list... | stack = [ ( dst , src ) ]
while stack :
current_dst , current_src = stack . pop ( )
for key in current_src :
source = current_src [ key ]
if key not in current_dst :
current_dst [ key ] = source
else :
dest = current_dst [ key ]
if isinstance ( source ... |
def _load ( self , time_series ) :
"""Load time series into a TimeSeries object .
: param timeseries : a TimeSeries , a dictionary or a path to a csv file ( str ) .
: return TimeSeries : a TimeSeries object .""" | if isinstance ( time_series , TimeSeries ) :
return time_series
if isinstance ( time_series , dict ) :
return TimeSeries ( time_series )
return TimeSeries ( utils . read_csv ( time_series ) ) |
def parse_package_for_version ( name ) :
"""Searches for a variable named _ _ version _ _ in name ' s _ _ init _ _ . py file and
returns the value . This function parses the source text . It does not load
the module .""" | from utool import util_regex
init_fpath = join ( name , '__init__.py' )
version_errmsg = textwrap . dedent ( '''
You must include a __version__ variable
in %s\'s __init__.py file.
Try something like:
__version__ = '1.0.0.dev1' ''' % ( name , ) )
if not exists ( init_fpath ) :
raise A... |
def _getScalesDiag ( self , termx = 0 ) :
"""Internal function for parameter initialization
Uses 2 term single trait model to get covar params for initialization
Args :
termx : non - noise term terms that is used for initialization""" | assert self . P > 1 , 'VarianceDecomposition:: diagonal init_method allowed only for multi trait models'
assert self . noisPos is not None , 'VarianceDecomposition:: noise term has to be set'
assert termx < self . n_randEffs - 1 , 'VarianceDecomposition:: termx>=n_randEffs-1'
assert self . trait_covar_type [ self . noi... |
def pt2leaf ( self , x ) :
"""Get the leaf which domain contains x .""" | if self . leafnode :
return self
else :
if x [ self . split_dim ] < self . split_value :
return self . lower . pt2leaf ( x )
else :
return self . greater . pt2leaf ( x ) |
def __getAvatar ( self , web ) :
"""Scrap the avatar from a GitHub profile .
: param web : parsed web .
: type web : BeautifulSoup node .""" | try :
self . avatar = web . find ( "img" , { "class" : "avatar" } ) [ 'src' ] [ : - 10 ]
except IndexError as error :
print ( "There was an error with the user " + self . name )
print ( error )
except AttributeError as error :
print ( "There was an error with the user " + self . name )
print ( error... |
def search ( self , search_phrase , limit = None ) :
"""Finds partitions by search phrase .
Args :
search _ phrase ( str or unicode ) :
limit ( int , optional ) : how many results to generate . None means without limit .
Generates :
PartitionSearchResult instances .""" | query , query_params = self . _make_query_from_terms ( search_phrase , limit = limit )
self . _parsed_query = ( str ( query ) , query_params )
if query is not None :
self . backend . library . database . set_connection_search_path ( )
results = self . execute ( query , ** query_params )
for result in result... |
def get_teachers_sorted ( self ) :
"""Get teachers sorted by last name .
This is used for the announcement request page .""" | teachers = self . get_teachers ( )
teachers = [ ( u . last_name , u . first_name , u . id ) for u in teachers ]
for t in teachers :
if t is None or t [ 0 ] is None or t [ 1 ] is None or t [ 2 ] is None :
teachers . remove ( t )
for t in teachers :
if t [ 0 ] is None or len ( t [ 0 ] ) <= 1 :
tea... |
def formatedTime ( ms ) :
"""convert milliseconds in a human readable time
> > > formatedTime ( 60e3)
'1m '
> > > formatedTime ( 1000e3)
'16m 40s '
> > > formatedTime ( 200000123)
'2d 7h 33m 20.123s '""" | if ms :
s = ms / 1000.0
m , s = divmod ( s , 60 )
h , m = divmod ( m , 60 )
d , h = divmod ( h , 24 )
out = ''
if d :
out += '%gd ' % d
if h :
out += '%gh ' % h
if m :
out += '%gm ' % m
if s :
out += '%gs ' % s
return out [ : - 1 ]
return '' |
def plot_sampler_fingerprint ( sampler , hyperprior , weights = None , cutoff_weight = None , nbins = None , labels = None , burn = 0 , chain_mask = None , temp_idx = 0 , points = None , plot_samples = False , sample_color = 'k' , point_color = None , point_lw = 3 , title = '' , rot_x_labels = False , figsize = None ) ... | try :
k = sampler . flatchain . shape [ - 1 ]
except AttributeError : # Assumes array input is only case where there is no " flatchain " attribute .
k = sampler . shape [ - 1 ]
# Process the samples :
if isinstance ( sampler , emcee . EnsembleSampler ) :
if chain_mask is None :
chain_mask = scipy . ... |
def create_zip ( archive , compression , cmd , verbosity , interactive , filenames ) :
"""Create a ZIP archive with the zipfile Python module .""" | try :
with zipfile . ZipFile ( archive , 'w' ) as zfile :
for filename in filenames :
if os . path . isdir ( filename ) :
write_directory ( zfile , filename )
else :
zfile . write ( filename )
except Exception as err :
msg = "error creating %s: %s"... |
async def create_group ( self , * recipients ) :
r"""| coro |
Creates a group direct message with the recipients
provided . These recipients must be have a relationship
of type : attr : ` RelationshipType . friend ` .
. . note : :
This only applies to non - bot accounts .
Parameters
\ * recipients : :... | from . channel import GroupChannel
if len ( recipients ) < 2 :
raise ClientException ( 'You must have two or more recipients to create a group.' )
users = [ str ( u . id ) for u in recipients ]
data = await self . _state . http . start_group ( self . id , users )
return GroupChannel ( me = self , data = data , stat... |
async def runOnceNicely ( self ) :
"""Execute ` runOnce ` with a small tolerance of 0.01 seconds so that the Prodables
can complete their other asynchronous tasks not running on the event - loop .""" | start = time . perf_counter ( )
msgsProcessed = await self . prodAllOnce ( )
if msgsProcessed == 0 : # if no let other stuff run
await asyncio . sleep ( 0.01 , loop = self . loop )
dur = time . perf_counter ( ) - start
if dur >= 15 :
logger . info ( "it took {:.3f} seconds to run once nicely" . format ( dur ) ,... |
def single_column ( num_lev = 30 , water_depth = 1. , lev = None , ** kwargs ) :
"""Creates domains for a single column of atmosphere overlying a slab of water .
Can also pass a pressure array or pressure level axis object specified in ` ` lev ` ` .
If argument ` ` lev ` ` is not ` ` None ` ` then function trie... | if lev is None :
levax = Axis ( axis_type = 'lev' , num_points = num_lev )
elif isinstance ( lev , Axis ) :
levax = lev
else :
try :
levax = Axis ( axis_type = 'lev' , points = lev )
except :
raise ValueError ( 'lev must be Axis object or pressure array' )
depthax = Axis ( axis_type = 'd... |
def _cleanup ( self , kill , verbose ) :
"""Look for dead components ( weight = 0 ) and remove them
if enabled by ` ` kill ` ` .
Resize storage . Recompute determinant and covariance .""" | if kill :
removed_indices = self . g . prune ( )
self . nout -= len ( removed_indices )
if verbose and removed_indices :
print ( 'Removing %s' % removed_indices )
for j in removed_indices :
self . inv_map . pop ( j [ 0 ] ) |
def config_cred ( config , providers ) :
"""Read credentials from configfile .""" | expected = [ 'aws' , 'azure' , 'gcp' , 'alicloud' ]
cred = { }
to_remove = [ ]
for item in providers :
if any ( item . startswith ( itemb ) for itemb in expected ) :
try :
cred [ item ] = dict ( list ( config [ item ] . items ( ) ) )
except KeyError as e :
print ( "No credent... |
def query_api ( self , q , s , g , ** kwargs ) : # noqa : E501
"""Perform a charting query against Wavefront servers that returns the appropriate points in the specified time window and granularity # noqa : E501
Long time spans and small granularities can take a long time to calculate # noqa : E501
This method ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . query_api_with_http_info ( q , s , g , ** kwargs )
# noqa : E501
else :
( data ) = self . query_api_with_http_info ( q , s , g , ** kwargs )
# noqa : E501
return data |
def prep_db_parallel ( samples , parallel_fn ) :
"""Prepares gemini databases in parallel , handling jointly called populations .""" | batch_groups , singles , out_retrieve , extras = _group_by_batches ( samples , _has_variant_calls )
to_process = [ ]
has_batches = False
for ( name , caller ) , info in batch_groups . items ( ) :
fnames = [ x [ 0 ] for x in info ]
to_process . append ( [ fnames , ( str ( name ) , caller , True ) , [ x [ 1 ] for... |
def msg2processor ( msg , ** config ) :
"""For a given message return the text processor that can handle it .
This will raise a : class : ` fedmsg . meta . ProcessorsNotInitialized ` exception
if : func : ` fedmsg . meta . make _ processors ` hasn ' t been called yet .""" | for processor in processors :
if processor . handle_msg ( msg , ** config ) is not None :
return processor
else :
return processors [ - 1 ] |
def parse_fully_qualified_name ( fq_name : str ) -> Tuple [ Optional [ str ] , str ] :
"""Parse the given fully - quallified name ( separated with dots ) to a tuple of module and class names .
: param fq _ name : fully qualified name separated with dots
: return : ` ` None ` ` instead of module if the given nam... | last_dot = fq_name . rfind ( '.' )
if last_dot != - 1 :
return fq_name [ : last_dot ] , fq_name [ last_dot + 1 : ]
else :
return None , fq_name |
def solution ( swarm ) :
"""Determines the global best particle in the swarm .
Args :
swarm : iterable : an iterable that yields all particles in the swarm .
Returns :
cipy . algorithms . pso . Particle : The best particle in the swarm when
comparing the best _ fitness values of the particles .""" | best = swarm [ 0 ]
cmp = comparator ( best . best_fitness )
for particle in swarm :
if cmp ( particle . best_fitness , best . best_fitness ) :
best = particle
return best |
def predict ( self , h = 5 , intervals = False , ** kwargs ) :
"""Makes forecast with the estimated model
Parameters
h : int ( default : 5)
How many steps ahead would you like to forecast ?
intervals : boolean ( default : False )
Whether to return prediction intervals
Returns
- pd . DataFrame with pre... | nsims = kwargs . get ( 'nsims' , 200 )
if self . latent_variables . estimated is False :
raise Exception ( "No latent variables estimated!" )
else : # Retrieve data , dates and ( transformed ) latent variables
if self . latent_variables . estimation_method in [ 'M-H' ] :
lower_1_final = 0
upper_... |
def snpplot ( args ) :
"""% prog counts . cdt
Illustrate the histogram per SNP site .""" | p = OptionParser ( snpplot . __doc__ )
opts , args , iopts = p . set_image_options ( args , format = "png" )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
datafile , = args
# Read in CDT file
fp = open ( datafile )
next ( fp )
next ( fp )
data = [ ]
for row in fp :
atoms = row . split ( ) [ 4 : ]... |
def main ( ) :
"""Command line entry point for dcal .""" | if "--help" in sys . argv or "-h" in sys . argv or len ( sys . argv ) > 3 :
raise SystemExit ( __doc__ )
try :
discordian_calendar ( * sys . argv [ 1 : ] )
except ValueError as error :
raise SystemExit ( "Error: {}" . format ( "\n" . join ( error . args ) ) ) |
def setup_argument_parser ( ) :
"""Sets up teh parser with the required arguments
: return : The parser object""" | default_config_path = filesystem . get_default_config_path ( )
filesystem . create_path ( default_config_path )
parser = core_singletons . argument_parser
parser . add_argument ( '-n' , '--new' , action = 'store_true' , help = _ ( "whether to create a new state-machine" ) )
parser . add_argument ( '-o' , '--open' , act... |
def run_forecast ( self ) :
"""Updates card & runs for RAPID to GSSHA & LSM to GSSHA""" | # LSM to GSSHA
self . prepare_hmet ( )
self . prepare_gag ( )
# RAPID to GSSHA
self . rapid_to_gssha ( )
# HOTSTART
self . hotstart ( )
# Run GSSHA
return self . run ( ) |
def _add_info ( self , msg , ** kwargs ) :
"""Add information to a SAML message . If the attribute is not part of
what ' s defined in the SAML standard add it as an extension .
: param msg :
: param kwargs :
: return :""" | args , extensions = self . _filter_args ( msg , ** kwargs )
for key , val in args . items ( ) :
setattr ( msg , key , val )
if extensions :
if msg . extension_elements :
msg . extension_elements . extend ( extensions )
else :
msg . extension_elements = extensions |
def create_attachment ( self , upload_stream , file_name , repository_id , pull_request_id , project = None , ** kwargs ) :
"""CreateAttachment .
[ Preview API ] Attach a new file to a pull request .
: param object upload _ stream : Stream to upload
: param str file _ name : The name of the file .
: param s... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if file_name is not None :
route_values [ 'fileName' ] = self . _serialize . url ( 'file_name' , file_name , 'str' )
if repository_id is not None :
route_values [ 'repositoryId' ]... |
def is_installable_dir ( path ) :
"""Return True if ` path ` is a directory containing a setup . py file .""" | if not os . path . isdir ( path ) :
return False
setup_py = os . path . join ( path , "setup.py" )
if os . path . isfile ( setup_py ) :
return True
return False |
def L_fc ( fdata ) :
"""Apply L in the Fourier domain .""" | fd = np . copy ( fdata )
dphi_fc ( fdata )
divsin_fc ( fdata )
dtheta_fc ( fd )
return ( 1j * fdata , - 1j * fd ) |
def register_unused_addresses ( wallet_obj , subchain_index , num_addrs = 1 ) :
'''Hit / derive to register new unused _ addresses on a subchain _ index and verify them client - side
Returns a list of dicts of the following form :
{ ' address ' : ' 1abc123 . . . ' , ' path ' : ' m / 0/9 ' , ' public ' : ' 01234... | verbose_print ( 'register_unused_addresses called on subchain %s for %s addrs' % ( subchain_index , num_addrs , ) )
assert type ( subchain_index ) is int , subchain_index
assert type ( num_addrs ) is int , num_addrs
assert num_addrs > 0
mpub = wallet_obj . serialize_b58 ( private = False )
coin_symbol = coin_symbol_fro... |
def reset ( self ) :
"""Start a new episode .""" | self . _episode_steps = 0
if self . _episode_count : # No need to restart for the first episode .
self . _restart ( )
self . _episode_count += 1
logging . info ( "Starting episode: %s" , self . _episode_count )
self . _metrics . increment_episode ( )
self . _last_score = [ 0 ] * self . _num_agents
self . _state = e... |
def main ( ) -> None :
"""Main function of this script""" | # Make sure we have access to self
if 'self' not in globals ( ) :
print ( "Run 'set locals_in_py true' and then rerun this script" )
return
# Make sure the user passed in an output file
if len ( sys . argv ) != 2 :
print ( "Usage: {} <output_file>" . format ( os . path . basename ( sys . argv [ 0 ] ) ) )
... |
def update_instance ( InstanceId = None , LayerIds = None , InstanceType = None , AutoScalingType = None , Hostname = None , Os = None , AmiId = None , SshKeyName = None , Architecture = None , InstallUpdatesOnBoot = None , EbsOptimized = None , AgentVersion = None ) :
"""Updates a specified instance .
See also :... | pass |
def complete_offset_upload ( self , chunk_num ) : # type : ( Descriptor , int ) - > None
"""Complete the upload for the offset
: param Descriptor self : this
: param int chunk _ num : chunk num completed""" | with self . _meta_lock :
self . _outstanding_ops -= 1
# save resume state
if self . is_resumable : # only set resumable completed if all replicas for this
# chunk are complete
if blobxfer . util . is_not_empty ( self . _ase . replica_targets ) :
if chunk_num not in self . _replica_co... |
def register_channel ( im0 , im1 , scale = None , ch0angle = None , chanapproxangle = None ) :
"""Register the images assuming they are channels
Parameters :
im0 : 2d array
The first image
im1 : 2d array
The second image
scale : number , optional
The scale difference if known
ch0angle : number , opt... | im0 = np . asarray ( im0 )
im1 = np . asarray ( im1 )
# extract the channels edges
e0 = edge ( im0 )
e1 = edge ( im1 )
fe0 , fe1 = reg . dft_optsize_same ( np . float32 ( e0 ) , np . float32 ( e1 ) )
# compute the angle and channel width of biggest angular feature
w0 , a0 = channel_width ( fe0 , isccsedge = True , chan... |
def add_view_data ( self , view_data ) :
"""Add view data object to be sent to server""" | self . register_view ( view_data . view )
v_name = get_view_name ( self . options . namespace , view_data . view )
self . view_name_to_data_map [ v_name ] = view_data |
def _get_order_by ( order , orderby , order_by_fields ) :
"""Return the order by syntax for a model .
Checks whether use ascending or descending order , and maps the fieldnames .""" | try : # Find the actual database fieldnames for the keyword .
db_fieldnames = order_by_fields [ orderby ]
except KeyError :
raise ValueError ( "Invalid value for 'orderby': '{0}', supported values are: {1}" . format ( orderby , ', ' . join ( sorted ( order_by_fields . keys ( ) ) ) ) )
# Default to descending fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.