signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def slugify ( value , allow_unicode = False ) :
"""Normalizes string , converts to lowercase , removes non - alpha characters ,
and converts spaces to hyphens .
: param value : string
: param allow _ unicode : allow utf8 characters
: type allow _ unicode : bool
: return : slugified string
: rtype : str ... | value = str ( value )
if allow_unicode :
value = unicodedata . normalize ( 'NFKC' , value )
value = re . sub ( r'[^\w\s-]' , '' , value , flags = re . U ) . strip ( ) . lower ( )
return re . sub ( r'[-\s]+' , '-' , value , flags = re . U )
else :
value = unicodedata . normalize ( 'NFKD' , value ) . enco... |
def _make_predict_proba ( self , func ) :
"""The predict _ proba method will expect 3d arrays , but we are reshaping
them to 2D so that LIME works correctly . This wraps the function
you give in explain _ instance to first reshape the data to have
the shape the the keras - style network expects .""" | def predict_proba ( X ) :
n_samples = X . shape [ 0 ]
new_shape = ( n_samples , self . n_features , self . n_timesteps )
X = np . transpose ( X . reshape ( new_shape ) , axes = ( 0 , 2 , 1 ) )
return func ( X )
return predict_proba |
def add_callback ( self , phase , fn ) :
"""Adds a callback to the context .
The ` phase ` determines when and if the callback is executed , and which
positional arguments are passed in :
' enter '
: Called from ` rhino . Resource ` , after a handler for the current
request has been resolved , but before ... | try :
self . __callbacks [ phase ] . append ( fn )
except KeyError :
raise KeyError ( "Invalid callback phase '%s'. Must be one of %s" % ( phase , _callback_phases ) ) |
def decode_response ( client_message , to_object = None ) :
"""Decode response from client message""" | parameters = dict ( base = None , increment = None , batch_size = None )
parameters [ 'base' ] = client_message . read_long ( )
parameters [ 'increment' ] = client_message . read_long ( )
parameters [ 'batch_size' ] = client_message . read_int ( )
return parameters |
def p_exprlt ( p ) :
"""expr : expr LT expr""" | a = int ( p [ 1 ] ) if p [ 1 ] . isdigit ( ) else 0
b = int ( p [ 3 ] ) if p [ 3 ] . isdigit ( ) else 0
p [ 0 ] = '1' if a < b else '0' |
def avhrr ( scans_nb , scan_points , scan_angle = 55.37 , frequency = 1 / 6.0 , apply_offset = True ) :
"""Definition of the avhrr instrument .
Source : NOAA KLM User ' s Guide , Appendix J
http : / / www . ncdc . noaa . gov / oa / pod - guide / ncdc / docs / klm / html / j / app - j . htm""" | # build the avhrr instrument ( scan angles )
avhrr_inst = np . vstack ( ( ( scan_points / 1023.5 - 1 ) * np . deg2rad ( - scan_angle ) , np . zeros ( ( len ( scan_points ) , ) ) ) )
avhrr_inst = np . tile ( avhrr_inst [ : , np . newaxis , : ] , [ 1 , np . int ( scans_nb ) , 1 ] )
# building the corresponding times arra... |
def has_hash_of ( self , destpath , code , package ) :
"""Determine if a file has the hash of the code .""" | if destpath is not None and os . path . isfile ( destpath ) :
with openfile ( destpath , "r" ) as opened :
compiled = readfile ( opened )
hashash = gethash ( compiled )
if hashash is not None and hashash == self . comp . genhash ( package , code ) :
return compiled
return None |
def csd ( self , other , fftlength = None , overlap = None , window = 'hann' , ** kwargs ) :
"""Calculate the CSD ` FrequencySeries ` for two ` TimeSeries `
Parameters
other : ` TimeSeries `
the second ` TimeSeries ` in this CSD calculation
fftlength : ` float `
number of seconds in single FFT , defaults ... | return spectral . psd ( ( self , other ) , spectral . csd , fftlength = fftlength , overlap = overlap , window = window , ** kwargs ) |
def create_file_reader ( input_files , topology , featurizer , chunksize = None , ** kw ) :
r"""Creates a ( possibly featured ) file reader by a number of input files and either a topology file or a featurizer .
Parameters
: param input _ files :
A single input file or a list of input files .
: param topolo... | from pyemma . coordinates . data . numpy_filereader import NumPyFileReader
from pyemma . coordinates . data . py_csv_reader import PyCSVReader
from pyemma . coordinates . data import FeatureReader
from pyemma . coordinates . data . fragmented_trajectory_reader import FragmentedTrajectoryReader
# fragmented trajectories... |
def export ( self , hashVal , hashPath , tags = None , galleries = None ) :
"""The export function needs to :
- Move source image to asset folder
- Rename to guid . ext
- Save thumbnail , video _ thumbnail , and MP4 versions . If the source is already h264 , then only transcode the thumbnails""" | self . source = hashPath . replace ( '\\' , '/' ) . replace ( ROOT , '' )
galleries = galleries or [ ]
tags = tags or [ ]
# - - Get info
videodata = self . info ( )
self . width = videodata [ 'width' ]
self . height = videodata [ 'height' ]
self . framerate = videodata [ 'framerate' ]
self . duration = videodata [ 'dur... |
def main ( jlink_serial , device ) :
"""Main function .
Args :
jlink _ serial ( str ) : the J - Link serial number
device ( str ) : the target CPU
Returns :
` ` None ` `
Raises :
JLinkException : on error""" | buf = StringIO . StringIO ( )
jlink = pylink . JLink ( log = buf . write , detailed_log = buf . write )
jlink . open ( serial_no = jlink_serial )
jlink . set_tif ( pylink . enums . JLinkInterfaces . SWD )
jlink . connect ( device , verbose = True )
# Figure out our original endianess first .
big_endian = jlink . set_li... |
def _check_for_mismatches ( self , known_keys ) :
"""check for bad options from value sources""" | for a_value_source in self . values_source_list :
try :
if a_value_source . always_ignore_mismatches :
continue
except AttributeError : # ok , this values source doesn ' t have the concept
# always igoring mismatches , we won ' t tolerate mismatches
pass
# we want to fetch th... |
def _init_map ( self , record_types = None , ** kwargs ) :
"""Initialize form map""" | osid_objects . OsidObjectForm . _init_map ( self , record_types = record_types )
self . _my_map [ 'numericScoreIncrement' ] = self . _numeric_score_increment_default
self . _my_map [ 'lowestNumericScore' ] = self . _lowest_numeric_score_default
self . _my_map [ 'basedOnGrades' ] = self . _based_on_grades_default
self .... |
def uniqify_once ( func ) :
"""Make sure that a method returns a unique name .""" | @ six . wraps ( func )
def unique_once ( self , * args , ** kwargs ) :
return self . unique_once ( func ( self , * args , ** kwargs ) )
return unique_once |
def log_info ( msg , logger = "TaskLogger" ) :
"""Log an INFO message
Convenience function to log a message to the default Logger
Parameters
msg : str
Message to be logged
logger : str , optional ( default : " TaskLogger " )
Unique name of the logger to retrieve
Returns
logger : TaskLogger""" | tasklogger = get_tasklogger ( logger )
tasklogger . info ( msg )
return tasklogger |
def on_session_start ( self , data ) : # pylint : disable = W0613
"""XMPP session started""" | # Send initial presence
self . send_presence ( ppriority = self . _initial_priority )
# Request roster
self . get_roster ( ) |
def inet_pton ( af , addr ) :
"""Convert an IP address from text representation into binary form""" | print ( 'hello' )
if af == socket . AF_INET :
return inet_aton ( addr )
elif af == socket . AF_INET6 : # IPv6 : The use of " : : " indicates one or more groups of 16 bits of zeros .
# We deal with this form of wildcard using a special marker .
JOKER = b"*"
while b"::" in addr :
addr = addr . replace... |
def urban_adj_factor ( self ) :
"""Return urban adjustment factor ( UAF ) used to adjust QMED and growth curves .
Methodology source : eqn . 8 , Kjeldsen 2010
: return : urban adjustment factor
: rtype : float""" | urbext = self . catchment . descriptors . urbext ( self . year )
result = self . _pruaf ( ) ** 2.16 * ( 1 + urbext ) ** 0.37
self . results_log [ 'urban_extent' ] = urbext
self . results_log [ 'urban_adj_factor' ] = result
return result |
def _compute_acq ( self , x ) :
"""Integrated Expected Improvement""" | means , stds = self . model . predict ( x )
fmins = self . model . get_fmin ( )
f_acqu = 0
for m , s , fmin in zip ( means , stds , fmins ) :
_ , Phi , _ = get_quantiles ( self . jitter , fmin , m , s )
f_acqu += Phi
return f_acqu / len ( means ) |
def mod_watch ( name , ** kwargs ) :
'''Install / reinstall a package based on a watch requisite
. . note : :
This state exists to support special handling of the ` ` watch ` `
: ref : ` requisite < requisites > ` . It should not be called directly .
Parameters for this function should be set by the state b... | sfun = kwargs . pop ( 'sfun' , None )
mapfun = { 'purged' : purged , 'latest' : latest , 'removed' : removed , 'installed' : installed }
if sfun in mapfun :
return mapfun [ sfun ] ( name , ** kwargs )
return { 'name' : name , 'changes' : { } , 'comment' : 'pkg.{0} does not work with the watch requisite' . format ( ... |
def is_same_channel ( self , left , right ) :
"""Check if given nicknames are equal in the server ' s case mapping .""" | return self . normalize ( left ) == self . normalize ( right ) |
def apply_with ( self , _ , val , ctx ) :
"""constructor
example val :
# header values used in multipart / form - data according to RFC2388
' header ' : {
' Content - Type ' : ' text / plain ' ,
# according to RFC2388 , available values are ' 7bit ' , ' 8bit ' , ' binary '
' Content - Transfer - Encodin... | self . header = val . get ( 'header' , { } )
self . data = val . get ( 'data' , None )
self . filename = val . get ( 'filename' , '' )
if self . data == None and self . filename == '' :
raise ValidationError ( 'should have file name or file object, not: {0}, {1}' . format ( self . data , self . filename ) ) |
def get_cache_key ( page ) :
"""Create the cache key for the current page and language""" | try :
site_id = page . node . site_id
except AttributeError :
site_id = page . site_id
return _get_cache_key ( 'page_sitemap' , page , 'default' , site_id ) |
def _SerializeAttributeContainer ( self , attribute_container ) :
"""Serializes an attribute container .
Args :
attribute _ container ( AttributeContainer ) : attribute container .
Returns :
bytes : serialized attribute container .
Raises :
IOError : if the attribute container cannot be serialized .
O... | if self . _serializers_profiler :
self . _serializers_profiler . StartTiming ( attribute_container . CONTAINER_TYPE )
try :
attribute_container_data = self . _serializer . WriteSerialized ( attribute_container )
if not attribute_container_data :
raise IOError ( 'Unable to serialize attribute contain... |
def remove_last_entry ( self ) :
"""Remove the last NoteContainer in the Bar .""" | self . current_beat -= 1.0 / self . bar [ - 1 ] [ 1 ]
self . bar = self . bar [ : - 1 ]
return self . current_beat |
def __parse_stream ( self , stream ) :
"""Generic method to parse mailmap streams""" | nline = 0
lines = stream . split ( '\n' )
for line in lines :
nline += 1
# Ignore blank lines and comments
m = re . match ( self . LINES_TO_IGNORE_REGEX , line , re . UNICODE )
if m :
continue
line = line . strip ( '\n' ) . strip ( ' ' )
parts = line . split ( '>' )
if len ( parts ) ... |
def add_dir ( self , path , compress ) :
"""Add all files under directory ` path ` to the MAR file .
Args :
path ( str ) : path to directory to add to this MAR file
compress ( str ) : One of ' xz ' , ' bz2 ' , or None . Defaults to None .""" | if not os . path . isdir ( path ) :
raise ValueError ( '{} is not a directory' . format ( path ) )
for root , dirs , files in os . walk ( path ) :
for f in files :
self . add_file ( os . path . join ( root , f ) , compress ) |
def eval ( self , expr , inplace = False , ** kwargs ) :
"""Evaluate a string describing operations on DataFrame columns .
Operates on columns only , not specific rows or elements . This allows
` eval ` to run arbitrary code , which can make you vulnerable to code
injection if you pass user input to this func... | from pandas . core . computation . eval import eval as _eval
inplace = validate_bool_kwarg ( inplace , 'inplace' )
resolvers = kwargs . pop ( 'resolvers' , None )
kwargs [ 'level' ] = kwargs . pop ( 'level' , 0 ) + 1
if resolvers is None :
index_resolvers = self . _get_index_resolvers ( )
column_resolvers = sel... |
def get_primitive_standard_structure ( self , international_monoclinic = True ) :
"""Gives a structure with a primitive cell according to certain standards
the standards are defined in Setyawan , W . , & Curtarolo , S . ( 2010 ) .
High - throughput electronic band structure calculations :
Challenges and tools... | conv = self . get_conventional_standard_structure ( international_monoclinic = international_monoclinic )
lattice = self . get_lattice_type ( )
if "P" in self . get_space_group_symbol ( ) or lattice == "hexagonal" :
return conv
transf = self . get_conventional_to_primitive_transformation_matrix ( international_mono... |
def GetTaskPendingMerge ( self , current_task ) :
"""Retrieves the first task that is pending merge or has a higher priority .
This function will check if there is a task with a higher merge priority
than the current _ task being merged . If so , that task with the higher
priority is returned .
Args :
cur... | next_task = self . _tasks_pending_merge . PeekTask ( )
if not next_task :
return None
if current_task and next_task . merge_priority > current_task . merge_priority :
return None
with self . _lock :
next_task = self . _tasks_pending_merge . PopTask ( )
self . _tasks_merging [ next_task . identifier ] = next... |
def patch_custom_resource_definition_status ( self , name , body , ** kwargs ) : # noqa : E501
"""patch _ custom _ resource _ definition _ status # noqa : E501
partially update status of the specified CustomResourceDefinition # noqa : E501
This method makes a synchronous HTTP request by default . To make an
a... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . patch_custom_resource_definition_status_with_http_info ( name , body , ** kwargs )
# noqa : E501
else :
( data ) = self . patch_custom_resource_definition_status_with_http_info ( name , body , ** kwargs )
# noqa :... |
def libnet ( self ) :
"""Not ready yet . Should give the necessary C code that interfaces with libnet to recreate the packet""" | print ( "libnet_build_%s(" % self . __class__ . name . lower ( ) )
det = self . __class__ ( str ( self ) )
for f in self . fields_desc :
val = det . getfieldval ( f . name )
if val is None :
val = 0
elif type ( val ) is int :
val = str ( val )
else :
val = '"%s"' % str ( val )
... |
def unparse_flags ( self ) :
"""Unparses all flags to the point before any FLAGS ( argv ) was called .""" | for f in self . _flags ( ) . values ( ) :
f . unparse ( )
# We log this message before marking flags as unparsed to avoid a
# problem when the logging library causes flags access .
logging . info ( 'unparse_flags() called; flags access will now raise errors.' )
self . __dict__ [ '__flags_parsed' ] = False
self . __... |
def init ( self ) :
"""Init the connection to the rabbitmq server .""" | if not self . export_enable :
return None
try :
parameters = pika . URLParameters ( 'amqp://' + self . user + ':' + self . password + '@' + self . host + ':' + self . port + '/' )
connection = pika . BlockingConnection ( parameters )
channel = connection . channel ( )
return channel
except Exception... |
def bench ( client , n ) :
"""Benchmark n requests""" | items = list ( range ( n ) )
# Time client publish operations
started = time . time ( )
msg = b'x'
for i in items :
client . socket . send ( msg )
res = client . socket . recv ( )
assert msg == res
duration = time . time ( ) - started
print ( 'Raw REQ client stats:' )
util . print_stats ( n , duration ) |
def variant_context_w_alignment ( am , var , margin = 20 , tx_ac = None ) :
"""This module is experimental . It requires the uta _ align package from pypi .""" | from uta_align . align . algorithms import align , cigar_alignment
fh = full_house ( am , var , tx_ac = tx_ac )
tm = am . _fetch_AlignmentMapper ( fh [ 'n' ] . ac , fh [ 'g' ] . ac , am . alt_aln_method )
strand = tm . strand
span_g = _ival_to_span ( fh [ 'g' ] . posedit . pos )
span_g = ( span_g [ 0 ] - margin , span_... |
def _load_text_assets ( self , text_image_file , text_file ) :
"""Internal . Builds a character indexed dictionary of pixels used by the
show _ message function below""" | text_pixels = self . load_image ( text_image_file , False )
with open ( text_file , 'r' ) as f :
loaded_text = f . read ( )
self . _text_dict = { }
for index , s in enumerate ( loaded_text ) :
start = index * 40
end = start + 40
char = text_pixels [ start : end ]
self . _text_dict [ s ] = char |
def get_max_id ( cls , session ) :
"""Get the current max value of the ` ` id ` ` column .
When creating and storing ORM objects in bulk , : mod : ` sqlalchemy ` does not automatically
generate an incrementing primary key ` ` id ` ` . To do this manually , one needs to know the
current max ` ` id ` ` . For OR... | # sqlalchemy allows only one level of inheritance , so just check this class and all its bases
id_base = None
for c in [ cls ] + list ( cls . __bases__ ) :
for base_class in c . __bases__ :
if base_class . __name__ == 'Base' :
if id_base is None : # we found our base class for determining the ID... |
def update_subscription ( self , subscription_id , url = None , events = None ) :
"""Create subscription
: param subscription _ id : Subscription to update
: param events : Events to subscribe
: param url : Url to send events""" | params = { }
if url is not None :
params [ 'url' ] = url
if events is not None :
params [ 'events' ] = events
url = self . SUBSCRIPTIONS_ID_URL % subscription_id
connection = Connection ( self . token )
connection . set_url ( self . production , url )
connection . add_header ( 'Content-Type' , 'application/json... |
def _makeTimingRelative ( absoluteDataList ) :
'''Given normal pitch tier data , puts the times on a scale from 0 to 1
Input is a list of tuples of the form
( [ ( time1 , pitch1 ) , ( time2 , pitch2 ) , . . . ]
Also returns the start and end time so that the process can be reversed''' | timingSeq = [ row [ 0 ] for row in absoluteDataList ]
valueSeq = [ list ( row [ 1 : ] ) for row in absoluteDataList ]
relTimingSeq , startTime , endTime = makeSequenceRelative ( timingSeq )
relDataList = [ tuple ( [ time , ] + row ) for time , row in zip ( relTimingSeq , valueSeq ) ]
return relDataList , startTime , en... |
def find_cards ( self , source = None , ** filters ) :
"""Generate a card pool with all cards matching specified filters""" | if not filters :
new_filters = self . filters . copy ( )
else :
new_filters = filters . copy ( )
for k , v in new_filters . items ( ) :
if isinstance ( v , LazyValue ) :
new_filters [ k ] = v . evaluate ( source )
from . . import cards
return cards . filter ( ** new_filters ) |
def load_cfg ( path , envvar_prefix = 'LIBREANT_' , debug = False ) :
'''wrapper of config _ utils . load _ configs''' | try :
return load_configs ( envvar_prefix , path = path )
except Exception as e :
if debug :
raise
else :
die ( str ( e ) ) |
def t_multiline_NEWLINE ( self , t ) :
r'\ r \ n | \ n | \ r' | if t . lexer . multiline_newline_seen :
return self . t_multiline_OPTION_AND_VALUE ( t )
t . lexer . multiline_newline_seen = True |
def write_config_file ( self , f , comments ) :
"""This method write a sample file , with attributes , descriptions ,
sample values , required flags , using the configuration object
properties .""" | if len ( self . elements ) < 1 :
return
super ( _Section , self ) . write_config_file ( f , comments )
for e in self . elements . values ( ) :
e . write_config_file ( f , comments )
f . write ( "\n" ) |
def get_parameters_as_dictionary ( self , query_string ) :
"""Returns query string parameters as a dictionary .""" | pairs = ( x . split ( '=' , 1 ) for x in query_string . split ( '&' ) )
return dict ( ( k , unquote ( v ) ) for k , v in pairs ) |
def _valid_config ( self , settings ) :
"""Scan through the returned settings to ensure they appear sane .
There are time when the returned buffer has the proper information , but
the reading is inaccurate . When this happens , temperatures will swing
or system values will be set to improper values .
: para... | if ( ( int ( settings [ 'environment_temp' ] ) > self . MAX_BOUND_TEMP or int ( settings [ 'environment_temp' ] ) < self . MIN_BOUND_TEMP ) or ( int ( settings [ 'bean_temp' ] ) > self . MAX_BOUND_TEMP or int ( settings [ 'bean_temp' ] ) < self . MIN_BOUND_TEMP ) ) :
self . _log . error ( 'Temperatures are outside ... |
def logfile_generator ( self ) :
"""Yield each line of the file , or the next line if several files .""" | if not self . args [ 'exclude' ] : # ask all filters for a start _ limit and fast - forward to the maximum
start_limits = [ f . start_limit for f in self . filters if hasattr ( f , 'start_limit' ) ]
if start_limits :
for logfile in self . args [ 'logfile' ] :
logfile . fast_forward ( max ( s... |
def compile ( self , csdl ) :
"""Compile the given CSDL .
Uses API documented at http : / / dev . datasift . com / docs / api / rest - api / endpoints / compile
Raises a DataSiftApiException for any error given by the REST API , including CSDL compilation .
: param csdl : CSDL to compile
: type csdl : str
... | return self . request . post ( 'compile' , data = dict ( csdl = csdl ) ) |
def detach_internet_gateway ( self , internet_gateway_id , vpc_id ) :
"""Detach an internet gateway from a specific VPC .
: type internet _ gateway _ id : str
: param internet _ gateway _ id : The ID of the internet gateway to delete .
: type vpc _ id : str
: param vpc _ id : The ID of the VPC to attach to ... | params = { 'InternetGatewayId' : internet_gateway_id , 'VpcId' : vpc_id }
return self . get_status ( 'DetachInternetGateway' , params ) |
def next_undecoded_checkpoint ( model_dir , timeout_mins = 240 ) :
"""Yields successive checkpoints from model _ dir .""" | last_ckpt = None
last_step = 0
while True : # Get the latest checkpoint .
last_ckpt = tf . contrib . training . wait_for_new_checkpoint ( model_dir , last_ckpt , seconds_to_sleep = 60 , timeout = 60 * timeout_mins )
# Get all the checkpoint from the model dir .
ckpt_path = tf . train . get_checkpoint_state ... |
def _get_proc_status ( proc ) :
'''Returns the status of a Process instance .
It ' s backward compatible with < 2.0 versions of psutil .''' | try :
return salt . utils . data . decode ( proc . status ( ) if PSUTIL2 else proc . status )
except ( psutil . NoSuchProcess , psutil . AccessDenied ) :
return None |
def create ( self ) :
"""POST / layertemplates : Create a new item .""" | # url ( ' layertemplates ' )
content = request . environ [ 'wsgi.input' ] . read ( int ( request . environ [ 'CONTENT_LENGTH' ] ) )
content = content . decode ( 'utf8' )
content = simplejson . loads ( content )
lt = self . _new_lt_from_user ( content [ 'name' ] , content [ 'comment' ] , content [ 'json' ] , c . user )
... |
def list_commands ( self , ctx ) :
"""List all sub - commands .""" | env = ctx . ensure_object ( environment . Environment )
env . load ( )
return sorted ( env . list_commands ( * self . path ) ) |
def drain ( self , cluster , nodes , max_size ) :
"""Drain all the data for the given nodes and collate them into a list of
batches that will fit within the specified size on a per - node basis .
This method attempts to avoid choosing the same topic - node repeatedly .
Arguments :
cluster ( ClusterMetadata ... | if not nodes :
return { }
now = time . time ( )
batches = { }
for node_id in nodes :
size = 0
partitions = list ( cluster . partitions_for_broker ( node_id ) )
ready = [ ]
# to make starvation less likely this loop doesn ' t start at 0
self . _drain_index %= len ( partitions )
start = self .... |
def _move_file_with_sizecheck ( tx_file , final_file ) :
"""Move transaction file to final location ,
with size checks avoiding failed transfers .
Creates an empty file with ' . bcbiotmp ' extention in the destination
location , which serves as a flag . If a file like that is present ,
it means that transac... | # logger . debug ( " Moving % s to % s " % ( tx _ file , final _ file ) )
tmp_file = final_file + ".bcbiotmp"
open ( tmp_file , 'wb' ) . close ( )
want_size = utils . get_size ( tx_file )
shutil . move ( tx_file , final_file )
transfer_size = utils . get_size ( final_file )
assert want_size == transfer_size , ( 'distri... |
def render ( self , link_url , image_url , ** kwargs ) :
"""Preview link _ url and image _ url after interpolation .
Args :
link _ url ( str ) : URL of the badge link
image _ url ( str ) : URL of the badge image
* * kwargs : Extra options to send to the server ( e . g . sudo )
Raises :
GitlabAuthenticat... | path = '%s/render' % self . path
data = { 'link_url' : link_url , 'image_url' : image_url }
return self . gitlab . http_get ( path , data , ** kwargs ) |
def ReadLsbBytes ( rd , offset , value_size ) :
"""Reads value _ size bytes from rd at offset , least signifcant byte first .""" | encoding = None
if value_size == 1 :
encoding = '<B'
elif value_size == 2 :
encoding = '<H'
elif value_size == 4 :
encoding = '<L'
else :
raise errors . HidError ( 'Invalid value size specified' )
ret , = struct . unpack ( encoding , rd [ offset : offset + value_size ] )
return ret |
def nlmsg_attrlen ( nlh , hdrlen ) :
"""Length of attributes data .
https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / msg . c # L154
nlh - - Netlink message header ( nlmsghdr class instance ) .
hdrlen - - length of family specific header ( integer ) .
Returns :
Integer .""" | return max ( nlmsg_len ( nlh ) - libnl . linux_private . netlink . NLMSG_ALIGN ( hdrlen ) , 0 ) |
def process_item ( self , item ) :
"""Calculate new maximum value for each group ,
for " new " items only .""" | group , value = item [ 'group' ] , item [ 'value' ]
if group in self . _groups :
cur_val = self . _groups [ group ]
self . _groups [ group ] = max ( cur_val , value )
else : # New group . Could fetch old max . from target collection ,
# but for the sake of illustration recalculate it from
# the source collectio... |
def answers ( self ) :
"""获取收藏夹内所有答案对象 .
: return : 收藏夹内所有答案 , 返回生成器
: rtype : Answer . Iterable""" | self . _make_soup ( )
# noinspection PyTypeChecker
for answer in self . _page_get_answers ( self . soup ) :
yield answer
i = 2
while True :
soup = BeautifulSoup ( self . _session . get ( self . url [ : - 1 ] + '?page=' + str ( i ) ) . text )
for answer in self . _page_get_answers ( soup ) :
if answe... |
def _create_map ( self ) :
"""Initialize Brzozowski Algebraic Method""" | # at state i is represented by the regex self . B [ i ]
for state_a in self . mma . states :
self . A [ state_a . stateid ] = { }
# Create a map state to state , with the transition symbols
for arc in state_a . arcs :
if arc . nextstate in self . A [ state_a . stateid ] :
self . A [ stat... |
def _unmarshal_relationships ( pkg_reader , package , parts ) :
"""Add a relationship to the source object corresponding to each of the
relationships in * pkg _ reader * with its target _ part set to the actual
target part in * parts * .""" | for source_uri , srel in pkg_reader . iter_srels ( ) :
source = package if source_uri == '/' else parts [ source_uri ]
target = ( srel . target_ref if srel . is_external else parts [ srel . target_partname ] )
source . load_rel ( srel . reltype , target , srel . rId , srel . is_external ) |
def traffic ( stack_name : str , stack_version : Optional [ str ] , percentage : Optional [ int ] , region : Optional [ str ] , remote : Optional [ str ] , output : Optional [ str ] ) :
'''Manage stack traffic''' | lizzy = setup_lizzy_client ( remote )
if percentage is None :
stack_reference = [ stack_name ]
with Action ( 'Requesting traffic info..' ) :
stack_weights = [ ]
for stack in lizzy . get_stacks ( stack_reference , region = region ) :
if stack [ 'status' ] in [ 'CREATE_COMPLETE' , 'UPD... |
def save_as ( self , fname , obj = None ) :
"""Save DICOM file given a GDCM DICOM object .
Examples of a GDCM DICOM object :
* gdcm . Writer ( )
* gdcm . Reader ( )
* gdcm . Anonymizer ( )
: param fname : DICOM file name to be saved
: param obj : DICOM object to be saved , if None , Anonymizer ( ) is us... | writer = gdcm . Writer ( )
writer . SetFileName ( fname )
if obj is None and self . _anon_obj :
obj = self . _anon_obj
else :
raise ValueError ( "Need DICOM object, e.g. obj=gdcm.Anonymizer()" )
writer . SetFile ( obj . GetFile ( ) )
if not writer . Write ( ) :
raise IOError ( "Could not save DICOM file" )
... |
def step ( self , observation , argmax_sampling = False ) :
"""Select actions based on model ' s output""" | policy_params , q = self ( observation )
actions = self . action_head . sample ( policy_params , argmax_sampling = argmax_sampling )
# log probability - we can do that , because we support only discrete action spaces
logprobs = self . action_head . logprob ( actions , policy_params )
return { 'actions' : actions , 'q' ... |
def compute_similarity_score ( self , unit1 , unit2 ) :
"""Returns the similarity score between two words .
The type of similarity scoring method used depends on the currently active
method and clustering type .
: param unit1 : Unit object corresponding to the first word .
: type unit1 : Unit
: param unit... | if self . type == "PHONETIC" :
word1 = unit1 . phonetic_representation
word2 = unit2 . phonetic_representation
if self . current_similarity_measure == "phone" :
word1_length , word2_length = len ( word1 ) , len ( word2 )
if word1_length > word2_length : # Make sure n < = m , to use O ( min (... |
def _init_log ( level = logging . DEBUG ) :
"""Initialise the logging object .
Args :
level ( int ) : Logging level .
Returns :
Logger : Python logging object .""" | log = logging . getLogger ( __file__ )
log . setLevel ( level )
handler = logging . StreamHandler ( sys . stdout )
handler . setLevel ( level )
formatter = logging . Formatter ( '%(asctime)s: %(message)s' , '%Y/%m/%d-%H:%M:%S' )
handler . setFormatter ( formatter )
log . addHandler ( handler )
return log |
def properties_observer ( instance , prop , callback , ** kwargs ) :
"""Adds properties callback handler""" | change_only = kwargs . get ( 'change_only' , True )
observer ( instance , prop , callback , change_only = change_only ) |
def get_premises_model ( ) :
"""Support for custom company premises model
with developer friendly validation .""" | try :
app_label , model_name = PREMISES_MODEL . split ( '.' )
except ValueError :
raise ImproperlyConfigured ( "OPENINGHOURS_PREMISES_MODEL must be of the" " form 'app_label.model_name'" )
premises_model = get_model ( app_label = app_label , model_name = model_name )
if premises_model is None :
raise Improp... |
def evaluate_selection ( self ) :
"""Evaluates current * * Script _ Editor _ tabWidget * * Widget tab Model editor
selected content in the interactive console .
: return : Method success .
: rtype : bool""" | editor = self . get_current_editor ( )
if not editor :
return False
LOGGER . debug ( "> Evaluating 'Script Editor' selected content." )
if self . evaluate_code ( foundations . strings . to_string ( editor . get_selected_text ( ) . replace ( QChar ( QChar . ParagraphSeparator ) , QString ( "\n" ) ) ) ) :
self . ... |
def setUserPasswdCredentials ( self , username , password ) :
"""Set username and password in ` ` disk . 0 . os . credentials ` ` .""" | self . setCredentialValues ( username = username , password = password ) |
def follow_bytes ( self , s , index ) :
"Follows transitions ." | for ch in s :
index = self . follow_char ( int_from_byte ( ch ) , index )
if index is None :
return None
return index |
def _nacm_default_deny_stmt ( self , stmt : Statement , sctx : SchemaContext ) -> None :
"""Set NACM default access .""" | if not hasattr ( self , 'default_deny' ) :
return
if stmt . keyword == "default-deny-all" :
self . default_deny = DefaultDeny . all
elif stmt . keyword == "default-deny-write" :
self . default_deny = DefaultDeny . write |
def _init_tag ( self , tag ) :
"""True constructor , which really initializes the : class : ` HTMLElement ` .
This is the function where all the preprocessing happens .
Args :
tag ( str ) : HTML tag as string .""" | self . _element = tag
self . _parseIsTag ( )
self . _parseIsComment ( )
if not self . _istag or self . _iscomment :
self . _tagname = self . _element
else :
self . _parseTagName ( )
if self . _iscomment or not self . _istag :
return
self . _parseIsEndTag ( )
self . _parseIsNonPairTag ( )
if self . _istag an... |
def quick_add ( self , api_token , text , ** kwargs ) :
"""Add a task using the Todoist ' Quick Add Task ' syntax .
: param api _ token : The user ' s login api _ token .
: type api _ token : str
: param text : The text of the task that is parsed . A project
name starts with the ` # ` character , a label st... | params = { 'token' : api_token , 'text' : text }
return self . _post ( 'quick/add' , params , ** kwargs ) |
def obj_classes_from_module ( module ) :
"""Return a list of classes in a module that have a ' classID ' attribute .""" | for name in dir ( module ) :
if not name . startswith ( '_' ) :
cls = getattr ( module , name )
if getattr ( cls , 'classID' , None ) :
yield ( name , cls ) |
def specificity ( Ntn , Nfp , eps = numpy . spacing ( 1 ) ) :
"""Specificity
Wikipedia entry https : / / en . wikipedia . org / wiki / Sensitivity _ and _ specificity
Parameters
Ntn : int > = 0
Number of true negatives .
Nfp : int > = 0
Number of false positives .
eps : float
eps .
Default value n... | return float ( Ntn / ( Ntn + Nfp + eps ) ) |
def get ( self , sid ) :
"""Constructs a CredentialListContext
: param sid : The unique string that identifies the resource
: returns : twilio . rest . trunking . v1 . trunk . credential _ list . CredentialListContext
: rtype : twilio . rest . trunking . v1 . trunk . credential _ list . CredentialListContext"... | return CredentialListContext ( self . _version , trunk_sid = self . _solution [ 'trunk_sid' ] , sid = sid , ) |
def transform ( self , target_type : Type [ T ] , value : F , context : PipelineContext = None ) -> T :
"""Transforms an object to a new type .
Args :
target _ type : The type to be converted to .
value : The object to be transformed .
context : The context of the transformation ( mutable ) .""" | pass |
def asl_obctrl_send ( self , timestamp , uElev , uThrot , uThrot2 , uAilL , uAilR , uRud , obctrl_status , force_mavlink1 = False ) :
'''Off - board controls / commands for ASLUAVs
timestamp : Time since system start [ us ] ( uint64 _ t )
uElev : Elevator command [ ~ ] ( float )
uThrot : Throttle command [ ~ ... | return self . send ( self . asl_obctrl_encode ( timestamp , uElev , uThrot , uThrot2 , uAilL , uAilR , uRud , obctrl_status ) , force_mavlink1 = force_mavlink1 ) |
def linkify_sd_by_s ( self , hosts , services ) :
"""Replace dependent _ service _ description and service _ description
in service dependency by the real object
: param hosts : host list , used to look for a specific one
: type hosts : alignak . objects . host . Hosts
: param services : service list to loo... | to_del = [ ]
errors = self . configuration_errors
warns = self . configuration_warnings
for servicedep in self :
try :
s_name = servicedep . dependent_service_description
hst_name = servicedep . dependent_host_name
# The new member list , in id
serv = services . find_srv_by_name_and_... |
def fhi_header ( filename , ppdesc ) :
"""Parse the FHI abinit header . Example :
Troullier - Martins psp for element Sc Thu Oct 27 17:33:22 EDT 1994
21.00000 3.00000 940714 zatom , zion , pspdat
1 1 2 0 2001 . 00000 pspcod , pspxc , lmax , lloc , mmax , r2well
1.80626423934776 . 22824404341771 1.1737896812... | lines = _read_nlines ( filename , 4 )
try :
header = _dict_from_lines ( lines [ : 4 ] , [ 0 , 3 , 6 , 3 ] )
except ValueError : # The last record with rchrg . . . seems to be optional .
header = _dict_from_lines ( lines [ : 3 ] , [ 0 , 3 , 6 ] )
summary = lines [ 0 ]
return NcAbinitHeader ( summary , ** header ... |
def calculate ( self , calc , formula_reg , data_reg , out_reg , timestep = None , idx = None ) :
"""Calculate looping over specified repeat arguments .
: param calc : Calculation to loop over .
: param formula _ reg : Formula registry
: param data _ reg : Data registry
: param out _ reg : Outputs registry ... | # the superclass Calculator . calculate ( ) method
base_calculator = super ( LazyLoopingCalculator , self ) . calculate
# call base calculator and return if there are no repeat args
if not self . repeat_args :
base_calculator ( calc , formula_reg , data_reg , out_reg , timestep , idx )
return
# make dictionarie... |
def _search_env ( keys ) :
"""Search the environment for the supplied keys , returning the first
one found or None if none was found .""" | matches = ( os . environ [ key ] for key in keys if key in os . environ )
return next ( matches , None ) |
def get_max_url_file_name_length ( savepath ) :
"""Determines the max length for any max . . . parts .
: param str savepath : absolute savepath to work on
: return : max . allowed number of chars for any of the max . . . parts""" | number_occurrences = savepath . count ( '%max_url_file_name' )
number_occurrences += savepath . count ( '%appendmd5_max_url_file_name' )
savepath_copy = savepath
size_without_max_url_file_name = len ( savepath_copy . replace ( '%max_url_file_name' , '' ) . replace ( '%appendmd5_max_url_file_name' , '' ) )
# Windows : m... |
def _generate_consumer_tag ( self ) :
"""Generate a unique consumer tag .
: rtype string :""" | return "%s.%s%s" % ( self . __class__ . __module__ , self . __class__ . __name__ , self . _next_consumer_tag ( ) ) |
def first_cyclic_node ( head ) :
""": type head : Node
: rtype : Node""" | runner = walker = head
while runner and runner . next :
runner = runner . next . next
walker = walker . next
if runner is walker :
break
if runner is None or runner . next is None :
return None
walker = head
while runner is not walker :
runner , walker = runner . next , walker . next
return ... |
def rollback ( name , ** kwargs ) :
'''Rollbacks the committed changes .
. . code - block : : yaml
rollback the changes :
junos :
- rollback
- id : 5
Parameters :
Optional
* id :
The rollback id value [ 0-49 ] . ( default = 0)
* kwargs : Keyworded arguments which can be provided like -
* timeo... | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
ret [ 'changes' ] = __salt__ [ 'junos.rollback' ] ( ** kwargs )
return ret |
def get_server_certificate ( self , host , port ) :
"""Gets the remote x . 509 certificate
: param host :
: param port :
: return :""" | logger . info ( "Fetching server certificate from %s:%s" % ( host , port ) )
try :
return get_server_certificate ( ( host , int ( port ) ) )
except Exception as e :
logger . error ( 'Error getting server certificate from %s:%s: %s' % ( host , port , e ) )
return False |
def _eval ( self , teaching ) :
"""Returns the evaluation .""" | # transform if someone called _ get directly
if isinstance ( teaching , string_types ) :
teaching = self . _validate_teaching ( None , teaching , namespaces = self . _namespaces )
return teaching ( self . _dataObject ) |
def report_onlysize ( bytes_so_far , total_size , speed , eta ) :
'''This callback for the download function is used when console width
is not enough to print the bar .
It prints only the sizes''' | percent = int ( bytes_so_far * 100 / total_size )
current = approximate_size ( bytes_so_far ) . center ( 10 )
total = approximate_size ( total_size ) . center ( 10 )
sys . stdout . write ( 'D: {0}% -{1}/{2}' . format ( percent , current , total ) + "eta {0}" . format ( eta ) )
sys . stdout . write ( "\r" )
sys . stdout... |
def tsort ( self ) :
"""Given a partial ordering , return a totally ordered list .
part is a dict of partial orderings . Each value is a set ,
which the key depends on .
The return value is a list of sets , each of which has only
dependencies on items in previous entries in the list .
raise ValueError if ... | task_dict = { }
for key , task in self . tasks . iteritems ( ) :
task_dict [ task ] = task . dependencies
# parts = parts . copy ( )
parts = task_dict . copy ( )
result = [ ]
while True :
level = set ( [ name for name , deps in parts . iteritems ( ) if not deps ] )
if not level :
break
result . ... |
def is_allowed_view ( perm ) :
"""Check if permission is in acl list .""" | # Check if permission is in excluded list
for view in ACL_EXCLUDED_VIEWS :
module , separator , view_name = view . partition ( '*' )
if view and perm . startswith ( module ) :
return False
# Check if permission is in acl list
for view in ACL_ALLOWED_VIEWS :
module , separator , view_name = view . pa... |
def filter_extant_exports ( client , bucket , prefix , days , start , end = None ) :
"""Filter days where the bucket already has extant export keys .""" | end = end or datetime . now ( )
# days = [ start + timedelta ( i ) for i in range ( ( end - start ) . days ) ]
try :
tag_set = client . get_object_tagging ( Bucket = bucket , Key = prefix ) . get ( 'TagSet' , [ ] )
except ClientError as e :
if e . response [ 'Error' ] [ 'Code' ] != 'NoSuchKey' :
raise
... |
def unwind ( self , path , include_array_index = None , preserve_null_and_empty_arrays = False ) :
"""Adds an unwind stage to deconstruct an array
: param path : Field path to an array field
: param include _ array _ index : The name of a new field to hold the array index of the element .
: param preserve _ n... | unwind_query = { }
unwind_query [ '$unwind' ] = path if path [ 0 ] == '$' else '$' + path
if include_array_index :
unwind_query [ 'includeArrayIndex' ] = include_array_index
if preserve_null_and_empty_arrays :
unwind_query [ 'preserveNullAndEmptyArrays' ] = True
self . _q . append ( unwind_query )
return self |
def save ( self ) :
"""Saves current cursor position , so that it can be restored later""" | self . write ( self . term . save )
self . _saved = True |
def add_cron ( self , client , event , seconds = "*" , minutes = "*" , hours = "*" ) :
"""Add a cron entry .
The arguments for this event are :
1 . The name of the event to dispatch when the cron fires .
2 . What seconds to trigger on , as a timespec ( default " * " )
3 . What minutes to trigger on , as a t... | for cron in self . crons :
if cron . event == event :
_log . warning ( "Cron '%s' is already registered." , event )
return True
_log . info ( "Registering cron for '%s'." , event )
cron = Cron ( event , seconds , minutes , hours )
self . crons . append ( cron )
return True |
def get_access_token ( self , request , callback = None ) :
"""Fetch access token from callback request .""" | callback = request . build_absolute_uri ( callback or request . path )
if not self . check_application_state ( request ) :
logger . error ( 'Application state check failed.' )
return None
if 'code' in request . GET :
args = { 'client_id' : self . consumer_key , 'redirect_uri' : callback , 'client_secret' : ... |
def _is_normal_karyotype ( karyotype ) :
"""This will default to true if no karyotype is provided .
This is assuming human karyotypes .
: param karyotype :
: return :""" | is_normal = True
if karyotype is not None :
karyotype = karyotype . strip ( )
if karyotype not in [ '46;XX' , '46;XY' , '' ] :
is_normal = False
return is_normal |
def find_items ( self , q , shape = ID_ONLY , depth = SHALLOW , additional_fields = None , order_fields = None , calendar_view = None , page_size = None , max_items = None , offset = 0 ) :
"""Private method to call the FindItem service
: param q : a Q instance containing any restrictions
: param shape : control... | if shape not in SHAPE_CHOICES :
raise ValueError ( "'shape' %s must be one of %s" % ( shape , SHAPE_CHOICES ) )
if depth not in ITEM_TRAVERSAL_CHOICES :
raise ValueError ( "'depth' %s must be one of %s" % ( depth , ITEM_TRAVERSAL_CHOICES ) )
if not self . folders :
log . debug ( 'Folder list is empty' )
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.