signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def post ( self , request , bot_id , id , format = None ) :
"""Add a new header parameter to a handler
serializer : AbsParamSerializer
responseMessages :
- code : 401
message : Not authenticated
- code : 400
message : Not valid request""" | return super ( HeaderParameterList , self ) . post ( request , bot_id , id , format ) |
def fn_mean ( self , a , axis = None ) :
"""Compute the arithmetic mean of an array , ignoring NaNs .
: param a : The array .
: return : The arithmetic mean of the array .""" | return numpy . nanmean ( self . _to_ndarray ( a ) , axis = axis ) |
def load ( cls , filename , project = None , delim = ' | ' ) :
r"""Read in pore and throat data from a saved VTK file .
Parameters
filename : string ( optional )
The name of the file containing the data to import . The formatting
of this file is outlined below .
project : OpenPNM Project object
A Generi... | net = { }
filename = cls . _parse_filename ( filename , ext = 'vtp' )
tree = ET . parse ( filename )
piece_node = tree . find ( 'PolyData' ) . find ( 'Piece' )
# Extract connectivity
conn_element = piece_node . find ( 'Lines' ) . find ( 'DataArray' )
conns = VTK . _element_to_array ( conn_element , 2 )
# Extract coordi... |
def get_balance ( self , acc_id , site = 'Pro' ) :
"""获取当前账户资产
: return :""" | assert site in [ 'Pro' , 'HADAX' ]
path = f'/v1{"/" if site == "Pro" else "/hadax/"}account/accounts/{acc_id}/balance'
# params = { ' account - id ' : self . acct _ id }
params = { }
def _wrapper ( _func ) :
@ wraps ( _func )
def handle ( ) :
_func ( api_key_get ( params , path ) )
return handle
ret... |
def patch_connection ( filename = ':memory:' ) :
"""` ` filename ` ` : rlite filename to store db in , or memory
Patch the redis - py Connection and the
static from _ url ( ) of Redis and StrictRedis to use RliteConnection""" | if no_redis :
raise Exception ( "redis package not found, please install redis-py via 'pip install redis'" )
RliteConnection . set_file ( filename )
global orig_classes
# already patched
if orig_classes :
return
orig_classes = ( redis . connection . Connection , redis . connection . ConnectionPool )
_set_classe... |
def add_single_feature_methods ( cls ) :
"""Custom decorator intended for : class : ` ~ vision . helpers . VisionHelpers ` .
This metaclass adds a ` { feature } ` method for every feature
defined on the Feature enum .""" | # Sanity check : This only makes sense if we are building the GAPIC
# subclass and have enums already attached .
if not hasattr ( cls , "enums" ) :
return cls
# Add each single - feature method to the class .
for feature in cls . enums . Feature . Type : # Sanity check : Do not make a method for the falsy feature .... |
def check_required_params ( self ) :
"""Check if all required parameters are set""" | for param in self . REQUIRED_FIELDS :
if param not in self . params :
raise ValidationError ( "Missing parameter: {}" . format ( param ) ) |
def _set_lsp_auto_bandwidth ( self , v , load = False ) :
"""Setter method for lsp _ auto _ bandwidth , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / lsp / lsp _ auto _ bandwidth ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = lsp_auto_bandwidth . lsp_auto_bandwidth , is_container = 'container' , presence = True , yang_name = "lsp-auto-bandwidth" , rest_name = "autobw" , parent = self , path_helper = self . _path_helper , extmethods = self . _extme... |
def endian_swap_words ( source ) :
"""Endian - swap each word in ' source ' bitstring""" | assert len ( source ) % 4 == 0
words = "I" * ( len ( source ) // 4 )
return struct . pack ( "<" + words , * struct . unpack ( ">" + words , source ) ) |
def createFromFileName ( cls , fileName ) :
"""Creates a BaseRti ( or descendant ) , given a file name .""" | # See https : / / julien . danjou . info / blog / 2013 / guide - python - static - class - abstract - methods
# logger . debug ( " Trying to create object of class : { ! r } " . format ( cls ) )
basename = os . path . basename ( os . path . realpath ( fileName ) )
# strips trailing slashes
return cls ( nodeName = basen... |
def hotplugRegisterCallback ( self , callback , # pylint : disable = undefined - variable
events = HOTPLUG_EVENT_DEVICE_ARRIVED | HOTPLUG_EVENT_DEVICE_LEFT , flags = HOTPLUG_ENUMERATE , vendor_id = HOTPLUG_MATCH_ANY , product_id = HOTPLUG_MATCH_ANY , dev_class = HOTPLUG_MATCH_ANY , # pylint : enable = undefined - varia... | def wrapped_callback ( context_p , device_p , event , _ ) :
assert addressof ( context_p . contents ) == addressof ( self . __context_p . contents ) , ( context_p , self . __context_p )
device = USBDevice ( self , device_p , # pylint : disable = undefined - variable
event != HOTPLUG_EVENT_DEVICE_LEFT , # py... |
def delete_vector ( self , hash_name , bucket_keys , data ) :
"""Deletes vector and JSON - serializable data in buckets with specified keys .""" | lsh_keys = [ self . _format_mongo_key ( hash_name , key ) for key in bucket_keys ]
self . mongo_object . remove ( { 'lsh' : { '$in' : lsh_keys } , 'data' : data } ) |
def get_leaves ( self ) :
"Return a sorted leaves : only nodes with fixed file size ." | leaves = self . _get_leaves ( )
leaves . sort ( key = ( lambda x : x . _path ) )
# FF sorts " mixed " last
return leaves |
def open ( cls , grammar_filename , rel_to = None , ** options ) :
"""Create an instance of Lark with the grammar given by its filename
If rel _ to is provided , the function will find the grammar filename in relation to it .
Example :
> > > Lark . open ( " grammar _ file . lark " , rel _ to = _ _ file _ _ , ... | if rel_to :
basepath = os . path . dirname ( rel_to )
grammar_filename = os . path . join ( basepath , grammar_filename )
with open ( grammar_filename , encoding = 'utf8' ) as f :
return cls ( f , ** options ) |
def get_page_break_positions ( docbody ) :
"""Locate page breaks in the list of document lines and create a list
positions in the document body list .
@ param docbody : ( list ) of strings - each string is a line in the
document .
@ return : ( list ) of integer positions , whereby each integer represents th... | page_break_posns = [ ]
p_break = re . compile ( ur'^\s*\f\s*$' , re . UNICODE )
num_document_lines = len ( docbody )
for i in xrange ( num_document_lines ) :
if p_break . match ( docbody [ i ] ) is not None :
page_break_posns . append ( i )
return page_break_posns |
def arch ( ) :
"""returns the current cpu archictecture""" | with settings ( hide ( 'warnings' , 'running' , 'stdout' , 'stderr' ) , warn_only = True , capture = True ) :
result = sudo ( 'rpm -E %dist' ) . strip ( )
return result |
def deserialize_email_messages ( messages : List [ str ] ) :
"""Deserialize EmailMessages passed as task argument .""" | return [ pickle . loads ( zlib . decompress ( base64 . b64decode ( m ) ) ) for m in messages ] |
def align_unaligned_seqs ( seqs , moltype = DNA , params = None ) :
"""Returns an Alignment object from seqs .
seqs : SequenceCollection object , or data that can be used to build one .
moltype : a MolType object . DNA , RNA , or PROTEIN .
params : dict of parameters to pass in to the Muscle app controller . ... | if not params :
params = { }
# create SequenceCollection object from seqs
seq_collection = SequenceCollection ( seqs , MolType = moltype )
# Create mapping between abbreviated IDs and full IDs
int_map , int_keys = seq_collection . getIntMap ( )
# Create SequenceCollection from int _ map .
int_map = SequenceCollecti... |
def SetField ( cls , default = NOTHING , required = True , repr = False , key = None ) :
"""Create new set field on a model .
: param cls : class ( or name ) of the model to be related in Set .
: param default : any TypedSet or set
: param bool required : whether or not the object is invalid if not provided .... | default = _init_fields . init_default ( required , default , set ( ) )
converter = converters . to_set_field ( cls )
validator = _init_fields . init_validator ( required , types . TypedSet )
return attrib ( default = default , converter = converter , validator = validator , repr = repr , metadata = dict ( key = key ) ) |
def sleep_walk ( secs ) :
'''Pass the time by adding numbers until the specified number of seconds has
elapsed . Intended as a replacement for ` ` time . sleep ` ` that doesn ' t leave the
CPU idle ( which will make the job seem like it ' s stalled ) .''' | start_time = datetime . now ( )
num = 0
while ( datetime . now ( ) - start_time ) . seconds < secs :
num = num + 1 |
def property ( self , property_name , default = Ellipsis ) :
"""Returns a property value
: param : default will return that value if the property is not found ,
else , will raise a KeyError .""" | try :
return self . _a_tags [ property_name ]
except KeyError :
if default != Ellipsis :
return default
else :
raise |
def redirectURL ( self , realm , return_to = None , immediate = False ) :
"""Returns a URL with an encoded OpenID request .
The resulting URL is the OpenID provider ' s endpoint URL with
parameters appended as query arguments . You should redirect
the user agent to this URL .
OpenID 2.0 endpoints also accep... | message = self . getMessage ( realm , return_to , immediate )
return message . toURL ( self . endpoint . server_url ) |
def _parse_heading ( self ) :
"""Parse a section heading at the head of the wikicode string .""" | self . _global |= contexts . GL_HEADING
reset = self . _head
self . _head += 1
best = 1
while self . _read ( ) == "=" :
best += 1
self . _head += 1
context = contexts . HEADING_LEVEL_1 << min ( best - 1 , 5 )
try :
title , level = self . _parse ( context )
except BadRoute :
self . _head = reset + best -... |
def parse_toplevel_config ( self , config ) :
"""Parse @ config to setup @ self state .""" | if not Formatter . initialized :
html_theme = config . get ( 'html_theme' , 'default' )
if html_theme != 'default' :
uri = urllib . parse . urlparse ( html_theme )
if not uri . scheme :
html_theme = config . get_path ( 'html_theme' )
debug ( "Using theme located at %s" % ... |
def start_review ( self ) :
"""Mark our review as started .""" | if self . set_status :
self . github_repo . create_status ( state = "pending" , description = "Static analysis in progress." , context = "inline-plz" , sha = self . last_sha , ) |
def start ( self , blocking = True ) :
"""Start the producer . This will eventually fire the ` ` server _ start ` `
and ` ` running ` ` events in sequence , which signify that the incoming
TCP request socket is running and the workers have been forked ,
respectively . If ` ` blocking ` ` is False , control ."... | self . setup_zmq ( )
if blocking :
self . serve ( )
else :
eventlet . spawn ( self . serve )
# ensure that self . serve runs now as calling code will
# expect start ( ) to have started the server even non - blk
eventlet . sleep ( 0 ) |
def _parse_value ( cls , stream_rdr , offset , value_count , value_offset ) :
"""Return the long int value contained in the * value _ offset * field of
this entry . Only supports single values at present .""" | if value_count == 1 :
return stream_rdr . read_long ( offset , 8 )
else : # pragma : no cover
return 'Multi-value long integer NOT IMPLEMENTED' |
def wrap_in_ndarray ( value ) :
"""Wraps the argument in a numpy . ndarray .
If value is a scalar , it is converted in a list first .
If value is array - like , the shape is conserved .""" | if hasattr ( value , "__len__" ) :
return np . array ( value )
else :
return np . array ( [ value ] ) |
def set_author ( voevent , title = None , shortName = None , logoURL = None , contactName = None , contactEmail = None , contactPhone = None , contributor = None ) :
"""For setting fields in the detailed author description .
This can optionally be neglected if a well defined AuthorIVORN is supplied .
. . note :... | # We inspect all local variables except the voevent packet ,
# Cycling through and assigning them on the Who . Author element .
AuthChildren = locals ( )
AuthChildren . pop ( 'voevent' )
if not voevent . xpath ( 'Who/Author' ) :
etree . SubElement ( voevent . Who , 'Author' )
for k , v in AuthChildren . items ( ) :... |
def RefreshResumableUploadState ( self ) :
"""Talk to the server and refresh the state of this resumable upload .
Returns :
Response if the upload is complete .""" | if self . strategy != RESUMABLE_UPLOAD :
return
self . EnsureInitialized ( )
refresh_request = http_wrapper . Request ( url = self . url , http_method = 'PUT' , headers = { 'Content-Range' : 'bytes */*' } )
refresh_response = http_wrapper . MakeRequest ( self . http , refresh_request , redirections = 0 , retries = ... |
def overview ( ) :
'''Show status of the DRBD devices , support two nodes only .
drbd - overview is removed since drbd - utils - 9.6.0,
use status instead .
CLI Example :
. . code - block : : bash
salt ' * ' drbd . overview''' | cmd = 'drbd-overview'
for line in __salt__ [ 'cmd.run' ] ( cmd ) . splitlines ( ) :
ret = { }
fields = line . strip ( ) . split ( )
minnum = fields [ 0 ] . split ( ':' ) [ 0 ]
device = fields [ 0 ] . split ( ':' ) [ 1 ]
connstate , _ = _analyse_overview_field ( fields [ 1 ] )
localrole , partner... |
def triangle_coordinates ( i , j , k ) :
"""Computes coordinates of the constituent triangles of a triangulation for the
simplex . These triangules are parallel to the lower axis on the lower side .
Parameters
i , j , k : enumeration of the desired triangle
Returns
A numpy array of coordinates of the hexa... | return [ ( i , j , k ) , ( i + 1 , j , k - 1 ) , ( i , j + 1 , k - 1 ) ] |
def hasAspect ( obj1 , obj2 , aspList ) :
"""Returns if there is an aspect between objects
considering a list of possible aspect types .""" | aspType = aspectType ( obj1 , obj2 , aspList )
return aspType != const . NO_ASPECT |
def _reconnect ( self ) :
"""Schedule the next connection attempt if the class is not currently
closing .""" | if self . idle or self . closed :
LOGGER . debug ( 'Attempting RabbitMQ reconnect in %s seconds' , self . reconnect_delay )
self . io_loop . call_later ( self . reconnect_delay , self . connect )
return
LOGGER . warning ( 'Reconnect called while %s' , self . state_description ) |
async def seek ( self , pos , whence = sync_io . SEEK_SET ) :
"""Move to new file position .
Argument offset is a byte count . Optional argument whence defaults to
SEEK _ SET or 0 ( offset from start of file , offset should be > = 0 ) ; other
values are SEEK _ CUR or 1 ( move relative to current position , po... | return self . _stream . seek ( pos , whence ) |
def refresh_oauth_token ( self , keychain ) :
"""Use sfdx force : org : describe to refresh token instead of built in OAuth handling""" | if hasattr ( self , "_scratch_info" ) : # Cache the scratch _ info for 1 hour to avoid unnecessary calls out
# to sfdx CLI
delta = datetime . datetime . utcnow ( ) - self . _scratch_info_date
if delta . total_seconds ( ) > 3600 :
del self . _scratch_info
# Force a token refresh
self . fo... |
def get ( self , keys , default = None ) :
r"""This subclassed method can be used to obtain a dictionary containing
subset of data on the object
Parameters
keys : string or list of strings
The item or items to retrieve .
default : any object
The value to return in the event that the requested key ( s ) ... | # If a list of several keys is passed , then create a subdict
if isinstance ( keys , list ) :
ret = { }
for k in keys :
ret [ k ] = super ( ) . get ( k , default )
else : # Otherwise return numpy array
ret = super ( ) . get ( keys , default )
return ret |
def top_level_doc ( self ) :
"""The top - level documentation string for the program .""" | return self . _doc_template . format ( available_commands = '\n ' . join ( sorted ( self . _commands ) ) , program = self . program ) |
def get_opener ( self , protocol ) : # type : ( Text ) - > Opener
"""Get the opener class associated to a given protocol .
Arguments :
protocol ( str ) : A filesystem protocol .
Returns :
Opener : an opener instance .
Raises :
~ fs . opener . errors . UnsupportedProtocol : If no opener
could be found ... | protocol = protocol or self . default_opener
if self . load_extern :
entry_point = next ( pkg_resources . iter_entry_points ( "fs.opener" , protocol ) , None )
else :
entry_point = None
# If not entry point was loaded from the extensions , try looking
# into the registered protocols
if entry_point is None :
... |
def to_dict ( self , serial = False ) :
'''A dictionary representing the the data of the class is returned .
Native Python objects will still exist in this dictionary ( for example ,
a ` ` datetime ` ` object will be returned rather than a string )
unless ` ` serial ` ` is set to True .''' | if serial :
return dict ( ( key , self . _fields [ key ] . to_serial ( getattr ( self , key ) ) ) for key in list ( self . _fields . keys ( ) ) if hasattr ( self , key ) )
else :
return dict ( ( key , getattr ( self , key ) ) for key in list ( self . _fields . keys ( ) ) if hasattr ( self , key ) ) |
def create_table_sql ( cls , db ) :
'''Returns the SQL command for creating a table for this model .''' | parts = [ 'CREATE TABLE IF NOT EXISTS `%s`.`%s` (' % ( db . db_name , cls . table_name ( ) ) ]
cols = [ ]
for name , field in iteritems ( cls . fields ( ) ) :
cols . append ( ' %s %s' % ( name , field . get_sql ( ) ) )
parts . append ( ',\n' . join ( cols ) )
parts . append ( ')' )
parts . append ( 'ENGINE = ' +... |
def total_build_duration_for_chain ( self , build_chain_id ) :
"""Returns the total duration for one specific build chain run""" | return sum ( [ int ( self . __build_duration_for_id ( id ) ) for id in self . __build_ids_of_chain ( build_chain_id ) ] ) |
def Remind ( self , minutes , command , use_reminders = False ) :
"""Check for events between now and now + minutes .
If use _ reminders then only remind if now > = event [ ' start ' ] - reminder""" | # perform a date query for now + minutes + slip
start = self . now
end = ( start + timedelta ( minutes = ( minutes + 5 ) ) )
event_list = self . _search_for_events ( start , end , None )
message = ''
for event in event_list : # skip this event if it already started
# XXX maybe add a 2 + minute grace period here . . .
... |
def forecast ( stl , fc_func , steps = 10 , seasonal = False , ** fc_func_kwargs ) :
"""Forecast the given decomposition ` ` stl ` ` forward by ` ` steps ` ` steps using the forecasting
function ` ` fc _ func ` ` , optionally including the calculated seasonality .
This is an additive model , Y [ t ] = T [ t ] +... | # container for forecast values
forecast_array = np . array ( [ ] )
# forecast trend
# unpack precalculated trend array stl frame
trend_array = stl . trend
# iteratively forecast trend ( " seasonally adjusted " ) component
# note : this loop can be slow
for step in range ( steps ) : # make this prediction on all availa... |
def tableinfo ( tableid , lang = DEFAULT_LANGUAGE ) :
"""Fetch metadata for statbank table
Metadata includes information about variables ,
which can be used when extracting data .""" | request = Request ( 'tableinfo' , tableid , lang = lang )
return Tableinfo ( request . json , lang = lang ) |
def fill_from_simbad ( self , ident , debug = False ) :
"""Fill in astrometric information using the Simbad web service .
This uses the CDS Simbad web service to look up astrometric
information for the source name * ident * and fills in attributes
appropriately . Values from Simbad are not always reliable .
... | info = get_simbad_astrometry_info ( ident , debug = debug )
posref = 'unknown'
for k , v in six . iteritems ( info ) :
if '~' in v :
continue
# no info
if k == 'COO(d;A)' :
self . ra = float ( v ) * D2R
elif k == 'COO(d;D)' :
self . dec = float ( v ) * D2R
elif k == 'COO(E)' ... |
def find_spectrum_match ( spec , spec_lib , method = 'euclidian' ) :
"""Find spectrum in spec _ lib most similar to spec .""" | # filter out any points with abundance below 1 %
# spec [ spec / np . sum ( spec ) < 0.01 ] = 0
# normalize everything to sum to 1
spec = spec / np . max ( spec )
if method == 'dot' :
d1 = ( spec_lib * lil_matrix ( spec ) . T ) . sum ( axis = 1 ) . A ** 2
d2 = np . sum ( spec ** 2 ) * spec_lib . multiply ( spec... |
def tuple_to_qfont ( tup ) :
"""Create a QFont from tuple :
( family [ string ] , size [ int ] , italic [ bool ] , bold [ bool ] )""" | if not isinstance ( tup , tuple ) or len ( tup ) != 4 or not is_text_string ( tup [ 0 ] ) or not isinstance ( tup [ 1 ] , int ) or not isinstance ( tup [ 2 ] , bool ) or not isinstance ( tup [ 3 ] , bool ) :
return None
font = QFont ( )
family , size , italic , bold = tup
font . setFamily ( family )
font . setPoint... |
def get_longest_line_length ( text ) :
"""Get the length longest line in a paragraph""" | lines = text . split ( "\n" )
length = 0
for i in range ( len ( lines ) ) :
if len ( lines [ i ] ) > length :
length = len ( lines [ i ] )
return length |
def get_metrics ( metrics_description ) :
"""Get metrics from a list of dictionaries .""" | return utils . get_objectlist ( metrics_description , config_key = 'data_analyzation_plugins' , module = sys . modules [ __name__ ] ) |
def set_data ( self , pos = None , symbol = 'o' , size = 10. , edge_width = 1. , edge_width_rel = None , edge_color = 'black' , face_color = 'white' , scaling = False ) :
"""Set the data used to display this visual .
Parameters
pos : array
The array of locations to display each symbol .
symbol : str
The s... | assert ( isinstance ( pos , np . ndarray ) and pos . ndim == 2 and pos . shape [ 1 ] in ( 2 , 3 ) )
if ( edge_width is not None ) + ( edge_width_rel is not None ) != 1 :
raise ValueError ( 'exactly one of edge_width and edge_width_rel ' 'must be non-None' )
if edge_width is not None :
if edge_width < 0 :
... |
def from_config ( cls , config , name , section_key = "scoring_contexts" ) :
"""Expects :
scoring _ contexts :
enwiki :
scorer _ models :
damaging : enwiki _ damaging _ 2014
good - faith : enwiki _ good - faith _ 2014
extractor : enwiki
ptwiki :
scorer _ models :
damaging : ptwiki _ damaging _ 201... | logger . info ( "Loading {0} '{1}' from config." . format ( cls . __name__ , name ) )
section = config [ section_key ] [ name ]
model_map = { }
for model_name , key in section [ 'scorer_models' ] . items ( ) :
scorer_model = Model . from_config ( config , key )
model_map [ model_name ] = scorer_model
extractor ... |
def prj_view_atype ( self , * args , ** kwargs ) :
"""View the , in the atype table view selected , assettype .
: returns : None
: rtype : None
: raises : None""" | if not self . cur_prj :
return
i = self . prj_atype_tablev . currentIndex ( )
item = i . internalPointer ( )
if item :
atype = item . internal_data ( )
self . view_atype ( atype ) |
def with_callback ( self , subprocess , callback , * matchers , intercept_callback = None ) :
"""Monitoring event matchers while executing a subprocess . ` callback ( event , matcher ) ` is called each time
an event is matched by any event matchers . If the callback raises an exception , the subprocess is termina... | it_ = _await ( subprocess )
if not matchers and not intercept_callback :
return ( yield from it_ )
try :
try :
m = next ( it_ )
except StopIteration as e :
return e . value
while True :
if m is None :
try :
yield
except GeneratorExit_ :
... |
def _from_dict ( cls , _dict ) :
"""Initialize a RuntimeEntity object from a json dictionary .""" | args = { }
xtra = _dict . copy ( )
if 'entity' in _dict :
args [ 'entity' ] = _dict . get ( 'entity' )
del xtra [ 'entity' ]
else :
raise ValueError ( 'Required property \'entity\' not present in RuntimeEntity JSON' )
if 'location' in _dict :
args [ 'location' ] = _dict . get ( 'location' )
del xtra... |
def set_offset ( self , offset ) :
"""Set the current read offset ( in bytes ) for the instance .""" | assert offset in range ( len ( self . buffer ) )
self . pos = offset
self . _fill_buffer ( ) |
def get_variable_values ( schema : GraphQLSchema , var_def_nodes : List [ VariableDefinitionNode ] , inputs : Dict [ str , Any ] , ) -> CoercedVariableValues :
"""Get coerced variable values based on provided definitions .
Prepares a dict of variable values of the correct type based on the provided
variable def... | errors : List [ GraphQLError ] = [ ]
coerced_values : Dict [ str , Any ] = { }
for var_def_node in var_def_nodes :
var_name = var_def_node . variable . name . value
var_type = type_from_ast ( schema , var_def_node . type )
if not is_input_type ( var_type ) : # Must use input types for variables . This shoul... |
def group_distance ( values , distance ) :
"""Find groups of points which have neighbours closer than radius ,
where no two points in a group are farther than distance apart .
Parameters
points : ( n , d ) float
Points of dimension d
distance : float
Max distance between points in a cluster
Returns
... | values = np . asanyarray ( values , dtype = np . float64 )
consumed = np . zeros ( len ( values ) , dtype = np . bool )
tree = cKDTree ( values )
# ( n , d ) set of values that are unique
unique = [ ]
# ( n ) sequence of indices in values
groups = [ ]
for index , value in enumerate ( values ) :
if consumed [ index ... |
def apex_location_info ( glats , glons , alts , dates ) :
"""Determine apex location for the field line passing through input point .
Employs a two stage method . A broad step ( 100 km ) field line trace spanning
Northern / Southern footpoints is used to find the location with the largest
geodetic ( WGS84 ) h... | # use input location and convert to ECEF
ecef_xs , ecef_ys , ecef_zs = geodetic_to_ecef ( glats , glons , alts )
# prepare parameters for field line trace
step_size = 100.
max_steps = 1000
steps = np . arange ( max_steps )
# high resolution trace parameters
fine_step_size = .01
fine_max_steps = int ( step_size / fine_s... |
def isin ( self , values ) :
"""Check whether ` values ` are contained in Series .
Return a boolean Series showing whether each element in the Series
matches an element in the passed sequence of ` values ` exactly .
Parameters
values : set or list - like
The sequence of values to test . Passing in a singl... | result = algorithms . isin ( self , values )
return self . _constructor ( result , index = self . index ) . __finalize__ ( self ) |
def discrete_approx_mvn ( X , means , covars , match_variances = True ) :
"""Find a discrete approximation to a multivariate normal distribution .
The method employs find the discrete distribution with support only at the
supplied points X with minimal K - L divergence to a target multivariate
normal distribu... | X = ensure_type ( np . asarray ( X ) , dtype = np . float32 , ndim = 2 , name = 'X' , warn_on_cast = False )
means = ensure_type ( np . asarray ( means ) , np . float64 , ndim = 1 , name = 'means' , warn_on_cast = False )
covars = np . asarray ( covars )
# Get the un - normalized probability of each point X _ i in the ... |
def print_omega_channel ( channel , file = sys . stdout ) :
"""Print a ` Channel ` in Omega - pipeline scan format""" | print ( '{' , file = file )
try :
params = channel . params . copy ( )
except AttributeError :
params = OrderedDict ( )
params . setdefault ( 'channelName' , str ( channel ) )
params . setdefault ( 'alwaysPlotFlag' , int ( params . pop ( 'important' , False ) ) )
if channel . frametype :
params . setdefault... |
def estimate_row_means ( self , X , observed , column_means , column_scales ) :
"""row _ center [ i ] =
sum { j in observed [ i , : ] } {
(1 / column _ scale [ j ] ) * ( X [ i , j ] - column _ center [ j ] )
sum { j in observed [ i , : ] } { 1 / column _ scale [ j ] }""" | n_rows , n_cols = X . shape
column_means = np . asarray ( column_means )
if len ( column_means ) != n_cols :
raise ValueError ( "Expected length %d but got shape %s" % ( n_cols , column_means . shape ) )
X = X - column_means . reshape ( ( 1 , n_cols ) )
column_weights = 1.0 / column_scales
X *= column_weights . res... |
def get_tickers_from_file ( self , filename ) :
"""Load ticker list from txt file""" | if not os . path . exists ( filename ) :
log . error ( "Ticker List file does not exist: %s" , filename )
tickers = [ ]
with io . open ( filename , 'r' ) as fd :
for ticker in fd :
tickers . append ( ticker . rstrip ( ) )
return tickers |
def validate ( args ) :
"""% prog validate agpfile componentfasta targetfasta
validate consistency between agpfile and targetfasta""" | p = OptionParser ( validate . __doc__ )
opts , args = p . parse_args ( args )
try :
agpfile , componentfasta , targetfasta = args
except Exception as e :
sys . exit ( p . print_help ( ) )
agp = AGP ( agpfile )
build = Fasta ( targetfasta )
bacs = Fasta ( componentfasta , index = False )
# go through this line b... |
def follow ( self ) :
"""Follow a user . " """ | data = json . dumps ( { "action" : "follow" } )
r = requests . post ( "https://kippt.com/api/users/%s/relationship" % ( self . id ) , headers = self . kippt . header , data = data )
return ( r . json ( ) ) |
def add ( self , idx ) :
"""Add an index to the tree ( recursive ) .""" | if self . leafnode and self . children >= self . max_points_per_region and self . max_depth > 0 :
self . split ( )
self . idxs . append ( idx )
if self . leafnode :
leaf_add = self
else :
if self . get_data_x ( ) [ idx , self . split_dim ] >= self . split_value :
leaf_add = self . greater . add ( id... |
def update_text ( self , token , match ) :
"""Update text from results of regex match""" | if isinstance ( self . text , MatchGroup ) :
self . text = self . text . get_group_value ( token , match ) |
def _get_prefetched_translations ( self , meta = None ) :
"""Return the queryset with prefetch results .""" | if meta is None :
meta = self . _parler_meta . root
related_name = meta . rel_name
try : # Read the list directly , avoid QuerySet construction .
# Accessing self . _ get _ translated _ queryset ( parler _ meta ) . _ prefetch _ done is more expensive .
return self . _prefetched_objects_cache [ related_name ]
ex... |
def update_memo_key ( self , key , account = None , ** kwargs ) :
"""Update an account ' s memo public key
This method does * * not * * add any private keys to your
wallet but merely changes the memo public key .
: param str key : New memo public key
: param str account : ( optional ) the account to allow a... | if not account :
if "default_account" in self . config :
account = self . config [ "default_account" ]
if not account :
raise ValueError ( "You need to provide an account" )
PublicKey ( key , prefix = self . prefix )
account = Account ( account , blockchain_instance = self )
account [ "options" ] [ "mem... |
def build_specfiles ( source , target , env ) :
"""Filter the targets for the needed files and use the variables in env
to create the specfile .""" | # At first we care for the CONTROL / control file , which is the main file for ipk .
# For this we need to open multiple files in random order , so we store into
# a dict so they can be easily accessed .
opened_files = { }
def open_file ( needle , haystack ) :
try :
return opened_files [ needle ]
except... |
def parse_response ( cls , response_string ) :
"""JSONRPC allows for * * batch * * responses to be communicated
as arrays of dicts . This method parses out each individual
element in the batch and returns a list of tuples , each
tuple a result of parsing of each item in the batch .
: Returns : | tuple of ( ... | try :
batch = cls . json_loads ( response_string )
except ValueError as err :
raise errors . RPCParseError ( "No valid JSON. (%s)" % str ( err ) )
if isinstance ( batch , ( list , tuple ) ) and batch : # batch is true batch .
# list of parsed request objects , is _ batch _ mode _ flag
return [ cls . _parse_... |
def set_data_rate ( self , datarate ) :
"""Set the radio datarate to be used""" | if datarate != self . current_datarate :
_send_vendor_setup ( self . handle , SET_DATA_RATE , datarate , 0 , ( ) )
self . current_datarate = datarate |
def execute ( self , i , o ) :
"""Executes the command .
: type i : cleo . inputs . input . Input
: type o : cleo . outputs . output . Output""" | super ( InstallCommand , self ) . execute ( i , o )
database = i . get_option ( 'database' )
repository = DatabaseMigrationRepository ( self . _resolver , 'migrations' )
repository . set_source ( database )
repository . create_repository ( )
o . writeln ( '<info>Migration table created successfully</info>' ) |
def best_buy_1 ( self ) :
"""量大收紅
: rtype : bool""" | result = self . data . value [ - 1 ] > self . data . value [ - 2 ] and self . data . price [ - 1 ] > self . data . openprice [ - 1 ]
return result |
def has_data_for_dates ( series_or_df , first_date , last_date ) :
"""Does ` series _ or _ df ` have data on or before first _ date and on or after
last _ date ?""" | dts = series_or_df . index
if not isinstance ( dts , pd . DatetimeIndex ) :
raise TypeError ( "Expected a DatetimeIndex, but got %s." % type ( dts ) )
first , last = dts [ [ 0 , - 1 ] ]
return ( first <= first_date ) and ( last >= last_date ) |
def adopt_saved_state ( self , saved_state_file ) :
"""Associates the given saved state file to the virtual machine .
On success , the machine will go to the Saved state . Next time it is
powered up , it will be restored from the adopted saved state and
continue execution from the place where the saved state ... | if not isinstance ( saved_state_file , basestring ) :
raise TypeError ( "saved_state_file can only be an instance of type basestring" )
self . _call ( "adoptSavedState" , in_p = [ saved_state_file ] ) |
def setKey ( self , key , value ) :
"""Sets the value for the specified dictionary key""" | data = self . getDictionary ( )
data [ key ] = value
self . setDictionary ( data ) |
def aStockQoutation ( self , code ) :
'''订阅一只股票的实时行情数据 , 接收推送
: param code : 股票代码
: return :''' | # 设置监听 - - > 订阅 - - > 调用接口
# 分时
self . quote_ctx . set_handler ( RTDataTest ( ) )
self . quote_ctx . subscribe ( code , SubType . RT_DATA )
ret_code_rt_data , ret_data_rt_data = self . quote_ctx . get_rt_data ( code )
# 逐笔
self . quote_ctx . set_handler ( TickerTest ( ) )
self . quote_ctx . subscribe ( code , SubType .... |
def is_website_affected ( self , website ) :
"""Tell if the website is affected by the domain change""" | if self . domain is None :
return True
if not self . include_subdomains :
return self . domain in website [ 'subdomains' ]
else :
dotted_domain = "." + self . domain
for subdomain in website [ 'subdomains' ] :
if subdomain == self . domain or subdomain . endswith ( dotted_domain ) :
... |
def fallback ( func ) :
"""Decorator function for functions that handle spark context .
If a function changes sc we might lose it if an error occurs in the function .
In the event of an error this decorator will log the error but return sc .
: param func : function to decorate
: return : decorated function"... | @ wraps ( func )
def dec ( * args , ** kwargs ) :
try :
return func ( * args , ** kwargs )
except Exception as e :
logging . getLogger ( 'pySparkUtils' ) . error ( 'Decorator handled exception %s' % e , exc_info = True )
_ , _ , tb = sys . exc_info ( )
while tb . tb_next :
... |
def _subtask_error ( self , idx , error ) :
"""Receive an error from a single subtask .""" | self . set_exception ( error )
self . errbacks . clear ( ) |
def canonical_url ( configs , vip_setting = 'vip' ) :
'''Returns the correct HTTP URL to this host given the state of HTTPS
configuration and hacluster .
: configs : OSTemplateRenderer : A config tempating object to inspect for
a complete https context .
: vip _ setting : str : Setting in charm config that ... | scheme = 'http'
if 'https' in configs . complete_contexts ( ) :
scheme = 'https'
if is_clustered ( ) :
addr = config_get ( vip_setting )
else :
addr = unit_get ( 'private-address' )
return '%s://%s' % ( scheme , addr ) |
def set_int ( bytearray_ , byte_index , _int ) :
"""Set value in bytearray to int""" | # make sure were dealing with an int
_int = int ( _int )
_bytes = struct . unpack ( '2B' , struct . pack ( '>h' , _int ) )
bytearray_ [ byte_index : byte_index + 2 ] = _bytes
return bytearray_ |
def _make_stream_transport ( self ) :
"""Create an AdbStreamTransport with a newly allocated local _ id .""" | msg_queue = queue . Queue ( )
with self . _stream_transport_map_lock : # Start one past the last id we used , and grab the first available one .
# This mimics the ADB behavior of ' increment an unsigned and let it
# overflow ' , but with a check to ensure we don ' t reuse an id in use ,
# even though that ' s unlikely ... |
def ver ( self , value ) :
"""The ver property .
Args :
value ( int ) . the property value .""" | if value == self . _defaults [ 'ver' ] and 'ver' in self . _values :
del self . _values [ 'ver' ]
else :
self . _values [ 'ver' ] = value |
def drop ( self , table_names ) :
'''Drops the provided table ( s ) from this database .
Parameters
table _ names : list of str , str or None
Table ( s ) to be dropped''' | table_names = self . _check_table_names ( table_names )
for tname in table_names :
tname = self . _check_tname ( tname , noload = True )
# Warning : if auto _ load is on the next insert will re - create the table
with self . _lock :
del self . _db [ tname ]
filepath = os . path . join ( self... |
def rotation_at_time ( t , timestamps , rotation_sequence ) :
"""Get the gyro rotation at time t using SLERP .
Parameters
t : float
The query timestamp .
timestamps : array _ like float
List of all timestamps
rotation _ sequence : ( 4 , N ) ndarray
Rotation sequence as unit quaternions with scalar par... | idx = np . flatnonzero ( timestamps >= ( t - 0.0001 ) ) [ 0 ]
t0 = timestamps [ idx - 1 ]
t1 = timestamps [ idx ]
tau = ( t - t0 ) / ( t1 - t0 )
q1 = rotation_sequence [ : , idx - 1 ]
q2 = rotation_sequence [ : , idx ]
q = rotations . slerp ( q1 , q2 , tau )
return q |
def to_displacements ( self ) :
"""Converts position coordinates of trajectory into displacements between consecutive frames""" | if not self . coords_are_displacement :
displacements = np . subtract ( self . frac_coords , np . roll ( self . frac_coords , 1 , axis = 0 ) )
displacements [ 0 ] = np . zeros ( np . shape ( self . frac_coords [ 0 ] ) )
# Deal with PBC
displacements = [ np . subtract ( item , np . round ( item ) ) for i... |
def _name_available ( self , obj , name , shaders ) :
"""Return True if * name * is available for * obj * in * shaders * .""" | if name in self . _global_ns :
return False
shaders = self . shaders if self . _is_global ( obj ) else shaders
for shader in shaders :
if name in self . _shader_ns [ shader ] :
return False
return True |
def _op_msg_uncompressed ( flags , command , identifier , docs , check_keys , opts ) :
"""Internal compressed OP _ MSG message helper .""" | data , total_size , max_bson_size = _op_msg_no_header ( flags , command , identifier , docs , check_keys , opts )
request_id , op_message = __pack_message ( 2013 , data )
return request_id , op_message , total_size , max_bson_size |
def ensure ( self , status , cost ) :
"""ensure link properties correspond to the specified ones
perform save operation only if necessary""" | changed = False
status_id = LINK_STATUS [ status ]
if self . status != status_id :
self . status = status_id
changed = True
if self . metric_value != cost :
self . metric_value = cost
changed = True
if changed :
self . save ( ) |
def scan_cgroups ( subsys_name , filters = list ( ) ) :
"""It returns a control group hierarchy which belong to the subsys _ name .
When collecting cgroups , filters are applied to the cgroups . See pydoc
of apply _ filters method of CGroup for more information about the filters .""" | status = SubsystemStatus ( )
if subsys_name not in status . get_all ( ) :
raise NoSuchSubsystemError ( "No such subsystem found: " + subsys_name )
if subsys_name not in status . get_available ( ) :
raise EnvironmentError ( "Disabled in the kernel: " + subsys_name )
if subsys_name not in status . get_enabled ( )... |
def home ( self ) :
"""Set cursor to initial position and reset any shifting .""" | self . command ( c . LCD_RETURNHOME )
self . _cursor_pos = ( 0 , 0 )
c . msleep ( 2 ) |
def set_elements_tail ( parent_to_parse , element_path = None , tail_values = None ) :
"""Assigns an array of tail values to each of the elements parsed from the parent . The
tail values are assigned in the same order they are provided .
If there are less values then elements , the remaining elements are skippe... | if tail_values is None :
tail_values = [ ]
return _set_elements_property ( parent_to_parse , element_path , _ELEM_TAIL , tail_values ) |
def move ( src_parent , src_idx , dest_parent , dest_idx ) :
"""Move an item .""" | copy ( src_parent , src_idx , dest_parent , dest_idx )
remove ( src_parent , src_idx ) |
def pksign ( self , conn ) :
"""Sign a message digest using a private EC key .""" | log . debug ( 'signing %r digest (algo #%s)' , self . digest , self . algo )
identity = self . get_identity ( keygrip = self . keygrip )
r , s = self . client . sign ( identity = identity , digest = binascii . unhexlify ( self . digest ) )
result = sig_encode ( r , s )
log . debug ( 'result: %r' , result )
keyring . se... |
def draw_mini_map ( self , surf ) :
"""Draw the minimap .""" | if ( self . _render_rgb and self . _obs . observation . HasField ( "render_data" ) and self . _obs . observation . render_data . HasField ( "minimap" ) ) : # Draw the rendered version .
surf . blit_np_array ( features . Feature . unpack_rgb_image ( self . _obs . observation . render_data . minimap ) )
else : # Rend... |
def get_files_by_path ( self , path , tree = TreeType . SOURCE_ROOT ) :
"""Gets the files under the given tree type that match the given path .
: param path : Path to the file relative to the tree root
: param tree : Tree type to look for the path . By default the SOURCE _ ROOT
: return : List of all PBXFileR... | files = [ ]
for file_ref in self . objects . get_objects_in_section ( u'PBXFileReference' ) :
if file_ref . path == path and file_ref . sourceTree == tree :
files . append ( file_ref )
return files |
def _read_temp ( data ) :
'''Return what would be written to disk''' | tout = StringIO ( )
tout . write ( data )
tout . seek ( 0 )
output = tout . readlines ( )
tout . close ( )
return output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.