signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def zadd ( self , key , score , member , * pairs , exist = None ) :
"""Add one or more members to a sorted set or update its score .
: raises TypeError : score not int or float
: raises TypeError : length of pairs is not even number""" | if not isinstance ( score , ( int , float ) ) :
raise TypeError ( "score argument must be int or float" )
if len ( pairs ) % 2 != 0 :
raise TypeError ( "length of pairs must be even number" )
scores = ( item for i , item in enumerate ( pairs ) if i % 2 == 0 )
if any ( not isinstance ( s , ( int , float ) ) for ... |
def persist_checksum ( self , requirement , cache_file ) :
"""Persist the checksum of the input used to generate a binary distribution .
: param requirement : A : class : ` . Requirement ` object .
: param cache _ file : The pathname of a cached binary distribution ( a string ) .
. . note : : The checksum is ... | if not self . config . trust_mod_times :
checksum_file = '%s.txt' % cache_file
with AtomicReplace ( checksum_file ) as temporary_file :
with open ( temporary_file , 'w' ) as handle :
handle . write ( '%s\n' % requirement . checksum ) |
def where ( self , key , operator , value ) :
"""Make where clause
: @ param key
: @ param operator
: @ param value
: @ type key , operator , value : string
: @ return self""" | self . __store_query ( { "key" : key , "operator" : operator , "value" : value } )
return self |
def ColumnTypeParser ( description ) :
"""Parses a single column description . Internal helper method .
Args :
description : a column description in the possible formats :
' id '
( ' id ' , )
( ' id ' , ' type ' )
( ' id ' , ' type ' , ' label ' )
( ' id ' , ' type ' , ' label ' , { ' custom _ prop1 '... | if not description :
raise DataTableException ( "Description error: empty description given" )
if not isinstance ( description , ( six . string_types , tuple ) ) :
raise DataTableException ( "Description error: expected either string or " "tuple, got %s." % type ( description ) )
if isinstance ( description , s... |
def fetch_tuples ( self , max_tuples = 20 , timeout = None ) :
"""Fetch a number of tuples from this view .
Fetching of data must have been started with
: py : meth : ` start _ data _ fetch ` before calling this method .
If ` ` timeout ` ` is ` ` None ` ` then the returned list will
contain ` ` max _ tuples... | tuples = list ( )
if timeout is None :
while len ( tuples ) < max_tuples :
fetcher = self . _data_fetcher
if not fetcher :
break
tuples . append ( fetcher . items . get ( ) )
return tuples
timeout = float ( timeout )
end = time . time ( ) + timeout
while len ( tuples ) < max_... |
def _add_attribute_values ( self , value , att_mappings , indices ) :
"""Add an attribute value to the given vertices .
: param int value : Attribute value .
: param dict att _ mappings : Dictionary of mappings between vertices and enumerated attributes .
: param list indices : Indices of the vertices .""" | for i in indices :
att_mappings [ i ] . append ( value ) |
def to_representation ( self , failure_line ) :
"""Manually add matches our wrapper of the TLEMetadata - > TLE relation .
I could not work out how to do this multiple relation jump with DRF ( or
even if it was possible ) so using this manual method instead .""" | try :
matches = failure_line . error . matches . all ( )
except AttributeError : # failure _ line . error can return None
matches = [ ]
tle_serializer = TextLogErrorMatchSerializer ( matches , many = True )
classified_failures = models . ClassifiedFailure . objects . filter ( error_matches__in = matches )
cf_se... |
def _pipdeptree ( python_bin , package_name : str = None , warn : bool = False ) -> typing . Optional [ dict ] :
"""Get pip dependency tree by executing pipdeptree tool .""" | cmd = "{} -m pipdeptree --json" . format ( python_bin )
_LOGGER . debug ( "Obtaining pip dependency tree using: %r" , cmd )
output = run_command ( cmd , is_json = True ) . stdout
if not package_name :
return output
for entry in output : # In some versions pipdeptree does not work with - - packages flag , do the log... |
def tplot_rename ( old_name , new_name ) :
"""This function will rename tplot variables that are already stored in memory .
Parameters :
old _ name : str
Old name of the Tplot Variable
new _ name : str
New name of the Tplot Variable
Returns :
None
Examples :
> > > # Rename Variable 1 to Variable 2... | # check if old name is in current dictionary
if old_name not in pytplot . data_quants . keys ( ) :
print ( "That name is currently not in pytplot" )
return
# if old name input is a number , convert to corresponding name
if isinstance ( old_name , int ) :
old_name = pytplot . data_quants [ old_name ] . name
... |
def _compute_term2 ( self , C , mag , r ) :
"""This computes the term f2 equation 8 Drouet & Cotton ( 2015)""" | return ( C [ 'c4' ] + C [ 'c5' ] * mag ) * np . log ( np . sqrt ( r ** 2 + C [ 'c6' ] ** 2 ) ) + C [ 'c7' ] * r |
def get ( self , sid ) :
"""Constructs a MessageContext
: param sid : The unique string that identifies the resource
: returns : twilio . rest . chat . v2 . service . channel . message . MessageContext
: rtype : twilio . rest . chat . v2 . service . channel . message . MessageContext""" | return MessageContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , channel_sid = self . _solution [ 'channel_sid' ] , sid = sid , ) |
def train ( net , train_data , test_data ) :
"""Train textCNN model for sentiment analysis .""" | start_pipeline_time = time . time ( )
net , trainer = text_cnn . init ( net , vocab , args . model_mode , context , args . lr )
random . shuffle ( train_data )
sp = int ( len ( train_data ) * 0.9 )
train_dataloader = DataLoader ( dataset = train_data [ : sp ] , batch_size = args . batch_size , shuffle = True )
val_data... |
def read_data ( self , sheet , begin = None ) :
"""用于简单模板匹配 , 只处理一行的模板 , begin为None时自动从for行开始
: param sheet : 应该使用read _ only模式打开
: param begin :
: return :""" | line = self . begin
rows = sheet . rows
for i in range ( line - 1 ) :
rows . next ( )
template_line = self . template [ self . begin - 1 ]
if not template_line [ 'subs' ] :
raise ValueError ( "Template definition is not right" )
for row in rows :
d = { }
for c in template_line [ 'subs' ] [ 0 ] [ 'cols' ... |
def ipv4_range_to_list ( start_packed , end_packed ) :
"""Return a list of IPv4 entries from start _ packed to end _ packed .""" | new_list = list ( )
start = struct . unpack ( '!L' , start_packed ) [ 0 ]
end = struct . unpack ( '!L' , end_packed ) [ 0 ]
for value in range ( start , end + 1 ) :
new_ip = socket . inet_ntoa ( struct . pack ( '!L' , value ) )
new_list . append ( new_ip )
return new_list |
def GET_AUTH ( self , courseid ) : # pylint : disable = arguments - differ
"""GET request""" | course , __ = self . get_course_and_check_rights ( courseid )
return self . page ( course ) |
def _skip_whitespace ( self ) :
"""Increment over whitespace , counting characters .""" | i = 0
while self . _cur_token [ 'type' ] is TT . ws and not self . _finished :
self . _increment ( )
i += 1
return i |
def setDocument ( self , filename , empty = "" ) :
"""Sets the HTML text to be displayed .""" | self . _source = QUrl . fromLocalFile ( filename )
if os . path . exists ( filename ) :
self . viewer . setSource ( self . _source )
else :
self . viewer . setText ( empty ) |
def create_snapshot_chart ( self , filename = '' ) :
"""Create chart that depicts the memory allocation over time apportioned to
the tracked classes .""" | try :
from pylab import figure , title , xlabel , ylabel , plot , fill , legend , savefig
import matplotlib . mlab as mlab
except ImportError :
return self . nopylab_msg % ( "memory allocation" )
classlist = self . tracked_classes
times = [ snapshot . timestamp for snapshot in self . snapshots ]
base = [ 0 ... |
def reset ( self ) :
"""Reset Union Pooler , clear active cell history""" | self . _unionSDR = numpy . zeros ( shape = ( self . _numInputs , ) )
self . _activeCellsHistory = [ ] |
def stream ( ** kwargs ) :
"""Provides an : py : func : ` open ` - like interface to the streaming encryptor / decryptor classes .
. . warning : :
Take care when decrypting framed messages with large frame length and large non - framed
messages . In order to protect the authenticity of the encrypted data , no... | mode = kwargs . pop ( "mode" )
_stream_map = { "e" : StreamEncryptor , "encrypt" : StreamEncryptor , "d" : StreamDecryptor , "decrypt" : StreamDecryptor }
try :
return _stream_map [ mode . lower ( ) ] ( ** kwargs )
except KeyError :
raise ValueError ( "Unsupported mode: {}" . format ( mode ) ) |
def add_oauth_header ( self ) :
"""Validate token and add the proper header for further requests .
: return : ( None )""" | # abort if no token
oauth_token = self . _get_token ( )
if not oauth_token :
return
# add oauth header & reach the api
self . headers [ "Authorization" ] = "token " + oauth_token
url = self . _api_url ( "user" )
raw_resp = self . requests . get ( url )
resp = raw_resp . json ( )
# abort & remove header if token is ... |
def formatPoint ( point , affine ) :
"""Retrieves a string representation of @ point""" | # Affine coordinates : ( x , y )
if affine :
fmt = "\tx:{}\n\ty:{}"
coords = [ point . x , point . y ]
# Projected coordinates : ( x , y , z )
else :
fmt = "\tx:{}\n\ty:{}\n\tz:{}"
coords = [ point . x , point . y , point . z ]
coordText = map ( hexString , coords )
return fmt . format ( * coordText ) |
def _set_mac_move_limit ( self , v , load = False ) :
"""Setter method for mac _ move _ limit , mapped from YANG variable / mac _ address _ table / mac _ move / mac _ move _ limit ( uint32)
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ mac _ move _ limit is considered... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = RestrictedClassType ( base_type = long , restriction_dict = { 'range' : [ '0..4294967295' ] } , int_size = 32 ) , restriction_dict = { 'range' : [ u'5..500' ] } ) , default = RestrictedClassT... |
def get_col_rgba ( color , transparency = None , opacity = None ) :
"""This class converts a Gdk . Color into its r , g , b parts and adds an alpha according to needs
If both transparency and opacity is None , alpha is set to 1 = > opaque
: param Gdk . Color color : Color to extract r , g and b from
: param f... | r , g , b = color . red , color . green , color . blue
# Convert from 0-6535 to 0-1
r /= 65535.
g /= 65535.
b /= 65535.
if transparency is not None or opacity is None :
transparency = 0 if transparency is None else transparency
# default value
if transparency < 0 or transparency > 1 :
raise ValueErr... |
def start ( self ) -> None :
"""Create the remote Spark session and wait for it to be ready .""" | session = self . client . create_session ( self . kind , self . proxy_user , self . jars , self . py_files , self . files , self . driver_memory , self . driver_cores , self . executor_memory , self . executor_cores , self . num_executors , self . archives , self . queue , self . name , self . spark_conf , )
self . ses... |
def collect ( self ) :
"""Collect metrics from all registered metric sets
: return :""" | logger . debug ( "Collecting metrics" )
for name , metricset in compat . iteritems ( self . _metricsets ) :
data = metricset . collect ( )
if data :
self . _queue_func ( constants . METRICSET , data ) |
def _set_load_interval ( self , v , load = False ) :
"""Setter method for load _ interval , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / policy / load _ interval ( uint32)
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ load _ inter... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = RestrictedClassType ( base_type = long , restriction_dict = { 'range' : [ '0..4294967295' ] } , int_size = 32 ) , restriction_dict = { 'range' : [ u'30..300' ] } ) , default = RestrictedClass... |
def removeSubscriber ( self , email ) :
"""Remove a subscriber from this workitem
If the subscriber has not been added , no more actions will be
performed .
: param email : the subscriber ' s email""" | headers , raw_data = self . _perform_subscribe ( )
missing_flag , raw_data = self . _remove_subscriber ( email , raw_data )
if missing_flag :
return
self . _update_subscribe ( headers , raw_data )
self . log . info ( "Successfully remove a subscriber: %s for <Workitem %s>" , email , self ) |
def format_result ( input ) :
"""From : http : / / stackoverflow . com / questions / 13062300 / convert - a - dict - to - sorted - dict - in - python""" | items = list ( iteritems ( input ) )
return OrderedDict ( sorted ( items , key = lambda x : x [ 0 ] ) ) |
def rollback ( awsclient , function_name , alias_name = ALIAS_NAME , version = None ) :
"""Rollback a lambda function to a given version .
: param awsclient :
: param function _ name :
: param alias _ name :
: param version :
: return : exit _ code""" | if version :
log . info ( 'rolling back to version {}' . format ( version ) )
else :
log . info ( 'rolling back to previous version' )
version = _get_previous_version ( awsclient , function_name , alias_name )
if version == '0' :
log . error ( 'unable to find previous version of lambda function'... |
def set_db_row ( db , start , size , _bytearray ) :
"""Here we replace a piece of data in a db block with new data
Args :
db ( int ) : The db to use
start ( int ) : The start within the db
size ( int ) : The size of the data in bytes
_ butearray ( enumerable ) : The data to put in the db""" | client . db_write ( db , start , size , _bytearray ) |
def write_fasta ( path , sequences , names , mode = 'w' , width = 80 ) :
"""Write nucleotide sequences stored as numpy arrays to a FASTA file .
Parameters
path : string
File path .
sequences : sequence of arrays
One or more ndarrays of dtype ' S1 ' containing the sequences .
names : sequence of strings ... | # check inputs
if isinstance ( sequences , np . ndarray ) : # single sequence
sequences = [ sequences ]
names = [ names ]
if len ( sequences ) != len ( names ) :
raise ValueError ( 'must provide the same number of sequences and names' )
for sequence in sequences :
if sequence . dtype != np . dtype ( 'S1... |
def _netsh_file ( content ) :
'''helper function to get the results of ` ` netsh - f content . txt ` `
Running ` ` netsh ` ` will drop you into a ` ` netsh ` ` prompt where you can issue
` ` netsh ` ` commands . You can put a series of commands in an external file and
run them as if from a ` ` netsh ` ` promp... | with tempfile . NamedTemporaryFile ( mode = 'w' , prefix = 'salt-' , suffix = '.netsh' , delete = False ) as fp :
fp . write ( content )
try :
log . debug ( '%s:\n%s' , fp . name , content )
return salt . modules . cmdmod . run ( 'netsh -f {0}' . format ( fp . name ) , python_shell = True )
finally :
os... |
def query ( self , query , time_precision = 's' , chunked = False ) :
"""Query data from the influxdb v0.8 database .
: param time _ precision : [ Optional , default ' s ' ] Either ' s ' , ' m ' , ' ms '
or ' u ' .
: param chunked : [ Optional , default = False ] True if the data shall be
retrieved in chunk... | return self . _query ( query , time_precision = time_precision , chunked = chunked ) |
def long_poll_notifications ( self , ** kwargs ) : # noqa : E501
"""Get notifications using Long Poll # noqa : E501
In this case , notifications are delivered through HTTP long poll requests . The HTTP request is kept open until an event notification or a batch of event notifications are delivered to the client o... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . long_poll_notifications_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . long_poll_notifications_with_http_info ( ** kwargs )
# noqa : E501
return data |
def add_code_verifier ( request_args , service , ** kwargs ) :
"""PKCE RFC 7636 support
To be added as a post _ construct method to an
: py : class : ` oidcservice . oidc . service . AccessToken ` instance
: param service : The service that uses this function
: param request _ args : Set of request argument... | _item = service . get_item ( Message , 'pkce' , kwargs [ 'state' ] )
request_args . update ( { 'code_verifier' : _item [ 'code_verifier' ] } )
return request_args |
def _gcs_get_keys ( bucket , pattern ) :
"""Get names of all Google Cloud Storage keys in a specified bucket that match a pattern .""" | return [ obj for obj in list ( bucket . objects ( ) ) if fnmatch . fnmatch ( obj . metadata . name , pattern ) ] |
def _central_slopes_directions ( self , data , dX , dY ) :
"""Calculates magnitude / direction of slopes using central difference""" | shp = np . array ( data . shape ) - 1
direction = np . full ( data . shape , FLAT_ID_INT , 'float64' )
mag = np . full ( direction , FLAT_ID_INT , 'float64' )
ind = 0
d1 , d2 , theta = _get_d1_d2 ( dX , dY , ind , [ 0 , 1 ] , [ 1 , 1 ] , shp )
s2 = ( data [ 0 : - 2 , 1 : - 1 ] - data [ 2 : , 1 : - 1 ] ) / d2
s1 = - ( d... |
def get_run_configuration ( fname ) :
"""Return script * fname * run configuration""" | configurations = _get_run_configurations ( )
for filename , options in configurations :
if fname == filename :
runconf = RunConfiguration ( )
runconf . set ( options )
return runconf |
def _getNewXref ( self ) :
"""_ getNewXref ( self ) - > PyObject *""" | if self . isClosed or self . isEncrypted :
raise ValueError ( "operation illegal for closed / encrypted doc" )
return _fitz . Document__getNewXref ( self ) |
def add_listener ( self , callback , event_type = None ) :
"""Add a listener that will send a callback when the client recieves
an event .
Args :
callback ( func ( roomchunk ) ) : Callback called when an event arrives .
event _ type ( str ) : The event _ type to filter for .
Returns :
uuid . UUID : Uniq... | listener_uid = uuid4 ( )
# TODO : listeners should be stored in dict and accessed / deleted directly . Add
# convenience method such that MatrixClient . listeners . new ( Listener ( . . . ) ) performs
# MatrixClient . listeners [ uuid4 ( ) ] = Listener ( . . . )
self . listeners . append ( { 'uid' : listener_uid , 'cal... |
def censor ( self , input_text ) :
"""Returns input _ text with any profane words censored .""" | bad_words = self . get_profane_words ( )
res = input_text
for word in bad_words : # Apply word boundaries to the bad word
regex_string = r'{0}' if self . _no_word_boundaries else r'\b{0}\b'
regex_string = regex_string . format ( word )
regex = re . compile ( regex_string , re . IGNORECASE )
res = regex ... |
def _coarsen_reshape ( self , windows , boundary , side ) :
"""Construct a reshaped - array for corsen""" | if not utils . is_dict_like ( boundary ) :
boundary = { d : boundary for d in windows . keys ( ) }
if not utils . is_dict_like ( side ) :
side = { d : side for d in windows . keys ( ) }
# remove unrelated dimensions
boundary = { k : v for k , v in boundary . items ( ) if k in windows }
side = { k : v for k , v ... |
def connect ( self , maximize = True ) :
"""Set up the selenium driver and connect to the server
: param maximize : True if the driver should be maximized
: returns : selenium driver""" | if not self . config . get ( 'Driver' , 'type' ) or self . config . get ( 'Driver' , 'type' ) in [ 'api' , 'no_driver' ] :
return None
self . driver = ConfigDriver ( self . config , self . utils ) . create_driver ( )
# Save session id and remote node to download video after the test execution
self . session_id = se... |
def ts_merge ( series ) :
'''Merge timeseries into a new : class : ` ~ . TimeSeries ` instance .
: parameter series : an iterable over : class : ` ~ . TimeSeries ` .''' | series = iter ( series )
ts = next ( series )
return ts . merge ( series ) |
def partition ( f , xs ) :
"""Works similar to filter , except it returns a two - item tuple where the
first item is the sequence of items that passed the filter and the
second is a sequence of items that didn ' t pass the filter""" | t = type ( xs )
true = filter ( f , xs )
false = [ x for x in xs if x not in true ]
return t ( true ) , t ( false ) |
def add_function ( self , function ) :
"""Adds the function to the list of registered functions .""" | function = self . build_function ( function )
if function . name in self . functions :
raise FunctionAlreadyRegistered ( function . name )
self . functions [ function . name ] = function |
def convert2hdf5 ( platform_name ) :
"""Retrieve original RSR data and convert to internal hdf5 format""" | import h5py
ahi = AhiRSR ( platform_name )
filename = os . path . join ( ahi . output_dir , "rsr_ahi_{platform}.h5" . format ( platform = platform_name ) )
with h5py . File ( filename , "w" ) as h5f :
h5f . attrs [ 'description' ] = 'Relative Spectral Responses for AHI'
h5f . attrs [ 'platform_name' ] = platfor... |
def context_processor ( self , func ) :
"""Decorate a given function to use as a context processor .
@ app . ps . jinja2 . context _ processor
def my _ context ( ) :
return { . . . }""" | func = to_coroutine ( func )
self . providers . append ( func )
return func |
def do_create_subject ( self , subject_context ) :
"""By the time this method is invoked , all possible
` ` SubjectContext ` ` data ( session , identifiers , et . al . ) has been made
accessible using all known heuristics .
: returns : a Subject instance reflecting the data in the specified
SubjectContext d... | if not isinstance ( subject_context , web_subject_abcs . WebSubjectContext ) :
return super ( ) . do_create_subject ( subject_context = subject_context )
security_manager = subject_context . resolve_security_manager ( )
session = subject_context . resolve_session ( )
session_creation_enabled = subject_context . ses... |
def _stage ( self , accepted , count = 0 ) :
"""This is a repeated state in the state removal algorithm""" | new5 = self . _combine_rest_push ( )
new1 = self . _combine_push_pop ( )
new2 = self . _combine_push_rest ( )
new3 = self . _combine_pop_rest ( )
new4 = self . _combine_rest_rest ( )
new = new1 + new2 + new3 + new4 + new5
del new1
del new2
del new3
del new4
del new5
if len ( new ) == 0 : # self . printer ( )
# print ' ... |
def register_view ( self ) :
"""Display registration form and create new User .""" | safe_next_url = self . _get_safe_next_url ( 'next' , self . USER_AFTER_LOGIN_ENDPOINT )
safe_reg_next_url = self . _get_safe_next_url ( 'reg_next' , self . USER_AFTER_REGISTER_ENDPOINT )
# Initialize form
login_form = self . LoginFormClass ( )
# for login _ or _ register . html
register_form = self . RegisterFormClass ... |
def handle_request ( self , environ , start_response ) :
"""Handle an HTTP request from the client .
This is the entry point of the Engine . IO application , using the same
interface as a WSGI application . For the typical usage , this function
is invoked by the : class : ` Middleware ` instance , but it can ... | method = environ [ 'REQUEST_METHOD' ]
query = urllib . parse . parse_qs ( environ . get ( 'QUERY_STRING' , '' ) )
if 'j' in query :
self . logger . warning ( 'JSONP requests are not supported' )
r = self . _bad_request ( )
else :
sid = query [ 'sid' ] [ 0 ] if 'sid' in query else None
b64 = False
if... |
def name ( self ) :
"""Return the String assosciated with the tag name""" | if self . m_name == - 1 or ( self . m_event != START_TAG and self . m_event != END_TAG ) :
return ''
return self . sb [ self . m_name ] |
def pull_log ( self , project_name , logstore_name , shard_id , from_time , to_time , batch_size = None , compress = None ) :
"""batch pull log data from log service using time - range
Unsuccessful opertaion will cause an LogException . the time parameter means the time when server receives the logs
: type proj... | begin_cursor = self . get_cursor ( project_name , logstore_name , shard_id , from_time ) . get_cursor ( )
end_cursor = self . get_cursor ( project_name , logstore_name , shard_id , to_time ) . get_cursor ( )
while True :
res = self . pull_logs ( project_name , logstore_name , shard_id , begin_cursor , count = batch... |
def set_guest_access ( self , room_id , guest_access ) :
"""Set the guest access policy of the room .
Args :
room _ id ( str ) : The room to set the rules for .
guest _ access ( str ) : Wether guests can join . One of : [ " can _ join " ,
" forbidden " ]""" | content = { "guest_access" : guest_access }
return self . send_state_event ( room_id , "m.room.guest_access" , content ) |
def _build_arguments ( self ) :
"""build arguments for command .""" | self . _parser . add_argument ( '--clean' , type = bool , required = False , default = False , help = "clean up everything that was created by freight forwarder at the end." )
self . _parser . add_argument ( '--configs' , type = bool , required = False , default = False , help = "Would you like to inject configuration ... |
def _convert_epytext ( line ) :
"""> > > _ convert _ epytext ( " L { A } " )
: class : ` A `""" | line = line . replace ( '@' , ':' )
for p , sub in RULES :
line = re . sub ( p , sub , line )
return line |
def compound_object ( element_name , attrnames , warn = False ) :
"""return a class which delegates bracket access to an internal dict .
Missing attributes are delegated to the child dict for convenience .
@ note : Care must be taken when child nodes and attributes have the same names""" | class CompoundObject ( ) :
_original_fields = sorted ( attrnames )
_fields = [ _prefix_keyword ( a , warn ) for a in _original_fields ]
def __init__ ( self , values , child_dict ) :
for name , val in zip ( self . _fields , values ) :
self . __dict__ [ name ] = val
self . _child_d... |
def tzname ( self , dt ) :
"""http : / / docs . python . org / library / datetime . html # datetime . tzinfo . tzname""" | sign = '+'
if self . __offset < datetime . timedelta ( ) :
sign = '-'
# total _ seconds was introduced in Python 2.7
if hasattr ( self . __offset , 'total_seconds' ) :
total_seconds = self . __offset . total_seconds ( )
else :
total_seconds = ( self . __offset . days * 24 * 60 * 60 ) + ( self . __offset . s... |
def compamp_to_spectrogram ( compamp ) :
'''Returns spectrogram , with each row containing the measured power spectrum for a XX second time sample .
Using this function is shorthand for :
aca = ibmseti . compamp . Compamp ( raw _ data )
power = ibmseti . dsp . complex _ to _ power ( aca . complex _ data ( ) ,... | power = complex_to_power ( compamp . complex_data ( ) , compamp . header ( ) [ 'over_sampling' ] )
return reshape_to_2d ( power ) |
def GetSectionByIndex ( self , section_index ) :
"""Retrieves a specific section based on the index .
Args :
section _ index ( int ) : index of the section .
Returns :
VolumeExtent : a volume extent or None if not available .""" | if not self . _is_parsed :
self . _Parse ( )
self . _is_parsed = True
if section_index < 0 or section_index >= len ( self . _sections ) :
return None
return self . _sections [ section_index ] |
def _parse_interval ( self , tokens ) :
"""Parses a range
Range : : = < num > | < num > ( ' . . ' | ' ^ ' ) < num >""" | fr = int ( tokens . pop ( 0 ) ) - 1
if len ( tokens ) > 1 and tokens [ 0 ] in [ '..' , '^' ] :
tokens . pop ( 0 )
# Pop ' . . ' | ' ^ '
to = int ( tokens . pop ( 0 ) )
return GenomicInterval ( fr , to , chromosome = self . hdr [ 'ACCESSION' ] [ 'value' ] )
return GenomicInterval ( fr , fr + 1 , chromoso... |
def collect_metrics ( local_evaluator = None , remote_evaluators = [ ] , timeout_seconds = 180 ) :
"""Gathers episode metrics from PolicyEvaluator instances .""" | episodes , num_dropped = collect_episodes ( local_evaluator , remote_evaluators , timeout_seconds = timeout_seconds )
metrics = summarize_episodes ( episodes , episodes , num_dropped )
return metrics |
def visitAdditionOrSubtractionExpression ( self , ctx ) :
"""expression : expression ( PLUS | MINUS ) expression""" | is_add = ctx . PLUS ( ) is not None
arg1 = self . visit ( ctx . expression ( 0 ) )
arg2 = self . visit ( ctx . expression ( 1 ) )
# first try as decimals
try :
_arg1 = conversions . to_decimal ( arg1 , self . _eval_context )
_arg2 = conversions . to_decimal ( arg2 , self . _eval_context )
return _arg1 + _ar... |
def set_widgets ( self ) :
"""Set widgets on the Hazard Category tab .""" | self . clear_further_steps ( )
# Set widgets
self . lstHazardCategories . clear ( )
self . lblDescribeHazardCategory . setText ( '' )
self . lblSelectHazardCategory . setText ( hazard_category_question )
hazard_categories = self . hazard_categories_for_layer ( )
for hazard_category in hazard_categories :
if not isi... |
def memoize ( func ) :
"""Provides memoization for methods on a specific instance .
Results are cached for given parameter list .
See also : http : / / en . wikipedia . org / wiki / Memoization
N . B . The cache object gets added to the instance instead of the global scope .
Therefore cached results are res... | cache_name = '__CACHED_{}' . format ( func . __name__ )
def wrapper ( self , * args ) :
cache = getattr ( self , cache_name , None )
if cache is None :
cache = { }
setattr ( self , cache_name , cache )
if args not in cache :
cache [ args ] = func ( self , * args )
return cache [ ... |
def fetch_followers ( account_file , outfile , limit , do_loop ) :
"""Fetch up to limit followers for each Twitter account in
account _ file . Write results to outfile file in format :
screen _ name user _ id follower _ id _ 1 follower _ id _ 2 . . .""" | print ( 'Fetching followers for accounts in %s' % account_file )
niters = 1
while True :
outf = gzip . open ( outfile , 'wt' )
for screen_name in iter_lines ( account_file ) :
timestamp = datetime . datetime . now ( ) . isoformat ( )
print ( 'collecting followers for' , screen_name )
fol... |
def set_dtreat_order ( self , order = None ) :
"""Set the order in which the data treatment should be performed
Provide an ordered list of keywords indicating the order in which
you wish the data treatment steps to be performed .
Each keyword corresponds to a step .
Available steps are ( in default order ) ... | if order is None :
order = list ( self . _ddef [ 'dtreat' ] [ 'order' ] )
assert type ( order ) is list and all ( [ type ( ss ) is str for ss in order ] )
if not all ( [ ss in [ 'indt' , 'indch' , 'indlamb' ] for ss in order ] [ - 4 : - 1 ] ) :
msg = "indt and indch must be the treatment steps -2 and -3 !"
... |
def sodium_pad ( s , blocksize ) :
"""Pad the input bytearray ` ` s ` ` to a multiple of ` ` blocksize ` `
using the ISO / IEC 7816-4 algorithm
: param s : input bytes string
: type s : bytes
: param blocksize :
: type blocksize : int
: return : padded string
: rtype : bytes""" | ensure ( isinstance ( s , bytes ) , raising = exc . TypeError )
ensure ( isinstance ( blocksize , integer_types ) , raising = exc . TypeError )
if blocksize <= 0 :
raise exc . ValueError
s_len = len ( s )
m_len = s_len + blocksize
buf = ffi . new ( "unsigned char []" , m_len )
p_len = ffi . new ( "size_t []" , 1 )
... |
def get_multi_async ( cls , blob_keys , ** ctx_options ) :
"""Async version of get _ multi ( ) .""" | for blob_key in blob_keys :
if not isinstance ( blob_key , ( BlobKey , basestring ) ) :
raise TypeError ( 'Expected blob key, got %r' % ( blob_key , ) )
if 'parent' in ctx_options :
raise TypeError ( 'Parent is not supported' )
blob_key_strs = map ( str , blob_keys )
keys = [ model . Key ( BLOB_INFO_KIN... |
def pull ( options ) :
"""pull all remote programs to a local directory""" | configuration = config . get_default ( )
app_url = configuration [ 'app_url' ]
if options . deployment != None :
deployment_name = options . deployment
else :
deployment_name = configuration [ 'deployment_name' ]
client_id = configuration [ 'client_id' ]
client_secret = configuration [ 'client_secret' ]
token_m... |
def _set_vcs_rbridge_config ( self , v , load = False ) :
"""Setter method for vcs _ rbridge _ config , mapped from YANG variable / brocade _ vcs _ rpc / vcs _ rbridge _ config ( rpc )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ vcs _ rbridge _ config is considered ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = vcs_rbridge_config . vcs_rbridge_config , is_leaf = True , yang_name = "vcs-rbridge-config" , rest_name = "vcs-rbridge-config" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_p... |
def hardware_custom_profile_kap_custom_profile_rpvst_rpvst_hello_interval ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
hardware = ET . SubElement ( config , "hardware" , xmlns = "urn:brocade.com:mgmt:brocade-hardware" )
custom_profile = ET . SubElement ( hardware , "custom-profile" )
kap_custom_profile = ET . SubElement ( custom_profile , "kap-custom-profile" )
name_key = ET . SubElement ( kap_custom_... |
def append ( self , key , _item ) : # type : ( Union [ Key , str ] , Any ) - > Table
"""Appends a ( key , item ) to the table .""" | if not isinstance ( _item , Item ) :
_item = item ( _item )
self . _value . append ( key , _item )
if isinstance ( key , Key ) :
key = key . key
if key is not None :
super ( Table , self ) . __setitem__ ( key , _item )
m = re . match ( "(?s)^[^ ]*([ ]+).*$" , self . _trivia . indent )
if not m :
return ... |
def _wrapper ( func , * args , ** kwargs ) :
'Decorator for the methods that follow' | try :
if func . __name__ == "init" : # init may not fail , as its return code is just stored as
# private _ data field of struct fuse _ context
return func ( * args , ** kwargs ) or 0
else :
try :
return func ( * args , ** kwargs ) or 0
except OSError as e :
i... |
def convertTimestamps ( column ) :
"""Convert a dtype of a given column to a datetime .
This method tries to do this by brute force .
Args :
column ( pandas . Series ) : A Series object with all rows .
Returns :
column : Converted to datetime if no errors occured , else the
original column will be retur... | tempColumn = column
try : # Try to convert the first row and a random row instead of the complete
# column , might be faster
# tempValue = np . datetime64 ( column [ 0 ] )
tempValue = np . datetime64 ( column [ randint ( 0 , len ( column . index ) - 1 ) ] )
tempColumn = column . apply ( to_datetime )
except Exc... |
def add_tracks ( self , subtracks ) :
"""Add one or more tracks to this view .
subtracks : Track or iterable of Tracks
A single Track instance or an iterable of them .""" | if isinstance ( subtracks , Track ) :
subtracks = [ subtracks ]
for subtrack in subtracks :
subtrack . subgroups [ 'view' ] = self . view
self . add_child ( subtrack )
self . subtracks . append ( subtrack ) |
def on_windows ( ) :
"""Returns true if running on windows , whether in cygwin or not .""" | if bjam . variable ( "NT" ) :
return True
elif bjam . variable ( "UNIX" ) :
uname = bjam . variable ( "JAMUNAME" )
if uname and uname [ 0 ] . startswith ( "CYGWIN" ) :
return True
return False |
def expand_exc ( excs , search , replace ) :
"""Find string in tokenizer exceptions , duplicate entry and replace string .
For example , to add additional versions with typographic apostrophes .
excs ( dict ) : Tokenizer exceptions .
search ( unicode ) : String to find and replace .
replace ( unicode ) : Re... | def _fix_token ( token , search , replace ) :
fixed = dict ( token )
fixed [ ORTH ] = fixed [ ORTH ] . replace ( search , replace )
return fixed
new_excs = dict ( excs )
for token_string , tokens in excs . items ( ) :
if search in token_string :
new_key = token_string . replace ( search , replac... |
def build_expression_from_tree ( self , runnable , regime , tree_node ) :
"""Recursively builds a Python expression from a parsed expression tree .
@ param runnable : Runnable object to which this expression would be added .
@ type runnable : lems . sim . runnable . Runnable
@ param regime : Dynamics regime b... | component_type = self . model . component_types [ runnable . component . type ]
dynamics = component_type . dynamics
if tree_node . type == ExprNode . VALUE :
if tree_node . value [ 0 ] . isalpha ( ) :
if tree_node . value == 't' :
return 'self.time_completed'
elif tree_node . value in c... |
def handle_m2m ( self , sender , instance , ** kwargs ) :
"""Handle many to many relationships""" | self . handle_save ( instance . __class__ , instance ) |
def connect_pull ( self , timeout = 1 ) :
'''Establish a connection with the event pull socket
Default timeout is 1 s''' | if self . cpush :
return True
if self . _run_io_loop_sync :
with salt . utils . asynchronous . current_ioloop ( self . io_loop ) :
if self . pusher is None :
self . pusher = salt . transport . ipc . IPCMessageClient ( self . pulluri , io_loop = self . io_loop )
try :
self... |
def divisors ( n ) :
"""Generate the divisors of n""" | for i in range ( 1 , int ( math . sqrt ( n ) + 1 ) ) :
if n % i == 0 :
yield i
if i * i != n :
yield n / i |
def receivestealth ( scanpriv , spendpriv , ephempub ) :
'''Derive the private key for a stealth payment , using the scan and
spend private keys , and the ephemeral public key .
Input private keys should be 64 - char hex strings , and ephemeral
public key should be a 66 - char hex compressed public key .
> ... | return addprivkeys ( sha256 ( multiplypub ( ephempub , scanpriv , True ) ) , spendpriv ) |
def get ( self , * args , ** kwargs ) :
"""Get the sub interfaces for this VlanInterface
> > > itf = engine . interface . get ( 3)
> > > list ( itf . vlan _ interface )
[ Layer3PhysicalInterfaceVlan ( name = VLAN 3.3 ) , Layer3PhysicalInterfaceVlan ( name = VLAN 3.5 ) ,
Layer3PhysicalInterfaceVlan ( name = ... | if args :
kwargs = { 'vlan_id' : str ( args [ 0 ] ) }
key , value = kwargs . popitem ( )
for item in self :
if 'vlan_id' in key and getattr ( item , key , None ) == value :
return item
for vlan in item . interfaces :
if getattr ( vlan , key , None ) == value :
return item |
def _start ( self ) :
"""Starts the underlying send and receive threads .""" | # Initialize the locks
self . _recv_lock = coros . Semaphore ( 0 )
self . _send_lock = coros . Semaphore ( 0 )
# Boot the threads
self . _recv_thread = gevent . spawn ( self . _recv )
self . _send_thread = gevent . spawn ( self . _send )
# Link the threads such that we get notified if one or the
# other exits
self . _r... |
def transform ( self , path ) :
"""Transform a path into an actual Python object .
The path can be arbitrary long . You can pass the path to a package ,
a module , a class , a function or a global variable , as deep as you
want , as long as the deepest module is importable through
` ` importlib . import _ m... | if path is None or not path :
return None
obj_parent_modules = path . split ( "." )
objects = [ obj_parent_modules . pop ( - 1 ) ]
while True :
try :
parent_module_path = "." . join ( obj_parent_modules )
parent_module = importlib . import_module ( parent_module_path )
break
except I... |
def send_invitation ( self , user , sender = None , ** kwargs ) :
"""An intermediary function for sending an invitation email that
selects the templates , generating the token , and ensuring that the user
has not already joined the site .""" | if user . is_active :
return False
token = self . get_token ( user )
kwargs . update ( { "token" : token } )
self . email_message ( user , self . invitation_subject , self . invitation_body , sender , ** kwargs ) . send ( )
return True |
def info ( self , id ) :
"""Return the ` ` Package ` ` or ` ` Collection ` ` record for the
given item .""" | # self . _ update _ index ( ) # This is commented because it leads to
# excessive network load
if id in self . _packages :
return self . _packages [ id ]
if id in self . _collections :
return self . _collections [ id ]
self . _update_index ( )
# If package is not found , most probably we did not
# warm up the c... |
def run ( coro , loop = None ) :
"""Convenient shortcut alias to ` ` loop . run _ until _ complete ` ` .
Arguments :
coro ( coroutine ) : coroutine object to schedule .
loop ( asyncio . BaseEventLoop ) : optional event loop to use .
Defaults to : ` ` asyncio . get _ event _ loop ( ) ` ` .
Returns :
mixe... | loop = loop or asyncio . get_event_loop ( )
return loop . run_until_complete ( coro ) |
def com_google_fonts_check_metadata_valid_full_name_values ( style , font_metadata , font_familynames , typographic_familynames ) :
"""METADATA . pb font . full _ name field contains font name in right format ?""" | from fontbakery . constants import RIBBI_STYLE_NAMES
if style in RIBBI_STYLE_NAMES :
familynames = font_familynames
if familynames == [ ] :
yield SKIP , "No FONT_FAMILYNAME"
else :
familynames = typographic_familynames
if familynames == [ ] :
yield SKIP , "No TYPOGRAPHIC_FAMILYNAME"
for ... |
def _add_endpoints_to_config ( self , config , co_name , backend_name ) :
"""Use the request path from the context to determine the target backend ,
then construct mappings from bindings to endpoints for the virtual
IdP for the CO .
The endpoint URLs have the form
{ base } / { backend } / { co _ name } / { ... | for service , endpoint in self . endpoints . items ( ) :
idp_endpoints = [ ]
for binding , path in endpoint . items ( ) :
url = "{base}/{backend}/{co_name}/{path}" . format ( base = self . base_url , backend = backend_name , co_name = quote_plus ( co_name ) , path = path )
mapping = ( url , bind... |
def advance ( parser ) : # type : ( Parser ) - > None
"""Moves the internal parser object to the next lexed token .""" | prev_end = parser . token . end
parser . prev_end = prev_end
parser . token = parser . lexer . next_token ( prev_end ) |
def Rsync ( url , tgt_name , tgt_root = None ) :
"""RSync a folder .
Args :
url ( str ) : The url of the SOURCE location .
fname ( str ) : The name of the TARGET .
to ( str ) : Path of the target location .
Defaults to ` ` CFG [ " tmpdir " ] ` ` .""" | if tgt_root is None :
tgt_root = str ( CFG [ "tmp_dir" ] )
from benchbuild . utils . cmd import rsync
tgt_dir = local . path ( tgt_root ) / tgt_name
if not source_required ( tgt_dir ) :
Copy ( tgt_dir , "." )
return
rsync ( "-a" , url , tgt_dir )
update_hash ( tgt_dir )
Copy ( tgt_dir , "." ) |
def init_app ( self , app , config_prefix = None ) :
"""Actual method to read redis settings from app configuration , initialize
Redis connection and copy all public connection methods to current
instance .
: param app : : class : ` flask . Flask ` application instance .
: param config _ prefix : Config pre... | # Put redis to application extensions
if 'redis' not in app . extensions :
app . extensions [ 'redis' ] = { }
# Which config prefix to use , custom or default one ?
self . config_prefix = config_prefix = config_prefix or 'REDIS'
# No way to do registration two times
if config_prefix in app . extensions [ 'redis' ] ... |
def _load_secedit_data ( ) :
'''Helper function that loads secedit data . It runs ` secedit / export / cfg
< file _ name > ` which creates a file that contains the secedit data .
Returns :
str : The contents of the file generated by the secedit command''' | try :
f_exp = os . path . join ( __opts__ [ 'cachedir' ] , 'secedit-{0}.txt' . format ( UUID ) )
__salt__ [ 'cmd.run' ] ( [ 'secedit' , '/export' , '/cfg' , f_exp ] )
with io . open ( f_exp , encoding = 'utf-16' ) as fp :
secedit_data = fp . readlines ( )
return secedit_data
finally :
if __s... |
def _bsd_brdel ( br ) :
'''Internal , deletes the bridge''' | ifconfig = _tool_path ( 'ifconfig' )
if not br :
return False
return __salt__ [ 'cmd.run' ] ( '{0} {1} destroy' . format ( ifconfig , br ) , python_shell = False ) |
def add_cnt_64bit ( self , oid , value , label = None ) :
"""Short helper to add a 64 bit counter value to the MIB subtree .""" | # Truncate integer to 64bits ma , x
self . add_oid_entry ( oid , 'Counter64' , int ( value ) % 18446744073709551615 , label = label ) |
def InsertFloatArg ( self , string = '' , ** unused_kwargs ) :
"""Inserts a Float argument .""" | try :
float_value = float ( string )
except ( TypeError , ValueError ) :
raise errors . ParseError ( '{0:s} is not a valid float.' . format ( string ) )
return self . InsertArg ( float_value ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.