signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def create_cluster_role ( self , body , ** kwargs ) :
"""create a ClusterRole
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . create _ cluster _ role ( body , async _ req = True )
> > > result = thread . get... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . create_cluster_role_with_http_info ( body , ** kwargs )
else :
( data ) = self . create_cluster_role_with_http_info ( body , ** kwargs )
return data |
def pdist ( objects , dmeasure , diagval = numpy . inf ) :
"""Compute the pair - wise distances between arbitrary objects .
Notes
` ` dmeasure ` ` is assumed to be * symmetry * i . e . between object * a * and object * b * the
function will be called only ones .
Parameters
objects : sequence
A sequence ... | out = numpy . zeros ( [ len ( objects ) ] * 2 , numpy . float )
numpy . fill_diagonal ( out , diagval )
for idx1 , idx2 in combinations ( list ( range ( len ( objects ) ) ) , 2 ) :
out [ idx1 , idx2 ] = dmeasure ( objects [ idx1 ] , objects [ idx2 ] )
return out + out . T |
def ttfautohint ( in_file , out_file , args = None , ** kwargs ) :
"""Thin wrapper around the ttfautohint command line tool .
Can take in command line arguments directly as a string , or spelled out as
Python keyword arguments .""" | arg_list = [ "ttfautohint" ]
file_args = [ in_file , out_file ]
if args is not None :
if kwargs :
raise TypeError ( "Should not provide both cmd args and kwargs." )
rv = subprocess . call ( arg_list + args . split ( ) + file_args )
if rv != 0 :
raise TTFAError ( rv )
return
boolean_optio... |
def pre_delete_title ( instance , ** kwargs ) :
'''Update article . languages''' | if instance . article . languages :
languages = instance . article . languages . split ( ',' )
else :
languages = [ ]
if instance . language in languages :
languages . remove ( instance . language )
instance . article . languages = ',' . join ( languages )
instance . article . _publisher_keep_state ... |
def process_request ( self , request , client_address ) :
"""Fork a new subprocess to process the request .""" | self . collect_children ( )
pid = os . fork ( )
# @ UndefinedVariable
if pid : # Parent process
if self . active_children is None :
self . active_children = [ ]
self . active_children . append ( pid )
self . close_request ( request )
# close handle in parent process
return
else : # Child pro... |
def list_members ( slug , owner_screen_name , limit = 1e10 ) :
"""See https : / / dev . twitter . com / rest / reference / get / lists / members""" | cursor = - 1
members = [ ]
try :
response = twapi . request ( 'lists/members' , { 'slug' : slug , 'owner_screen_name' : owner_screen_name , 'cursor' : cursor , 'count' : 5000 } )
if response . status_code in [ 88 , 130 , 420 , 429 ] : # rate limit
sys . stderr . write ( 'Error for %s/%s: %s\nSleeping fo... |
def configure ( self , options , conf ) :
"""Turn style - forcing on if bar - forcing is on .
It ' d be messy to position the bar but still have the rest of the
terminal capabilities emit ' ' .""" | super ( ProgressivePlugin , self ) . configure ( options , conf )
if ( getattr ( options , 'verbosity' , 0 ) > 1 and getattr ( options , 'enable_plugin_id' , False ) ) : # TODO : Can we forcibly disable the ID plugin ?
print ( 'Using --with-id and --verbosity=2 or higher with ' 'nose-progressive causes visualizatio... |
def generate_exact ( self , model , vcpu_num , host_cpu ) :
"""Generate exact CPU model with nested virtualization CPU feature .
Args :
model ( str ) : libvirt supported CPU model
vcpu _ num ( int ) : number of virtual cpus
host _ cpu ( lxml . etree . Element ) : the host CPU model
Returns :
lxml . etre... | nested = { 'Intel' : 'vmx' , 'AMD' : 'svm' }
cpu = ET . Element ( 'cpu' , match = 'exact' )
ET . SubElement ( cpu , 'model' ) . text = model
cpu . append ( self . generate_topology ( vcpu_num ) )
vendor = host_cpu . findtext ( 'vendor' )
if not nested . get ( vendor ) :
LOGGER . debug ( 'Unknown vendor: {0}, did no... |
def ascdiff ( decl , lat ) :
"""Returns the Ascensional Difference of a point .""" | delta = math . radians ( decl )
phi = math . radians ( lat )
ad = math . asin ( math . tan ( delta ) * math . tan ( phi ) )
return math . degrees ( ad ) |
def relabel ( self , label = None , group = None , depth = 0 ) :
"""Clone object and apply new group and / or label .
Applies relabeling to children up to the supplied depth .
Args :
label ( str , optional ) : New label to apply to returned object
group ( str , optional ) : New group to apply to returned ob... | new_data = self . data
if ( depth > 0 ) and getattr ( self , '_deep_indexable' , False ) :
new_data = [ ]
for k , v in self . data . items ( ) :
relabelled = v . relabel ( group = group , label = label , depth = depth - 1 )
new_data . append ( ( k , relabelled ) )
keywords = [ ( 'label' , label ... |
def list_cache_settings ( self , service_id , version_number ) :
"""Get a list of all cache settings for a particular service and version .""" | content = self . _fetch ( "/service/%s/version/%d/cache_settings" % ( service_id , version_number ) )
return map ( lambda x : FastlyCacheSettings ( self , x ) , content ) |
def isAspecting ( obj1 , obj2 , aspList ) :
"""Returns if obj1 aspects obj2 within its orb ,
considering a list of possible aspect types .""" | aspDict = _aspectDict ( obj1 , obj2 , aspList )
if aspDict :
return aspDict [ 'orb' ] < obj1 . orb ( )
return False |
def separator_width ( self , value ) :
"""Setter for * * self . _ _ separator _ width * * attribute .
: param value : Attribute value .
: type value : int""" | if value is not None :
assert type ( value ) is int , "'{0}' attribute: '{1}' type is not 'int'!" . format ( "separator_width" , value )
assert value > 0 , "'{0}' attribute: '{1}' need to be exactly positive!" . format ( "separator_width" , value )
self . __separator_width = value |
def find_dist_to_centroid ( cvects , idx_list , weights = None ) :
"""Find the centroid for a set of vectors
Parameters
cvects : ~ numpy . ndarray ( 3 , nsrc ) with directional cosine ( i . e . , x , y , z component ) values
idx _ list : [ int , . . . ]
list of the source indices in the cluster
weights : ... | centroid = find_centroid ( cvects , idx_list , weights )
dist_vals = np . degrees ( np . arccos ( ( centroid * cvects . T [ idx_list ] ) . sum ( 1 ) ) )
return dist_vals , centroid |
def eval ( w , t , x , msk , s ) :
"""Pythia server - side computation of intermediate PRF output .
@ w : ensemble key selector ( any string , e . g . webserver ID )
@ t : tweak ( any string , e . g . user ID )
@ x : message ( any string )
@ msk : Pythia server ' s master secret key
@ s : state value from... | # Verify types
assertType ( w , ( str , int , long ) )
assertType ( t , ( str , int , long ) )
assertType ( x , ( str , int , long ) )
# Construct the key
kw = genKw ( w , msk , s )
# Compute y
beta = hashG1 ( t , x )
y = beta * kw
return y , kw , beta |
def check_file_blocks ( self , path , size , block_list , ** kwargs ) :
"""文件块检查
: param path : 文件路径
: param size : 文件大小
: param block _ list : 文件块的列表 , 注意按文件块顺序
: type block _ list : list
. . note : :
如果服务器不存在path的文件 , 则返回中的block _ list会等于提交的block _ list
: return : requests . Response
. . note : : ... | data = { 'path' : path , 'size' : size , 'isdir' : 0 , 'block_list' : json . dumps ( block_list ) }
return self . _request ( 'precreate' , 'post' , data = data , ** kwargs ) |
def prepare ( cls , value ) :
"""Pack datetime value into proper binary format""" | pfield = struct . pack ( 'b' , cls . type_code )
if isinstance ( value , string_types ) :
value = datetime . datetime . strptime ( value , "%Y-%m-%d" )
year = value . year | 0x8000
# for some unknown reasons year has to be bit - or ' ed with 0x8000
month = value . month - 1
# for some unknown reasons HANA counts mo... |
def adsb_vehicle_send ( self , ICAO_address , lat , lon , altitude_type , altitude , heading , hor_velocity , ver_velocity , callsign , emitter_type , tslc , flags , squawk , force_mavlink1 = False ) :
'''The location and information of an ADSB vehicle
ICAO _ address : ICAO address ( uint32 _ t )
lat : Latitude... | return self . send ( self . adsb_vehicle_encode ( ICAO_address , lat , lon , altitude_type , altitude , heading , hor_velocity , ver_velocity , callsign , emitter_type , tslc , flags , squawk ) , force_mavlink1 = force_mavlink1 ) |
def check_subscriber_key_length ( app_configs = None , ** kwargs ) :
"""Check that DJSTRIPE _ SUBSCRIBER _ CUSTOMER _ KEY fits in metadata .
Docs : https : / / stripe . com / docs / api # metadata""" | from . import settings as djstripe_settings
messages = [ ]
key = djstripe_settings . SUBSCRIBER_CUSTOMER_KEY
key_size = len ( str ( key ) )
if key and key_size > 40 :
messages . append ( checks . Error ( "DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY must be no more than 40 characters long" , hint = "Current value: %r (%i chara... |
def load_val_from_git_cfg ( cfg_key_suffix ) :
"""Retrieve one option from Git config .""" | cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}'
cmd = "git" , "config" , "--local" , "--get" , cfg_key
try :
return ( subprocess . check_output ( cmd , stderr = subprocess . DEVNULL ) . strip ( ) . decode ( "utf-8" ) )
except subprocess . CalledProcessError :
return None |
def build_from_info ( cls , info ) :
"""build a Term instance from a dict
Parameters
cls : class
info : dict
contains all information needed to build the term
Return
Term instance""" | info = deepcopy ( info )
if 'term_type' in info :
cls_ = TERMS [ info . pop ( 'term_type' ) ]
if issubclass ( cls_ , MetaTermMixin ) :
return cls_ . build_from_info ( info )
else :
cls_ = cls
return cls_ ( ** info ) |
def request_data ( self ) :
'''在调用dialog . run ( ) 之前先调用这个函数来获取数据''' | def on_tasks_received ( info , error = None ) :
if error or not info :
logger . error ( 'BTBrowserDialog.on_tasks_received: %s, %s.' % ( info , error ) )
return
if 'magnet_info' in info :
tasks = info [ 'magnet_info' ]
elif 'torrent_info' in info :
tasks = info [ 'torrent_inf... |
def apply ( self , sim_time ) :
"""Apply the event and
: param sim _ time :
: return :""" | if not self . n :
return
# skip if already applied
if self . _last_time != sim_time :
self . _last_time = sim_time
else :
return |
def addattr ( self , attrname , value = None , persistent = True ) :
"""Adds an attribute to self . If persistent is True , the attribute will
be made a persistent attribute . Persistent attributes are copied
whenever a view or copy of this array is created . Otherwise , new views
or copies of this will not h... | setattr ( self , attrname , value )
# add as persistent
if persistent and attrname not in self . __persistent_attributes__ :
self . __persistent_attributes__ . append ( attrname ) |
def MultiHeadedAttentionQKV ( feature_depth , num_heads = 8 , dropout = 0.0 , mode = 'train' ) :
"""Transformer - style multi - headed attention .
Accepts inputs of the form ( q , k , v ) , mask .
Args :
feature _ depth : int : depth of embedding
num _ heads : int : number of attention heads
dropout : flo... | return combinators . Serial ( combinators . Parallel ( combinators . Parallel ( core . Dense ( feature_depth ) , core . Dense ( feature_depth ) , core . Dense ( feature_depth ) , ) , combinators . Identity ( ) ) , PureMultiHeadedAttention ( # pylint : disable = no - value - for - parameter
feature_depth = feature_depth... |
async def async_set_config ( self , data ) :
"""Set config of thermostat .
" mode " : " auto " ,
" heatsetpoint " : 180,""" | field = self . deconz_id + '/config'
await self . _async_set_state_callback ( field , data ) |
def on_session_destroyed ( self , * callbacks ) :
'''Provide callbacks to invoke when the session serving the Document
is destroyed''' | for callback in callbacks :
_check_callback ( callback , ( 'session_context' , ) )
self . _session_destroyed_callbacks . add ( callback ) |
def fig4 ( args ) :
"""% prog fig4 layout data
Napus Figure 4A displays an example deleted region for quartet chromosomes ,
showing read alignments from high GL and low GL lines .""" | p = OptionParser ( fig4 . __doc__ )
p . add_option ( "--gauge_step" , default = 200000 , type = "int" , help = "Step size for the base scale" )
opts , args , iopts = p . set_image_options ( args , figsize = "9x7" )
if len ( args ) != 2 :
sys . exit ( not p . print_help ( ) )
layout , datadir = args
layout = F4ALayo... |
def ellipse ( self , x , y , width , height , color ) :
"""See the Processing function ellipse ( ) :
https : / / processing . org / reference / ellipse _ . html""" | self . context . set_source_rgb ( * color )
self . context . save ( )
self . context . translate ( self . tx ( x + ( width / 2.0 ) ) , self . ty ( y + ( height / 2.0 ) ) )
self . context . scale ( self . tx ( width / 2.0 ) , self . ty ( height / 2.0 ) )
self . context . arc ( 0.0 , 0.0 , 1.0 , 0.0 , 2 * math . pi )
sel... |
def __get_stored_instances ( self , factory_name ) : # type : ( str ) - > List [ StoredInstance ]
"""Retrieves the list of all stored instances objects corresponding to
the given factory name
: param factory _ name : A factory name
: return : All components instantiated from the given factory""" | with self . __instances_lock :
return [ stored_instance for stored_instance in self . __instances . values ( ) if stored_instance . factory_name == factory_name ] |
def watch ( filenames , callback , use_sudo = False ) :
"""Call callback if any of filenames change during the context""" | filenames = [ filenames ] if isinstance ( filenames , basestring ) else filenames
old_md5 = { fn : md5sum ( fn , use_sudo ) for fn in filenames }
yield
for filename in filenames :
if md5sum ( filename , use_sudo ) != old_md5 [ filename ] :
callback ( )
return |
def remove_subproducts ( self ) :
"""Removes all archived files subproducts associated with this DP""" | if not self . fullpath or not self . archived :
raise RuntimeError ( """Can't remove a non-archived data product""" )
for root , dirs , files in os . walk ( self . subproduct_dir ( ) , topdown = False ) :
for name in files :
try :
os . remove ( os . path . join ( root , name ) )
exce... |
def password_input ( * args , ** kwargs ) :
'''Get a password''' | password_input = wtforms . PasswordField ( * args , ** kwargs )
password_input . input_type = 'password'
return password_input |
def get_tasks ( self ) :
"""Returns an ordered dictionary { task _ name : task } of all tasks within this workflow .
: return : Ordered dictionary with key being task _ name ( str ) and an instance of a corresponding task from this
workflow
: rtype : OrderedDict""" | tasks = collections . OrderedDict ( )
for dep in self . ordered_dependencies :
tasks [ dep . name ] = dep . task
return tasks |
def handle ( self , pkt , raddress , rport ) :
"Handle a packet , hopefully an ACK since we just sent a DAT ." | if isinstance ( pkt , TftpPacketACK ) :
log . debug ( "Received ACK for packet %d" % pkt . blocknumber )
# Is this an ack to the one we just sent ?
if self . context . next_block == pkt . blocknumber :
if self . context . pending_complete :
log . info ( "Received ACK to final DAT, we're ... |
def do_hash ( hash_algo , marfile , asn1 = False ) :
"""Output the hash for this MAR file .""" | # Add a dummy signature into a temporary file
dst = tempfile . TemporaryFile ( )
with open ( marfile , 'rb' ) as f :
add_signature_block ( f , dst , hash_algo )
dst . seek ( 0 )
with MarReader ( dst ) as m :
hashes = m . calculate_hashes ( )
h = hashes [ 0 ] [ 1 ]
if asn1 :
h = format_hash ( h ,... |
def put ( self , message ) :
"""Put a message into the outgoing message stack .
Outgoing message will be stored indefinitely to support multi - users .""" | with self . _outgoing_lock :
self . _outgoing . append ( message )
self . _outgoing_counter += 1
# Check to see if there are pending queues waiting for the item .
if self . _outgoing_counter in self . _outgoing_pending_queues :
for q in self . _outgoing_pending_queues [ self . _outgoing_counter ... |
def make_modular ( self , rebuild = False ) :
"""Find and return all : class : ` Molecule ` s in : class : ` MolecularSystem ` .
This function populates : attr : ` MolecularSystem . molecules ` with
: class : ` Molecule ` s .
Parameters
rebuild : : class : ` bool `
If True , run first the : func : ` rebui... | if rebuild is True :
supercell_333 = create_supercell ( self . system )
else :
supercell_333 = None
dis = discrete_molecules ( self . system , rebuild = supercell_333 )
self . no_of_discrete_molecules = len ( dis )
self . molecules = { }
for i in range ( len ( dis ) ) :
self . molecules [ i ] = Molecule ( d... |
def multi_platform_open ( cmd ) :
"""Take the given command and use the OS to automatically open the appropriate
resource . For instance , if a URL is provided , this will have the OS automatically
open the URL in the default web browser .""" | if platform == "linux" or platform == "linux2" :
cmd = [ 'xdg-open' , cmd ]
elif platform == "darwin" :
cmd = [ 'open' , cmd ]
elif platform == "win32" :
cmd = [ 'start' , cmd ]
subprocess . check_call ( cmd ) |
def s_rec2latex ( r , empty = "" ) :
"""Export a recarray * r * to a LaTeX table in a string""" | latex = ""
names = r . dtype . names
def translate ( x ) :
if x is None or str ( x ) . lower == "none" :
x = empty
return latex_quote ( x )
latex += r"\begin{tabular}{%s}" % ( "" . join ( [ "c" ] * len ( names ) ) , ) + "\n"
# simple c columns
latex += r"\hline" + "\n"
latex += " & " . join ( [ latex_qu... |
def strip_pem ( x ) :
"""Strips PEM to bare base64 encoded form
: param x :
: return :""" | if x is None :
return None
x = to_string ( x )
pem = x . replace ( '-----BEGIN CERTIFICATE-----' , '' )
pem = pem . replace ( '-----END CERTIFICATE-----' , '' )
pem = re . sub ( r'-----BEGIN .+?-----' , '' , pem )
pem = re . sub ( r'-----END .+?-----' , '' , pem )
pem = pem . replace ( ' ' , '' )
pem = pem . replac... |
def status ( * args ) :
"""Get the current status of the fragments repository , limited to FILENAME ( s ) if specified .
Limit output to files with status STATUS , if present .""" | parser = argparse . ArgumentParser ( prog = "%s %s" % ( __package__ , status . __name__ ) , description = status . __doc__ )
parser . add_argument ( 'FILENAME' , help = "files to show status for" , nargs = "*" , default = [ '.' ] )
parser . add_argument ( '-l' , '--limit' , type = str , dest = "STATUS" , default = 'MDA... |
def OnDeactivateCard ( self , card ) :
"""Called when a card is deactivated in the reader tree control
or toolbar .""" | SimpleSCardAppEventObserver . OnActivateCard ( self , card )
self . feedbacktext . SetLabel ( 'Deactivated card: ' + repr ( card ) ) |
def map_ormclass ( self , name ) :
"""Populate _ mapped attribute with orm class
Parameters
name : str
Component part of orm class name . Concatenated with _ prefix .""" | try :
self . _mapped [ name ] = getattr ( self . _pkg , self . _prefix + name )
except AttributeError :
print ( 'Warning: Relation %s does not exist.' % name ) |
def dir_tails_target ( self , rr_id ) -> str :
"""Return target directory for revocation registry and tails file production .
: param rr _ id : revocation registry identifier
: return : tails target directory""" | return join ( self . dir_tails_top ( rr_id ) , rev_reg_id2cred_def_id ( rr_id ) ) |
def hours ( self ) :
"""Return the number of hours this entry has lasted . If the duration is a tuple with a start and an end time ,
the difference between the two times will be calculated . If the duration is a number , it will be returned
as - is .""" | if not isinstance ( self . duration , tuple ) :
return self . duration
if self . duration [ 1 ] is None :
return 0
time_start = self . get_start_time ( )
# This can happen if the previous entry has a non - tuple duration
# and the current entry has a tuple duration without a start time
if time_start is None :
... |
def get_scores_for_category ( cat_word_counts , not_cat_word_counts , scaler_algo = DEFAULT_SCALER_ALGO , beta = DEFAULT_BETA ) :
'''Computes unbalanced scaled - fscores
Parameters
category : str
category name to score
scaler _ algo : str
Function that scales an array to a range \ in [ 0 and 1 ] . Use ' p... | assert beta > 0
precision = ( cat_word_counts * 1. / ( cat_word_counts + not_cat_word_counts ) )
recall = cat_word_counts * 1. / cat_word_counts . sum ( )
precision_normcdf = ScaledFScore . _safe_scaler ( scaler_algo , precision )
recall_normcdf = ScaledFScore . _safe_scaler ( scaler_algo , recall )
scores = ( 1 + beta... |
def add_hyperedge ( self , nodes , attr_dict = None , ** attr ) :
"""Adds a hyperedge to the hypergraph , along with any related
attributes of the hyperedge .
This method will automatically add any node from the node set
that was not in the hypergraph .
A hyperedge without a " weight " attribute specified w... | attr_dict = self . _combine_attribute_arguments ( attr_dict , attr )
# Don ' t allow empty node set ( invalid hyperedge )
if not nodes :
raise ValueError ( "nodes argument cannot be empty." )
# Use frozensets for node sets to allow for hashable keys
frozen_nodes = frozenset ( nodes )
is_new_hyperedge = not self . h... |
def clock ( self , interval , basis = "system" ) :
"""Return a NodeInput tuple for triggering an event every interval .
Args :
interval ( int ) : The interval at which this input should
trigger . If basis = = system ( the default ) , this interval must
be in seconds . Otherwise it will be in units of whatev... | if basis == "system" :
if ( interval % 10 ) == 0 :
tick = self . allocator . attach_stream ( self . system_tick )
count = interval // 10
else :
tick = self . allocator . attach_stream ( self . fast_tick )
count = interval
trigger = InputTrigger ( u'count' , '>=' , count )
... |
def initial_update ( self , mapping ) :
'''Initially fills the underlying dictionary with keys , values and
timestamps .''' | for key , val in mapping . items ( ) :
_ , timestamp = val
if not self . TTL or ( datetime . utcnow ( ) - datetime . utcfromtimestamp ( timestamp ) < self . TTL ) :
self . __setitem__ ( key , val , raw = True ) |
def refresh ( self ) :
"""刷新 Question object 的属性 .
例如回答数增加了 , 先调用 ` ` refresh ( ) ` `
再访问 answer _ num 属性 , 可获得更新后的答案数量 .
: return : None""" | super ( ) . refresh ( )
self . _html = None
self . _title = None
self . _details = None
self . _answer_num = None
self . _follower_num = None
self . _topics = None
self . _last_edit_time = None
self . _logs = None |
def delete_object ( container_name , object_name , profile , ** libcloud_kwargs ) :
'''Delete an object in the cloud
: param container _ name : Container name
: type container _ name : ` ` str ` `
: param object _ name : Object name
: type object _ name : ` ` str ` `
: param profile : The profile key
: ... | conn = _get_driver ( profile = profile )
libcloud_kwargs = salt . utils . args . clean_kwargs ( ** libcloud_kwargs )
obj = conn . get_object ( container_name , object_name , ** libcloud_kwargs )
return conn . delete_object ( obj ) |
def get_closest_dt_idx ( dt , dt_list ) :
"""Get indices of dt _ list that is closest to input dt""" | from pygeotools . lib import malib
dt_list = malib . checkma ( dt_list , fix = False )
dt_diff = np . abs ( dt - dt_list )
return dt_diff . argmin ( ) |
def link ( self , req , ino , newparent , newname ) :
"""Create a hard link
Valid replies :
reply _ entry
reply _ err""" | self . reply_err ( req , errno . EROFS ) |
def _calc_concat_over ( datasets , dim , data_vars , coords ) :
"""Determine which dataset variables need to be concatenated in the result ,
and which can simply be taken from the first dataset .""" | # Return values
concat_over = set ( )
equals = { }
if dim in datasets [ 0 ] :
concat_over . add ( dim )
for ds in datasets :
concat_over . update ( k for k , v in ds . variables . items ( ) if dim in v . dims )
def process_subset_opt ( opt , subset ) :
if isinstance ( opt , str ) :
if opt == 'differ... |
def run ( self , argv ) :
"""Equivalent to the main program for the application .
: param argv : input arguments and options
: paramtype argv : list of str""" | try :
index = 0
command_pos = - 1
help_pos = - 1
help_command_pos = - 1
for arg in argv :
if arg == 'bash-completion' and help_command_pos == - 1 :
self . _bash_completion ( )
return 0
if arg in self . commands [ self . api_version ] :
if command_p... |
def is_enabled_path ( path ) :
"""Determine whether or not the path matches one or more paths
in the ENABLED _ PATHS setting .
: param path : A string describing the path to be matched .""" | for enabled_path in ENABLED_PATHS :
match = re . search ( enabled_path , path [ 1 : ] )
if match :
return True
return False |
def make_connector ( self , app = None , bind = None ) :
"""Creates the connector for a given state and bind .""" | return _EngineConnector ( self , self . get_app ( app ) , bind ) |
def haversine ( point1 , point2 , unit = 'km' ) :
"""Calculate the great - circle distance between two points on the Earth surface .
: input : two 2 - tuples , containing the latitude and longitude of each point
in decimal degrees .
Keyword arguments :
unit - - a string containing the initials of a unit of ... | # mean earth radius - https : / / en . wikipedia . org / wiki / Earth _ radius # Mean _ radius
AVG_EARTH_RADIUS_KM = 6371.0088
# Units values taken from http : / / www . unitconversion . org / unit _ converter / length . html
conversions = { 'km' : 1 , 'm' : 1000 , 'mi' : 0.621371192 , 'nmi' : 0.539956803 , 'ft' : 3280... |
def list_wildcard ( self , wildcard_path ) :
"""Yields full object URIs matching the given wildcard .
Currently only the ' * ' wildcard after the last path delimiter is supported .
( If we need " full " wildcard functionality we should bring in gsutil dependency with its
https : / / github . com / GoogleCloud... | path , wildcard_obj = wildcard_path . rsplit ( '/' , 1 )
assert '*' not in path , "The '*' wildcard character is only supported after the last '/'"
wildcard_parts = wildcard_obj . split ( '*' )
assert len ( wildcard_parts ) == 2 , "Only one '*' wildcard is supported"
for it in self . listdir ( path ) :
if it . star... |
def dfs_do_func_on_graph ( node , func , * args , ** kwargs ) :
'''invoke func on each node of the dr graph''' | for _node in node . tree_iterator ( ) :
func ( _node , * args , ** kwargs ) |
def removeReader ( self , selectable ) :
"""Remove a FileDescriptor for notification of data available to read .""" | try :
if selectable . disconnected :
self . _reads [ selectable ] . kill ( block = False )
del self . _reads [ selectable ]
else :
self . _reads [ selectable ] . pause ( )
except KeyError :
pass |
def from_dict ( cls , data : Dict [ str , Union [ str , int ] ] ) :
"""Generate an ` ExpGene ` object from a dictionary .
Parameters
data : dict
A dictionary with keys corresponding to attribute names .
Attributes with missing keys will be assigned ` None ` .
Returns
` ExpGene `
The gene .""" | assert isinstance ( data , dict )
if 'ensembl_id' not in data :
raise ValueError ( 'An "ensembl_id" key is missing!' )
# make a copy
data = dict ( data )
for attr in [ 'name' , 'chromosome' , 'position' , 'length' , 'type' , 'source' ] :
if attr in data and data [ attr ] == '' :
data [ attr ] = None
dat... |
def update_model ( self , updates = None ) :
"""Get or set , whether automatic updates are performed . When updates are
off , the model might be in a non - working state . To make the model work
turn updates on again .
: param bool | None updates :
bool : whether to do updates
None : get the current updat... | if updates is None :
return self . _update_on
assert isinstance ( updates , bool ) , "updates are either on (True) or off (False)"
p = getattr ( self , '_highest_parent_' , None )
def turn_updates ( s ) :
s . _update_on = updates
p . traverse ( turn_updates )
self . trigger_update ( ) |
def signature_string_parts ( posargs , optargs , mod = '!r' ) :
"""Return stringified arguments as tuples .
Parameters
posargs : sequence
Positional argument values , always included in the returned string
tuple .
optargs : sequence of 3 - tuples
Optional arguments with names and defaults , given in the... | # Convert modifiers to 2 - sequence of sequence of strings
if is_string ( mod ) or callable ( mod ) :
pos_mod = opt_mod = mod
else :
pos_mod , opt_mod = mod
mods = [ ]
for m , args in zip ( ( pos_mod , opt_mod ) , ( posargs , optargs ) ) :
if is_string ( m ) or callable ( m ) :
mods . append ( [ m ]... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'text' ) and self . text is not None :
_dict [ 'text' ] = self . text
if hasattr ( self , 'entities' ) and self . entities is not None :
_dict [ 'entities' ] = [ x . _to_dict ( ) for x in self . entities ]
if hasattr ( self , 'keywords' ) and self . keywords is not None :
_di... |
def update ( self , item_id , attributes , silent = False , hook = True ) :
"""Updates the item using the supplied attributes . If ' silent ' is true , Podio will send
no notifications to subscribed users and not post updates to the stream .
Important : webhooks will still be called .""" | if not isinstance ( attributes , dict ) :
raise TypeError ( 'Must be of type dict' )
attributes = json . dumps ( attributes )
return self . transport . PUT ( body = attributes , type = 'application/json' , url = '/item/%d%s' % ( item_id , self . get_options ( silent = silent , hook = hook ) ) ) |
def connect_head_namespaced_pod_proxy_with_path ( self , name , namespace , path , ** kwargs ) : # noqa : E501
"""connect _ head _ namespaced _ pod _ proxy _ with _ path # noqa : E501
connect HEAD requests to proxy of Pod # noqa : E501
This method makes a synchronous HTTP request by default . To make an
async... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . connect_head_namespaced_pod_proxy_with_path_with_http_info ( name , namespace , path , ** kwargs )
# noqa : E501
else :
( data ) = self . connect_head_namespaced_pod_proxy_with_path_with_http_info ( name , namespace ,... |
def get_fee ( speed = FEE_SPEED_MEDIUM ) :
"""Gets the recommended satoshi per byte fee .
: param speed : One of : ' fast ' , ' medium ' , ' slow ' .
: type speed : ` ` string ` `
: rtype : ` ` int ` `""" | if speed == FEE_SPEED_FAST :
return DEFAULT_FEE_FAST
elif speed == FEE_SPEED_MEDIUM :
return DEFAULT_FEE_MEDIUM
elif speed == FEE_SPEED_SLOW :
return DEFAULT_FEE_SLOW
else :
raise ValueError ( 'Invalid speed argument.' ) |
def from_dict ( config_cls , dictionary , validate = False ) :
"""Loads an instance of ` ` config _ cls ` ` from a dictionary .
: param type config _ cls : The class to build an instance of
: param dict dictionary : The dictionary to load from
: param bool validate : Preforms validation before building ` ` co... | return _build ( config_cls , dictionary , validate = validate ) |
def process_form ( request , form_class , form_dict = None , save_kwargs = None , * a , ** kw ) :
'''Optional :
You can pass kwargs to the form save function in a ' save _ kwargs ' dict .
Example Usage :
success , form = process _ form ( request , DiscussionForm , initial = {
' category ' : Category . objec... | form = form_class ( form_dict or request . POST or None , * a , ** kw )
if request . method == 'POST' :
if form . is_valid ( ) :
if not save_kwargs :
save_kwargs = { }
results = form . save ( request = request , ** save_kwargs )
return ( True , results )
return ( False , form ) |
def ensure_future ( fut , * , loop = None ) :
"""Wraps asyncio . async ( ) / asyncio . ensure _ future ( ) depending on the python version
: param fut : The awaitable , future , or coroutine to wrap
: param loop : The loop to run in
: return : The wrapped future""" | if sys . version_info < ( 3 , 4 , 4 ) : # This is to avoid a SyntaxError on 3.7.0a2 +
func = getattr ( asyncio , "async" )
else :
func = asyncio . ensure_future
return func ( fut , loop = loop ) |
def _send_scp ( self , cabinet , frame , board , * args , ** kwargs ) :
"""Determine the best connection to use to send an SCP packet and use
it to transmit .
See the arguments for
: py : meth : ` ~ rig . machine _ control . scp _ connection . SCPConnection ` for
details .""" | # Find the connection which best matches the specified coordinates ,
# preferring direct connections to a board when available .
connection = self . connections . get ( ( cabinet , frame , board ) , None )
if connection is None :
connection = self . connections . get ( ( cabinet , frame ) , None )
assert connection... |
def control_valve_noise_l_2015 ( m , P1 , P2 , Psat , rho , c , Kv , d , Di , FL , Fd , t_pipe , rho_pipe = 7800.0 , c_pipe = 5000.0 , rho_air = 1.2 , c_air = 343.0 , xFz = None , An = - 4.6 ) :
r'''Calculates the sound made by a liquid flowing through a control valve
according to the standard IEC 60534-8-4 ( 201... | # Convert Kv to Cv as C
N34 = 1.17
# for Cv - conversion constant but not to many decimals
N14 = 0.0046
C = Kv_to_Cv ( Kv )
xF = ( P1 - P2 ) / ( P1 - Psat )
dPc = min ( P1 - P2 , FL * FL * ( P1 - Psat ) )
if xFz is None :
xFz = 0.9 * ( 1.0 + 3.0 * Fd * ( C / ( N34 * FL ) ) ** 0.5 ) ** - 0.5
xFzp1 = xFz * ( 6E5 / P1... |
def nth ( iterable , n , default = None ) :
"""Returns the nth item or a default value .
Example : :
> > > nth ( [ 0 , 1 , 2 ] , 1)
> > > nth ( [ 0 , 1 , 2 ] , 100)
None
* * 中文文档 * *
取出一个可循环对象中的第n个元素 。 等效于list ( iterable ) [ n ] , 但占用极小的内存 。
因为list ( iterable ) 要将所有元素放在内存中并生成一个新列表 。 该方法常用语对于
那些取inde... | return next ( itertools . islice ( iterable , n , None ) , default ) |
async def _stream_helper ( self , response , decode = False ) :
"""Generator for data coming from a chunked - encoded HTTP response .""" | if decode :
async for chunk in json_stream ( self . _stream_helper ( response , False ) ) :
yield chunk
else :
async with response . context as res :
reader = res . content
while True : # this read call will block until we get a chunk
data = await reader . read ( 1 )
... |
def _canonical_type ( name ) : # pylint : disable = too - many - return - statements
"""Replace aliases to the corresponding type to compute the ids .""" | if name == 'int' :
return 'int256'
if name == 'uint' :
return 'uint256'
if name == 'fixed' :
return 'fixed128x128'
if name == 'ufixed' :
return 'ufixed128x128'
if name . startswith ( 'int[' ) :
return 'int256' + name [ 3 : ]
if name . startswith ( 'uint[' ) :
return 'uint256' + name [ 4 : ]
if n... |
def autocomplete ( self , line ) :
"""Given a line , return a list of suggestions .""" | current_length = len ( line )
self . _current_line = line
if current_length == 1 and self . _last_position > 1 : # Reset state . This is likely from a user completing
# a previous command .
self . reset ( )
elif current_length < self . _last_position : # The user has hit backspace . We ' ll need to check
# the curr... |
def Read ( self , timeout = None ) :
'''Reads the context menu
: param timeout : Optional . Any value other than None indicates a non - blocking read
: return :''' | # if not self . Shown :
# self . Shown = True
# self . TrayIcon . show ( )
timeout1 = timeout
# if timeout1 = = 0:
# timeout1 = 1
# if wx . GetApp ( ) :
# wx . GetApp ( ) . ProcessPendingEvents ( )
# self . App . ProcessPendingEvents ( )
# self . App . ProcessIdle ( )
# return self . MenuItemChosen
if timeout1 is not N... |
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 .""" | return '\n\n' . join ( codeobj . pretty_str ( indent = indent ) for codeobj in self . children ) |
def run_once ( name , cmd , env , shutdown , loop = None , utc = False ) :
"""Starts a child process and waits for its completion .
. . note : : This function is a coroutine .
Standard output and error streams are captured and forwarded to the parent
process ' standard output . Each line is prefixed with the ... | # Get the default event loop if necessary .
loop = loop or asyncio . get_event_loop ( )
# Launch the command into a child process .
if isinstance ( cmd , str ) :
cmd = shlex . split ( cmd )
process = yield from asyncio . create_subprocess_exec ( * cmd , env = env , stdin = asyncio . subprocess . PIPE , stdout = asy... |
def absent ( name , exports = '/etc/exports' ) :
'''Ensure that the named path is not exported
name
The export path to remove''' | path = name
ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' }
old = __salt__ [ 'nfs3.list_exports' ] ( exports )
if path in old :
if __opts__ [ 'test' ] :
ret [ 'comment' ] = 'Export {0} would be removed' . format ( path )
ret [ 'changes' ] [ path ] = old [ path ]
... |
def run_itx_resistance_assessment ( job , rsem_files , univ_options , reports_options ) :
"""A wrapper for assess _ itx _ resistance .
: param dict rsem _ files : Results from running rsem
: param dict univ _ options : Dict of universal options used by almost all tools
: param dict reports _ options : Options... | return job . addChildJobFn ( assess_itx_resistance , rsem_files [ 'rsem.genes.results' ] , univ_options , reports_options ) . rv ( ) |
def create_payload ( self ) :
"""Wrap submitted data within an extra dict .
For more information , see ` Bugzilla # 1151220
< https : / / bugzilla . redhat . com / show _ bug . cgi ? id = 1151220 > ` _ .
In addition , rename the ` ` search _ ` ` field to ` ` search ` ` .""" | payload = super ( DiscoveryRule , self ) . create_payload ( )
if 'search_' in payload :
payload [ 'search' ] = payload . pop ( 'search_' )
return { u'discovery_rule' : payload } |
def root_mean_squared_error ( pred : Tensor , targ : Tensor ) -> Rank0Tensor :
"Root mean squared error between ` pred ` and ` targ ` ." | pred , targ = flatten_check ( pred , targ )
return torch . sqrt ( F . mse_loss ( pred , targ ) ) |
def is_yaml_file ( filename , show_warnings = False ) :
"""Check configuration file type is yaml
Return a boolean indicating wheather the file is yaml format or not""" | if is_json_file ( filename ) :
return ( False )
try :
config_dict = load_config ( filename , file_type = "yaml" )
if ( type ( config_dict ) == str ) :
is_yaml = False
else :
is_yaml = True
except :
is_yaml = False
return ( is_yaml ) |
def patch_namespaced_daemon_set_status ( self , name , namespace , body , ** kwargs ) : # noqa : E501
"""patch _ namespaced _ daemon _ set _ status # noqa : E501
partially update status of the specified DaemonSet # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous H... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . patch_namespaced_daemon_set_status_with_http_info ( name , namespace , body , ** kwargs )
# noqa : E501
else :
( data ) = self . patch_namespaced_daemon_set_status_with_http_info ( name , namespace , body , ** kwargs ... |
def ifi_type ( self , value ) :
"""Type setter .""" | self . bytearray [ self . _get_slicers ( 2 ) ] = bytearray ( c_ushort ( value or 0 ) ) |
def rpc_call ( self , request , method = None , ** payload ) :
"""Call REST API with RPC force .
return object : a result""" | if not method or self . separator not in method :
raise AssertionError ( "Wrong method name: {0}" . format ( method ) )
resource_name , method = method . split ( self . separator , 1 )
if resource_name not in self . api . resources :
raise AssertionError ( "Unknown method " + method )
data = QueryDict ( '' , mu... |
def load_jinja_template ( file_name ) :
"""Loads the jinja2 HTML template from the given file .
Assumes that the file is in the same directory as the script .""" | original_script_path = sys . argv [ 0 ]
# script _ path = os . path . dirname ( os . path . realpath ( _ _ file _ _ ) )
script_dir = os . path . dirname ( original_script_path )
# file _ path = os . path . join ( script _ path , file _ name )
# with open ( file _ path , ' r ' ) as template _ file :
# return template _ ... |
def _process_state_in_progress ( self , job_record ) :
"""method that takes care of processing job records in STATE _ IN _ PROGRESS state""" | def _process_state ( target_state , uow ) :
if uow . is_active : # Large Job processing takes more than 1 tick of the Scheduler
# Let the Job processing complete - do no updates to Scheduler records
pass
elif uow . is_finished : # create new UOW to cover new inserts
new_uow , is_duplicate = ... |
def _bin_zfill ( num , width = None ) :
"""Convert a base - 10 number to a binary string .
Parameters
num : int
width : int , optional
Zero - extend the string to this width .
Examples
> > > _ bin _ zfill ( 42)
'101010'
> > > _ bin _ zfill ( 42 , 8)
'00101010'""" | s = bin ( num ) [ 2 : ]
return s if width is None else s . zfill ( width ) |
def split_core ( self , minw ) :
"""Split clauses in the core whenever necessary .
Given a list of soft clauses in an unsatisfiable core , the method
is used for splitting clauses whose weights are greater than the
minimum weight of the core , i . e . the ` ` minw ` ` value computed in
: func : ` treat _ co... | for clid in self . core :
sel = self . sels [ clid ]
if self . wght [ clid ] > minw :
self . topv += 1
cl_new = [ ]
for l in self . soft [ clid ] :
if l != - sel :
cl_new . append ( l )
else :
cl_new . append ( - self . topv )
... |
def get_families_by_ids ( self , * args , ** kwargs ) :
"""Pass through to provider FamilyLookupSession . get _ families _ by _ ids""" | # Implemented from kitosid template for -
# osid . resource . BinLookupSession . get _ bins _ by _ ids
catalogs = self . _get_provider_session ( 'family_lookup_session' ) . get_families_by_ids ( * args , ** kwargs )
cat_list = [ ]
for cat in catalogs :
cat_list . append ( Family ( self . _provider_manager , cat , s... |
def memoized_method ( func = None , key_factory = per_instance , ** kwargs ) :
"""A convenience wrapper for memoizing instance methods .
Typically you ' d expect a memoized instance method to hold a cached value per class instance ;
however , for classes that implement a custom ` _ _ hash _ _ ` / ` _ _ eq _ _ `... | return memoized ( func = func , key_factory = key_factory , ** kwargs ) |
def trace ( self , s , active = None , verbose = False ) :
"""Rewrite string * s * like ` apply ( ) ` , but yield each rewrite step .
Args :
s ( str ) : the input string to process
active ( optional ) : a collection of external module names
that may be applied if called
verbose ( bool , optional ) : if ` ... | if active is None :
active = self . active
return self . group . trace ( s , active = active , verbose = verbose ) |
def delete_old_tickets ( ** kwargs ) :
"""Delete tickets if they are over 2 days old
kwargs = [ ' raw ' , ' signal ' , ' instance ' , ' sender ' , ' created ' ]""" | sender = kwargs . get ( 'sender' , None )
now = datetime . now ( )
expire = datetime ( now . year , now . month , now . day - 2 )
sender . objects . filter ( created__lt = expire ) . delete ( ) |
def get_member_info ( self , page_size = 500 ) :
"""Retrieves member information from the AD group object .
: param page _ size ( optional ) : Many servers have a limit on the number of results that can be returned .
Paged searches circumvent that limit . Adjust the page _ size to be below the
server ' s size... | member_info = [ ]
for member in self . _get_group_members ( page_size ) :
info_dict = { }
for attribute_name in member [ "attributes" ] :
raw_attribute = member [ "attributes" ] [ attribute_name ]
# Pop one - item lists
if len ( raw_attribute ) == 1 :
raw_attribute = raw_attr... |
def _build_request ( self , verb , verb_arguments ) :
"""Builds HttpRequest object .
Args :
verb ( str ) : Request verb ( ex . insert , update , delete ) .
verb _ arguments ( dict ) : Arguments to be passed with the request .
Returns :
httplib2 . HttpRequest : HttpRequest to be sent to the API .""" | method = getattr ( self . _component , verb )
# Python insists that keys in * * kwargs be strings ( not variables ) .
# Since we initially build our kwargs as a dictionary where one of the
# keys is a variable ( target ) , we need to convert keys to strings ,
# even though the variable in question is of type str .
meth... |
def set_attachments_order ( self , order ) :
"""Remember the attachments order""" | # append single uids to the order
if isinstance ( order , basestring ) :
new_order = self . storage . get ( "order" , [ ] )
new_order . append ( order )
order = new_order
self . storage . update ( { "order" : order } ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.