signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def determine_pool_size ( job_vector ) :
"""This function determines how large of a pool to make based on the
system resources currently available and how many jobs there are
to complete .""" | available_threads = cpu_count ( )
total_jobs = len ( job_vector )
threads_to_pass = total_jobs
if total_jobs >= available_threads :
threads_to_pass = available_threads
if threads_to_pass > 90 :
threads_to_pass = 90
print ( "There are {} threads available.\nThere are {} jobs:\nMaking a pool with {} threads" . fo... |
def add_capture_interface ( self , interface_id , logical_interface_ref , inspect_unspecified_vlans = True , zone_ref = None , comment = None ) :
"""Add a capture interface . Capture interfaces are supported on
Layer 2 FW and IPS engines .
. . note : :
Capture interface are supported on Layer 3 FW / clusters ... | capture = { 'interface_id' : interface_id , 'interface' : 'capture_interface' , 'logical_interface_ref' : logical_interface_ref , 'inspect_unspecified_vlans' : inspect_unspecified_vlans , 'zone_ref' : zone_ref , 'comment' : comment }
interface = Layer2PhysicalInterface ( engine = self . _engine , ** capture )
return se... |
def reset ( self ) :
"""Clear the active cells .""" | self . activePhases = np . empty ( ( 0 , 2 ) , dtype = "float" )
self . phaseDisplacement = np . empty ( ( 0 , 2 ) , dtype = "float" )
self . cellsForActivePhases = np . empty ( 0 , dtype = "int" )
self . activeCells = np . empty ( 0 , dtype = "int" )
self . sensoryAssociatedCells = np . empty ( 0 , dtype = "int" ) |
def write_terminator ( buff , capacity , ver , length ) :
"""Writes the terminator .
: param buff : The byte buffer .
: param capacity : Symbol capacity .
: param ver : ` ` None ` ` if a QR Code is written , " M1 " , " M2 " , " M3 " , or " M4 " if a
Micro QR Code is written .
: param length : Length of th... | # ISO / IEC 18004:2015 - - 7.4.9 Terminator ( page 32)
buff . extend ( [ 0 ] * min ( capacity - length , consts . TERMINATOR_LENGTH [ ver ] ) ) |
def parse ( cls , fptr , offset , length ) :
"""Parse palette box .
Parameters
fptr : file
Open file object .
offset : int
Start position of box in bytes .
length : int
Length of the box in bytes .
Returns
PaletteBox
Instance of the current palette box .""" | num_bytes = offset + length - fptr . tell ( )
read_buffer = fptr . read ( num_bytes )
nrows , ncols = struct . unpack_from ( '>HB' , read_buffer , offset = 0 )
bps_signed = struct . unpack_from ( '>' + 'B' * ncols , read_buffer , offset = 3 )
bps = [ ( ( x & 0x7f ) + 1 ) for x in bps_signed ]
signed = [ ( ( x & 0x80 ) ... |
def emit ( self , record ) :
"""Emits a record . The record is sent carefully , according to the following rules , to ensure that data is not
lost by exceeding the MTU of the connection .
- If the byte - encoded record length plus prefix length plus suffix length plus priority length is less than the
maximum ... | # noinspection PyBroadException
try :
formatted_message = self . format ( record )
encoded_message = formatted_message . encode ( 'utf-8' )
prefix = suffix = b''
if getattr ( self , 'ident' , False ) :
prefix = self . ident . encode ( 'utf-8' ) if isinstance ( self . ident , six . text_type ) el... |
def post_config_hook ( self ) :
"""Format of total , up and down placeholders under FORMAT .
As default , substitutes left _ align and precision as % s and % s
Placeholders :
value - value ( float )
unit - unit ( string )""" | if not self . py3 . check_commands ( "vnstat" ) :
raise Exception ( STRING_NOT_INSTALLED )
elif self . statistics_type not in [ "d" , "m" ] :
raise Exception ( STRING_INVALID_TYPE )
self . slice = slice ( * ( 3 , 6 ) if self . statistics_type == "d" else ( 8 , 11 ) )
self . value_format = "{value:%s.%sf} {unit}... |
def output_to_trivialgraph ( file , namer = _trivialgraph_default_namer , block = None ) :
"""Walk the block and output it in trivial graph format to the open file .""" | graph = net_graph ( block )
node_index_map = { }
# map node - > index
# print the list of nodes
for index , node in enumerate ( graph ) :
print ( '%d %s' % ( index , namer ( node , is_edge = False ) ) , file = file )
node_index_map [ node ] = index
print ( '#' , file = file )
# print the list of edges
for _from... |
def angle ( self , value ) :
"""gets / sets the angle""" | if self . _angle != value and isinstance ( value , ( int , float , long ) ) :
self . _angle = value |
def _callRestartAgent ( self , ev_data : RestartLogData , failTimeout ) -> None :
"""Callback which is called when restart time come .
Writes restart record to restart log and asks
node control service to perform restart
: param ev _ data : restart event data
: param version : version to restart to""" | logger . info ( "{}'s restart calling agent for restart" . format ( self ) )
self . _actionLog . append_started ( ev_data )
self . _action_start_callback ( )
self . scheduledAction = None
asyncio . ensure_future ( self . _sendUpdateRequest ( ev_data , failTimeout ) ) |
def expires ( self ) :
"""The date and time after which the certificate will be considered invalid .""" | not_after = self . _cert . get_notAfter ( ) . decode ( 'ascii' )
return datetime . datetime . strptime ( not_after , '%Y%m%d%H%M%SZ' ) . replace ( tzinfo = datetime . timezone . utc ) |
def run ( self ) :
"""Append version number to vegas / _ _ init _ _ . py""" | with open ( 'src/vegas/__init__.py' , 'a' ) as vfile :
vfile . write ( "\n__version__ = '%s'\n" % VEGAS_VERSION )
_build_py . run ( self ) |
def UpdateNumberOfEvents ( self , number_of_consumed_events , number_of_produced_events ) :
"""Updates the number of events .
Args :
number _ of _ consumed _ events ( int ) : total number of events consumed by
the process .
number _ of _ produced _ events ( int ) : total number of events produced by
the p... | consumed_events_delta = 0
if number_of_consumed_events is not None :
if number_of_consumed_events < self . number_of_consumed_events :
raise ValueError ( 'Number of consumed events smaller than previous update.' )
consumed_events_delta = ( number_of_consumed_events - self . number_of_consumed_events )
... |
def exclude_by_filter ( self , filename , module_name ) :
''': return : True if it should be excluded , False if it should be included and None
if no rule matched the given file .''' | for exclude_filter in self . _exclude_filters : # : : type exclude _ filter : ExcludeFilter
if exclude_filter . is_path :
if glob_matches_path ( filename , exclude_filter . name ) :
if exclude_filter . exclude :
pydev_log . debug ( "File %s ignored by filter %s" % ( filename , ex... |
def get_apphook_configs ( obj ) :
"""Get apphook configs for an object obj
: param obj : any model instance
: return : list of apphook configs for given obj""" | keys = get_apphook_field_names ( obj )
return [ getattr ( obj , key ) for key in keys ] if keys else [ ] |
def filter_users_by_email ( email ) :
"""Return list of users by email address
Typically one , at most just a few in length . First we look through
EmailAddress table , than customisable User model table . Add results
together avoiding SQL joins and deduplicate .""" | from . models import EmailAddress
User = get_user_model ( )
mails = EmailAddress . objects . filter ( email__iexact = email )
users = [ e . user for e in mails . prefetch_related ( 'user' ) ]
if app_settings . USER_MODEL_EMAIL_FIELD :
q_dict = { app_settings . USER_MODEL_EMAIL_FIELD + '__iexact' : email }
users... |
def _gen_msg ( vevent , label , tail , sep ) :
"""Generate a Remind MSG from the given vevent .
Opposite of _ gen _ description ( )""" | rem = [ 'MSG' ]
msg = [ ]
if label :
msg . append ( label )
if hasattr ( vevent , 'summary' ) and vevent . summary . value :
msg . append ( Remind . _rem_clean ( vevent . summary . value ) )
else :
msg . append ( 'empty reminder' )
if hasattr ( vevent , 'location' ) and vevent . location . value :
msg .... |
def await_reply ( self , msg_id , timeout = None ) :
"""Continuously poll the kernel ' shell ' stream for messages until :
- It receives an ' execute _ reply ' status for the given message id
- The timeout is reached awaiting a message , in which case
a ` Queue . Empty ` exception will be raised .""" | while True :
msg = self . get_message ( stream = 'shell' , timeout = timeout )
# Is this the message we are waiting for ?
if msg [ 'parent_header' ] . get ( 'msg_id' ) == msg_id :
if msg [ 'content' ] [ 'status' ] == 'aborted' : # This should not occur !
raise RuntimeError ( 'Kernel abor... |
def check_shutdown_flag ( self ) :
"""Shutdown the server if the flag has been set""" | if self . shutdown_requested :
tornado . ioloop . IOLoop . instance ( ) . stop ( )
print ( "web server stopped." ) |
def add_defs ( self , variable , locations , size_threshold = 32 ) :
"""Add a collection of new definitions of a variable .
: param SimVariable variable : The variable being defined .
: param iterable locations : A collection of locations where the variable was defined .
: param int size _ threshold : The max... | new_defs_added = False
for loc in locations :
new_defs_added |= self . add_def ( variable , loc , size_threshold = size_threshold )
return new_defs_added |
def _stage2_bootstrap ( ) :
"""This is the second bootstrap stage . It should be called
_ immediately _ after importing this module the first time . The
reason behind this process is to allow this module to be inserted
as a replacement for ' couchbase . _ libcouchbase ' while not loading
dependencies which ... | from couchbase_ffi . result import ( Item , Result , ObserveInfo , MultiResult , ValueResult , OperationResult , HttpResult , AsyncResult )
from couchbase_ffi . n1ql import _N1QLParams
globals ( ) . update ( locals ( ) )
from couchbase_ffi . bucket import Bucket
globals ( ) [ 'Bucket' ] = Bucket
from couchbase import _... |
def to_wire ( self , origin = None , max_size = 65535 ) :
"""Return a string containing the update in DNS compressed wire
format .
@ rtype : string""" | if origin is None :
origin = self . origin
return super ( Update , self ) . to_wire ( origin , max_size ) |
def p_static_member ( p ) :
'''static _ member : class _ name DOUBLE _ COLON variable _ without _ objects
| variable _ class _ name DOUBLE _ COLON variable _ without _ objects''' | p [ 0 ] = ast . StaticProperty ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 2 ) ) |
def _reset_corpus_iterator ( self ) :
"""create an iterator over all documents in the file ( i . e . all
< text > elements ) .
Once you have iterated over all documents , call this method again
if you want to iterate over them again .""" | self . __context = etree . iterparse ( self . urml_file , events = ( 'end' , ) , tag = 'document' , recover = False ) |
def from_jd ( jd ) :
'''Calculate Mayan long count from Julian day''' | d = jd - EPOCH
baktun = trunc ( d / 144000 )
d = ( d % 144000 )
katun = trunc ( d / 7200 )
d = ( d % 7200 )
tun = trunc ( d / 360 )
d = ( d % 360 )
uinal = trunc ( d / 20 )
kin = int ( ( d % 20 ) )
return ( baktun , katun , tun , uinal , kin ) |
def close ( self ) :
"""Close and remove hooks .""" | if not self . closed :
self . _ipython . events . unregister ( 'post_run_cell' , self . _fill )
self . _box . close ( )
self . closed = True |
def relaxNGNewMemParserCtxt ( buffer , size ) :
"""Create an XML RelaxNGs parse context for that memory buffer
expected to contain an XML RelaxNGs file .""" | ret = libxml2mod . xmlRelaxNGNewMemParserCtxt ( buffer , size )
if ret is None :
raise parserError ( 'xmlRelaxNGNewMemParserCtxt() failed' )
return relaxNgParserCtxt ( _obj = ret ) |
def run ( self ) :
"""Run find _ route _ functions _ taint _ args on each CFG .""" | function_cfgs = list ( )
for _ in self . cfg_list :
function_cfgs . extend ( self . find_route_functions_taint_args ( ) )
self . cfg_list . extend ( function_cfgs ) |
def _getFromDt ( self ) :
"""Get the datetime of the next event after or before now .""" | myNow = timezone . localtime ( timezone = self . tz )
return self . __after ( myNow ) or self . __before ( myNow ) |
def get_magsymops ( self , data ) :
"""Equivalent to get _ symops except for magnetic symmetry groups .
Separate function since additional operation for time reversal symmetry
( which changes magnetic moments on sites ) needs to be returned .""" | magsymmops = [ ]
# check to see if magCIF file explicitly contains magnetic symmetry operations
if data . data . get ( "_space_group_symop_magn_operation.xyz" ) :
xyzt = data . data . get ( "_space_group_symop_magn_operation.xyz" )
if isinstance ( xyzt , str ) :
xyzt = [ xyzt ]
magsymmops = [ MagSym... |
def unpack_rgb ( data , dtype = None , bitspersample = None , rescale = True ) :
"""Return array from byte string containing packed samples .
Use to unpack RGB565 or RGB555 to RGB888 format .
Parameters
data : byte str
The data to be decoded . Samples in each pixel are stored consecutively .
Pixels are al... | if bitspersample is None :
bitspersample = ( 5 , 6 , 5 )
if dtype is None :
dtype = '<B'
dtype = numpy . dtype ( dtype )
bits = int ( numpy . sum ( bitspersample ) )
if not ( bits <= 32 and all ( i <= dtype . itemsize * 8 for i in bitspersample ) ) :
raise ValueError ( 'sample size not supported: %s' % str ... |
def changelog ( self , api_version , doc ) :
"""Add a changelog entry for this api .""" | doc = textwrap . dedent ( doc ) . strip ( )
self . _changelog [ api_version ] = doc
self . _changelog_locations [ api_version ] = get_callsite_location ( ) |
def cluster_template_events ( self , tcolumn , column , window_size ) :
"""Cluster the internal events over the named column""" | cvec = self . template_events [ column ]
tvec = self . template_events [ tcolumn ]
if window_size == 0 :
indices = numpy . arange ( len ( tvec ) )
else :
indices = findchirp_cluster_over_window ( tvec , cvec , window_size )
self . template_events = numpy . take ( self . template_events , indices ) |
def get_tight_bbox ( fig , bbox_extra_artists = [ ] , pad = None ) :
"""Compute a tight bounding box around all the artists in the figure .""" | renderer = fig . canvas . get_renderer ( )
bbox_inches = fig . get_tightbbox ( renderer )
bbox_artists = bbox_extra_artists [ : ]
bbox_artists += fig . get_default_bbox_extra_artists ( )
bbox_filtered = [ ]
for a in bbox_artists :
bbox = a . get_window_extent ( renderer )
if isinstance ( bbox , tuple ) :
... |
def get ( cls , api = None , ** kwargs ) :
"""Get api links .
: param api : Api instance .
: return : Endpoints object .""" | api = api if api else cls . _API
extra = { 'resource' : cls . __name__ , 'query' : { } }
logger . info ( 'Getting resources' , extra = extra )
endpoints = api . get ( url = cls . _URL [ 'get' ] ) . json ( )
return Endpoints ( api = api , ** endpoints ) |
def read_properties ( self ) :
"""Populate this object by reading
the audio properties of the file at the given path .
Currently this function uses
: class : ` ~ aeneas . ffprobewrapper . FFPROBEWrapper `
to get the audio file properties .
: raises : : class : ` ~ aeneas . audiofile . AudioFileProbeError ... | self . log ( u"Reading properties..." )
# check the file can be read
if not gf . file_can_be_read ( self . file_path ) :
self . log_exc ( u"File '%s' cannot be read" % ( self . file_path ) , None , True , OSError )
# get the file size
self . log ( [ u"Getting file size for '%s'" , self . file_path ] )
self . file_s... |
def stream_query ( self , commands ) :
"""A generator of watchman events that allows queries to be pipelined and multiplexed . This
continuously yields unilateral events and subscribe events , or None until an error condition
or non - unilateral event ( aside from subscribe ) is received , at which point the ge... | # The CLI transport does not support pipelining .
if self . transport is pywatchman . CLIProcessTransport :
raise NotImplementedError ( )
cmd_buf = deque ( command for command in reversed ( commands ) )
self . _connect ( )
while 1 : # Interleave sends and receives to avoid bi - directional communication issues .
... |
def get_median_area ( self , mag , rake ) :
"""Calculates median fault area from magnitude .""" | if rake is None : # Return average of strike - slip and dip - slip curves
return power ( 10.0 , ( mag - 4.185 ) )
elif ( - 45 <= rake <= 45 ) or ( rake >= 135 ) or ( rake <= - 135 ) : # strike - slip
return power ( 10.0 , ( mag - 4.18 ) )
else : # Dip - slip ( thrust or normal ) , and undefined rake
return ... |
def download_file ( url , suffix = '' ) :
"""Download attached file as temporary file .
Parameters
url : string
SCO - API download Url
suffix : string , optional
If suffix is specified , the name of the downloaded file will end with
that suffix , otherwise there will be no suffix .
Returns
string , ... | r = urllib2 . urlopen ( url )
# Save attached file in temp file and return path to temp file
fd , f_path = tempfile . mkstemp ( suffix = suffix )
os . write ( fd , r . read ( ) )
os . close ( fd )
return f_path , suffix |
def stream ( self , filter_by = list ( ) , * args , ** kwargs ) :
"""Yield a stream of blocks
: param array filter _ by : List of operations to filter for , e . g .
vote , comment , transfer , transfer _ to _ vesting ,
withdraw _ vesting , limit _ order _ create , limit _ order _ cancel ,
feed _ publish , c... | if isinstance ( filter_by , str ) :
filter_by = [ filter_by ]
for event in self . ops ( * args , ** kwargs ) :
op_type , op = event [ 'op' ]
if not filter_by or op_type in filter_by :
yield { ** op , "type" : op_type , "timestamp" : parse_time ( event . get ( "timestamp" ) ) , "block_num" : event . ... |
def sign ( self , data ) :
"""Create url - safe signed token .
: param data : Data to sign
: type data : object""" | try :
jsonstr = json . dumps ( data , separators = ( ',' , ':' ) )
except TypeError as e :
raise DataSignError ( e . args [ 0 ] )
else :
signature = self . _create_signature ( jsonstr )
return self . _b64encode ( jsonstr + '.' + signature ) |
def pad ( self , file , size = 6 ) :
"""Group together as many records as possible to fit in the specified size
This SingleRecordStrategy will not group any record and will return them one by one as
long as they are within the maximum size .
Args :
file ( str ) : file path to read the records from .
size ... | for element in self . splitter . split ( file ) :
if _validate_payload_size ( element , size ) :
yield element |
def accel ( q : np . ndarray ) :
"""Compute the gravitational accelerations in the system
q in row vector of 6 elements : sun ( x , y , z ) , earth ( x , y , z )""" | # Infer number of dimensions from q
dims : int = len ( q )
# Initialize acceleration as dimsx1 array
a : np . ndarray = np . zeros ( dims )
# Iterate over each distinct pair of bodies
for i in range ( B ) :
for j in range ( i + 1 , B ) : # Masses of body i and j
m0 = mass [ i ]
m1 = mass [ j ]
... |
def _copyright_end_of_headerblock ( relative_path , contents , linter_options ) :
"""Check for copyright notice at end of headerblock .""" | del relative_path
del linter_options
lineno = _find_last_line_index ( contents )
notice = "See /LICENCE.md for Copyright information"
regex = re . compile ( r"^{0} {1}( .*$|$)" . format ( _MDL_COMMENT , notice ) )
if not regex . match ( contents [ lineno ] ) :
description = ( """The last of the header block line mu... |
def remove_too_short ( utterances : List [ Utterance ] , _winlen = 25 , winstep = 10 ) -> List [ Utterance ] :
"""Removes utterances that will probably have issues with CTC because of
the number of frames being less than the number of tokens in the
transcription . Assuming char tokenization to minimize false ne... | def is_too_short ( utterance : Utterance ) -> bool :
charlen = len ( utterance . text )
if ( duration ( utterance ) / winstep ) < charlen :
return True
else :
return False
return [ utter for utter in utterances if not is_too_short ( utter ) ] |
def iter_ruptures ( self ) :
"""Yield ruptures for the current set of indices""" | assert self . orig , '%s is not fully initialized' % self
for ridx in range ( self . start , self . stop ) :
if self . orig . rate [ ridx ] : # ruptures may have have zero rate
rup = self . get_ucerf_rupture ( ridx , self . src_filter )
if rup :
yield rup |
def load_all ( self ) :
'''Helper function for actual Insights client use''' | # check for custom conf file before loading conf
self . _load_command_line ( conf_only = True )
self . _load_config_file ( )
self . _load_env ( )
self . _load_command_line ( )
self . _imply_options ( )
self . _validate_options ( )
return self |
def single_registers ( op ) :
"""Given a list of registers like [ ' a ' , ' bc ' , ' h ' , ' hl ' ] returns
a set of single registers : [ ' a ' , ' b ' , ' c ' , ' h ' , ' l ' ] .
Non register parameters , like numbers will be ignored .""" | result = set ( )
if isinstance ( op , str ) :
op = [ op ]
for x in op :
if is_8bit_register ( x ) :
result = result . union ( [ x ] )
elif x == 'sp' :
result . add ( x )
elif x == 'af' :
result = result . union ( [ 'a' , 'f' ] )
elif x == "af'" :
result = result . uni... |
def frompil ( self , pillow_image ) :
"""Create a copy of a PIL . Image from this Pix""" | bio = BytesIO ( )
pillow_image . save ( bio , format = 'png' , compress_level = 1 )
py_buffer = bio . getbuffer ( )
c_buffer = ffi . from_buffer ( py_buffer )
with _LeptonicaErrorTrap ( ) :
pix = Pix ( lept . pixReadMem ( c_buffer , len ( c_buffer ) ) )
return pix |
def btc_is_singlesig ( privkey_info , ** blockchain_opts ) :
"""Does the given private key info represent
a single signature bundle ? ( i . e . one private key ) ?
i . e . is this key a private key string ?""" | try :
jsonschema . validate ( privkey_info , PRIVKEY_SINGLESIG_SCHEMA )
return True
except ValidationError as e :
return False |
def extendMarkdown ( self , md , md_globals ) :
"""Add InlineGraphvizPreprocessor to the Markdown instance .""" | md . registerExtension ( self )
md . preprocessors . add ( 'graphviz_block' , InlineGraphvizPreprocessor ( md ) , "_begin" ) |
def sort_children ( self , attribute = None , reverse_order = False ) :
"""Sorts the children using either the given attribute or the Node name .
: param attribute : Attribute name used for sorting .
: type attribute : unicode
: param reverse _ order : Sort in reverse order .
: type reverse _ order : bool
... | sorted_children = [ ]
if attribute :
sortable_children = [ ]
unsortable_children = [ ]
for child in self . __children :
if child . attribute_exists ( attribute ) :
sortable_children . append ( child )
else :
unsortable_children . append ( child )
sorted_children =... |
def name ( self ) :
"""The final path component , if any .""" | parts = self . _parts
if len ( parts ) == ( 1 if ( self . _drv or self . _root ) else 0 ) :
return ''
return parts [ - 1 ] |
def main ( ) :
"""NAME
curie . py
DESCTIPTION
plots and interprets curie temperature data .
the 1st derivative is calculated from smoothed M - T curve
( convolution with trianfular window with width = < - w > degrees )
the 2nd derivative is calculated from smoothed 1st derivative curve
( using the sam... | plot , fmt = 0 , 'svg'
if '-h' in sys . argv :
print ( main . __doc__ )
sys . exit ( )
if '-f' in sys . argv :
ind = sys . argv . index ( '-f' )
meas_file = sys . argv [ ind + 1 ]
else :
print ( "missing -f\n" )
sys . exit ( )
if '-w' in sys . argv :
ind = sys . argv . index ( '-w' )
win... |
def group2commlst ( commlst , glist ) :
"""add group info to commlst""" | for ( gname , objname ) , commitem in zip ( glist , commlst ) :
newitem1 = "group %s" % ( gname , )
newitem2 = "idfobj %s" % ( objname , )
commitem [ 0 ] . insert ( 0 , newitem1 )
commitem [ 0 ] . insert ( 1 , newitem2 )
return commlst |
def get_form ( self , form , name ) :
"""Get an instance of the form .""" | kwargs = self . get_kwargs ( form , name )
form_class = self . get_form_class ( form , name )
composite_form = form_class ( data = form . data if form . is_bound else None , files = form . files if form . is_bound else None , ** kwargs )
return composite_form |
def set ( self , mutagen_file , value ) :
"""Assign the value for the field using this style .""" | self . store ( mutagen_file , self . serialize ( value ) ) |
def leave ( self ) :
"""Leave the room .
Returns :
boolean : Leaving the room was successful .""" | try :
self . client . api . leave_room ( self . room_id )
del self . client . rooms [ self . room_id ]
return True
except MatrixRequestError :
return False |
def write_info_file ( tensorboard_info ) :
"""Write TensorBoardInfo to the current process ' s info file .
This should be called by ` main ` once the server is ready . When the
server shuts down , ` remove _ info _ file ` should be called .
Args :
tensorboard _ info : A valid ` TensorBoardInfo ` object .
... | payload = "%s\n" % _info_to_string ( tensorboard_info )
with open ( _get_info_file_path ( ) , "w" ) as outfile :
outfile . write ( payload ) |
def enable ( name , ** kwargs ) :
'''Enable the named service to start at boot
CLI Example :
. . code - block : : bash
salt ' * ' service . enable < service name >''' | cmd = '/usr/sbin/svcadm enable {0}' . format ( name )
return not __salt__ [ 'cmd.retcode' ] ( cmd , python_shell = False ) |
def save_to_file ( self , filename , remap_dim0 = None , remap_dim1 = None ) :
"""Saves matrix to the file .
Args :
filename : name of the file where to save matrix
remap _ dim0 : dictionary with mapping row indices to row names which should
be saved to file . If none then indices will be used as names .
... | # rows - first index
# columns - second index
with open ( filename , 'w' ) as fobj :
columns = list ( sorted ( self . _dim1 ) )
for col in columns :
fobj . write ( ',' )
fobj . write ( str ( remap_dim1 [ col ] if remap_dim1 else col ) )
fobj . write ( '\n' )
for row in sorted ( self . _d... |
def calculate_size ( name , batch_size ) :
"""Calculates the request payload size""" | data_size = 0
data_size += calculate_size_str ( name )
data_size += INT_SIZE_IN_BYTES
return data_size |
def listDatasets ( self , ** kwargs ) :
"""API to list dataset ( s ) in DBS
* You can use ANY combination of these parameters in this API
* In absence of parameters , all valid datasets known to the DBS instance will be returned
: param dataset : Full dataset ( path ) of the dataset
: type dataset : str
:... | validParameters = [ 'dataset' , 'parent_dataset' , 'is_dataset_valid' , 'release_version' , 'pset_hash' , 'app_name' , 'output_module_label' , 'processing_version' , 'acquisition_era_name' , 'run_num' , 'physics_group_name' , 'logical_file_name' , 'primary_ds_name' , 'primary_ds_type' , 'processed_ds_name' , 'data_tier... |
def next ( self , type = None ) :
"""Returns the next word in the sentence with the given type .""" | i = self . index + 1
s = self . sentence
while i < len ( s ) :
if type in ( s [ i ] . type , None ) :
return s [ i ]
i += 1 |
def filter_tuples ( list_of_tuples , length ) :
"""Function to filter out all tuples with a specific length from a list .
Examples :
filter _ tuples ( [ ( 4 , 5 ) , ( 4 , ) , ( 8 , 6 , 7 ) , ( 1 , ) , ( 3 , 4 , 6 , 7 ) ] , 1)
- > [ ( 4 , 5 ) , ( 8 , 6 , 7 ) , ( 3 , 4 , 6 , 7 ) ]
filter _ tuples ( [ ( 4 , 5 ... | result = [ t for t in list_of_tuples if len ( t ) != length ]
return result |
def points ( self ) :
"""returns a pointer to the points as a numpy object""" | x = vtk_to_numpy ( self . GetXCoordinates ( ) )
y = vtk_to_numpy ( self . GetYCoordinates ( ) )
z = vtk_to_numpy ( self . GetZCoordinates ( ) )
xx , yy , zz = np . meshgrid ( x , y , z , indexing = 'ij' )
return np . c_ [ xx . ravel ( ) , yy . ravel ( ) , zz . ravel ( ) ] |
def confirm_commit ( jid ) :
'''. . versionadded : : 2019.2.0
Confirm a commit scheduled to be reverted via the ` ` revert _ in ` ` and
` ` revert _ at ` ` arguments from the
: mod : ` net . load _ template < salt . modules . napalm _ network . load _ template > ` or
: mod : ` net . load _ config < salt . m... | if __grains__ [ 'os' ] == 'junos' : # Confirm the commit , by committing ( i . e . , invoking the RPC call )
confirmed = __salt__ [ 'napalm.junos_commit' ] ( )
confirmed [ 'result' ] = confirmed . pop ( 'out' )
confirmed [ 'comment' ] = confirmed . pop ( 'message' )
else :
confirmed = cancel_commit ( ji... |
def on_do_accept ( self , minor_planet_number , provisional_name , note1 , note2 , date_of_obs , ra , dec , obs_mag , obs_mag_err , band , observatory_code , comment ) :
"""After a source has been mark for acceptance create an MPC Observation record .
@ param minor _ planet _ number : The MPC Number associated wi... | # Just extract the character code from the notes , not the
# full description
note1_code = note1 . split ( " " ) [ 0 ]
note2_code = note2 . split ( " " ) [ 0 ]
self . view . close_accept_source_dialog ( )
self . model . set_current_source_name ( provisional_name )
source_cutout = self . model . get_current_cutout ( )
m... |
def remove_stale_sockets ( self ) :
"""Removes stale sockets then adds new ones if pool is too small .""" | if self . opts . max_idle_time_seconds is not None :
with self . lock :
while ( self . sockets and self . sockets [ - 1 ] . idle_time_seconds ( ) > self . opts . max_idle_time_seconds ) :
sock_info = self . sockets . pop ( )
sock_info . close ( )
while True :
with self . lock :
... |
def parse_with_toml ( data ) :
"""Uses TOML syntax to parse data""" | try :
return toml . loads ( "key={}" . format ( data ) , DynaBox ) . key
except toml . TomlDecodeError :
return data |
def get_user_credentials ( self ) :
"""Get user credentials with the login dialog .""" | password = None
token = None
( username , remember_me , remember_token ) = self . _get_credentials_from_settings ( )
valid_py_os = not ( PY2 and sys . platform . startswith ( 'linux' ) )
if username and remember_me and valid_py_os : # Get password from keyring
try :
password = keyring . get_password ( 'gith... |
def custom_handler ( self , glade , function_name , widget_name , str1 , str2 , int1 , int2 ) :
"""Generic handler for creating custom widgets , internally used to
enable custom widgets ( custom widgets of glade ) .
The custom widgets have a creation function specified in design time .
Those creation function... | try :
handler = getattr ( self , function_name )
return handler ( str1 , str2 , int1 , int2 )
except AttributeError :
return None |
def generate ( env ) :
"""Add Builders and construction variables for Visual Age C + + compilers
to an Environment .""" | import SCons . Tool
import SCons . Tool . cc
static_obj , shared_obj = SCons . Tool . createObjBuilders ( env )
for suffix in CXXSuffixes :
static_obj . add_action ( suffix , SCons . Defaults . CXXAction )
shared_obj . add_action ( suffix , SCons . Defaults . ShCXXAction )
static_obj . add_emitter ( suffix ... |
def is_metal ( self , efermi_tol = 1e-4 ) :
"""Check if the band structure indicates a metal by looking if the fermi
level crosses a band .
Returns :
True if a metal , False if not""" | for spin , values in self . bands . items ( ) :
for i in range ( self . nb_bands ) :
if np . any ( values [ i , : ] - self . efermi < - efermi_tol ) and np . any ( values [ i , : ] - self . efermi > efermi_tol ) :
return True
return False |
def applyconfiguration ( self , conf = None , paths = None , drivers = None , logger = None , targets = None , scope = None , safe = None , besteffort = None , callconf = False , keepstate = None , modules = None ) :
"""Apply conf on a destination in those phases :
1 . identify the right driver to use with paths ... | result = [ ]
self . loadmodules ( modules = modules )
modules = [ ]
if scope is None :
scope = self . scope
if safe is None :
safe = self . safe
if besteffort is None :
besteffort = self . besteffort
if targets is None :
targets = self . targets
if logger is None :
logger = self . logger
if keepstat... |
def get ( cls , tag_id_or_URI , label = None ) :
'''Return the tag with the given id or URI , or None .
: param tag _ id _ or _ name : the id or name of the tag to return
: type tag _ id _ or _ name : string
: returns : the tag object with the given id or name , or None if there is
no tag with that id or na... | # First try to get the tag by ID .
semantictag = SemanticTag . by_id ( tag_id_or_URI )
if semantictag :
return semantictag
else :
semantictag = SemanticTag . by_URI ( tag_id_or_URI )
return semantictag |
def _patch ( ) :
"""Monkey - patch pyopengl to fix a bug in glBufferSubData .""" | import sys
from OpenGL import GL
if sys . version_info > ( 3 , ) :
buffersubdatafunc = GL . glBufferSubData
if hasattr ( buffersubdatafunc , 'wrapperFunction' ) :
buffersubdatafunc = buffersubdatafunc . wrapperFunction
_m = sys . modules [ buffersubdatafunc . __module__ ]
_m . long = int
# Fix m... |
def plot_survival_function ( self , ** kwargs ) :
"""Alias of ` ` plot ` `""" | return _plot_estimate ( self , estimate = self . survival_function_ , confidence_intervals = self . confidence_interval_survival_function_ , ** kwargs ) |
def join ( self , target , key = None ) :
"""Attempt to join a channel .
The optional second argument is the channel key , if needed .""" | chantypes = self . server . features . get ( "CHANTYPES" , "#" )
if not target or target [ 0 ] not in chantypes : # Among other things , this prevents accidentally sending the
# " JOIN 0 " command which actually removes you from all channels
_log . warning ( "Refusing to join channel that does not start " "with one... |
def remove_seat ( self , seat_id ) :
"""Remove a seat from your team
: param seat _ id : Id of user""" | url = self . TEAM_SEATS_ID_URL % seat_id
connection = Connection ( self . token )
connection . set_url ( self . production , url )
return connection . delete_request ( ) |
def rename ( self , old , new ) :
"""Directory renaming support . Needed because many file managers create directories with default names , wich
makes it impossible to perform a search without CLI . Name changes for files are not allowed , only for
directories .
Parameters
old : str
Old name . Converted t... | new = self . __pathToTuple ( new )
if not self . __exists ( old ) :
raise FuseOSError ( errno . ENOENT )
if self . PathType . get ( old ) is not self . PathType . subdir or self . PathType . get ( new ) is not self . PathType . subdir :
raise FuseOSError ( errno . EPERM )
if self . __exists ( new ) :
raise ... |
def action_size ( self ) -> Sequence [ Shape ] :
'''Returns the MDP action size .''' | return self . _sizes ( self . _compiler . rddl . action_size ) |
def add_bindings ( self , g : Graph ) -> "PrefixLibrary" :
"""Add bindings in the library to the graph
: param g : graph to add prefixes to
: return : PrefixLibrary object""" | for prefix , namespace in self :
g . bind ( prefix . lower ( ) , namespace )
return self |
def registerWalkthrough ( self , walkthrough ) :
"""Registers the inputed walkthrough to the system .
: param walkthrough | < XWalkthrough >""" | if not walkthrough in self . _walkthroughs :
self . _walkthroughs . append ( walkthrough ) |
def main ( prog : str = None , subcommand_overrides : Dict [ str , Subcommand ] = { } ) -> None :
"""The : mod : ` ~ allennlp . run ` command only knows about the registered classes in the ` ` allennlp ` `
codebase . In particular , once you start creating your own ` ` Model ` ` s and so forth , it won ' t
work... | # pylint : disable = dangerous - default - value
parser = ArgumentParserWithDefaults ( description = "Run AllenNLP" , usage = '%(prog)s' , prog = prog )
parser . add_argument ( '--version' , action = 'version' , version = '%(prog)s ' + __version__ )
subparsers = parser . add_subparsers ( title = 'Commands' , metavar = ... |
def static ( type = 'artist' , artist_pick = 'song_hotttnesss-desc' , variety = .5 , artist_id = None , artist = None , song_id = None , track_id = None , description = None , style = None , mood = None , results = 15 , max_tempo = None , min_tempo = None , max_duration = None , min_duration = None , max_loudness = Non... | limit = str ( limit ) . lower ( )
if seed_catalog and isinstance ( seed_catalog , catalog . Catalog ) :
seed_catalog = seed_catalog . id
if source_catalog and isinstance ( source_catalog , catalog . Catalog ) :
source_catalog = source_catalog . id
dmca = str ( dmca ) . lower ( )
kwargs = locals ( )
kwargs [ 'bu... |
def render_field_error ( self , obj_id , obj , exception , request ) :
"""Default rendering for items in field where the the usual rendering
method raised an exception .""" | if obj is None :
msg = 'No match for ID={0}' . format ( obj_id )
else :
msg = unicode ( exception )
return u'<p class="error">{0}</p>' . format ( msg ) |
def post_error ( self , name , message ) :
"""Asynchronously post a user facing error message about a service .
Args :
name ( string ) : The name of the service
message ( string ) : The user facing error message that will be stored
for the service and can be queried later .""" | self . post_command ( OPERATIONS . CMD_POST_MESSAGE , _create_message ( name , states . ERROR_LEVEL , message ) ) |
def get_ethernet_settings ( self ) :
"""Gets the Ethernet interconnect settings for the Logical Interconnect .
Returns :
dict : Ethernet Interconnect Settings""" | uri = "{}/ethernetSettings" . format ( self . data [ "uri" ] )
return self . _helper . do_get ( uri ) |
def hicup_truncating_chart ( self ) :
"""Generate the HiCUP Truncated reads plot""" | # Specify the order of the different possible categories
keys = OrderedDict ( )
keys [ 'Not_Truncated_Reads' ] = { 'color' : '#2f7ed8' , 'name' : 'Not Truncated' }
keys [ 'Truncated_Read' ] = { 'color' : '#0d233a' , 'name' : 'Truncated' }
# Construct a data structure for the plot - duplicate the samples for read 1 and ... |
def GetVOffsetTSlot ( self , slot , d ) :
"""GetVOffsetTSlot retrieves the VOffsetT that the given vtable location
points to . If the vtable value is zero , the default value ` d `
will be returned .""" | N . enforce_number ( slot , N . VOffsetTFlags )
N . enforce_number ( d , N . VOffsetTFlags )
off = self . Offset ( slot )
if off == 0 :
return d
return off |
def unit ( self ) :
"""Return unit vector of a point .""" | s = self . x * self . x + self . y * self . y
if s < 1e-5 :
return Point ( 0 , 0 )
s = math . sqrt ( s )
return Point ( self . x / s , self . y / s ) |
def get_objective_hierarchy_session ( self , proxy ) :
"""Gets the session for traversing objective hierarchies .
: param proxy : a proxy
: type proxy : ` ` osid . proxy . Proxy ` `
: return : an ` ` ObjectiveHierarchySession ` `
: rtype : ` ` osid . learning . ObjectiveHierarchySession ` `
: raise : ` ` ... | if not self . supports_objective_hierarchy ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( )
proxy = self . _convert_proxy ( proxy )
try :
session = sessions . ObjectiveHierarchySession ( proxy = proxy , runtime = self . _runtime )
except Attribute... |
def git_push ( ) :
"""Push new version and corresponding tag to origin
: return :""" | # get current version
new_version = version . __version__
values = list ( map ( lambda x : int ( x ) , new_version . split ( '.' ) ) )
# Push to origin new version and corresponding tag :
# * commit new version
# * create tag
# * push version , tag to origin
local ( 'git add pynb/version.py version.py' )
local ( 'git c... |
def juldate2date ( val ) :
'''Convert from a Julian date / datetime to python date or datetime''' | ival = int ( val )
dec = val - ival
try :
val4 = 4 * ival
yd = val4 % 1461
st = 1899
if yd >= 4 :
st = 1900
yd1 = yd - 241
y = val4 // 1461 + st
if yd1 >= 0 :
q = yd1 // 4 * 5 + 308
qq = q // 153
qr = q % 153
else :
q = yd // 4 * 5 + 1833
q... |
def _CheckCollation ( cursor ) :
"""Checks MySQL collation and warns if misconfigured .""" | # Do not fail for wrong collation , because changing it is harder than changing
# the character set . Some providers only allow changing character set and then
# use the default collation . Also , misconfigured collation is not expected to
# have major negative impacts , since it only affects string sort order for
# so... |
def goassoc_fieldmap ( relationship_type = ACTS_UPSTREAM_OF_OR_WITHIN ) :
"""Returns a mapping of canonical monarch fields to amigo - golr .
See : https : / / github . com / geneontology / amigo / blob / master / metadata / ann - config . yaml""" | return { M . SUBJECT : 'bioentity' , M . SUBJECT_CLOSURE : 'bioentity' , # # In the GO AmiGO instance , the type field is not correctly populated
# # See above in the code for hack that restores this for planteome instance
# # M . SUBJECT _ CATEGORY : ' type ' ,
M . SUBJECT_CATEGORY : None , M . SUBJECT_LABEL : 'bioent... |
def field_pklist_to_json ( self , model , pks ) :
"""Convert a list of primary keys to a JSON dict .
This uses the same format as cached _ queryset _ to _ json""" | app_label = model . _meta . app_label
model_name = model . _meta . model_name
return { 'app' : app_label , 'model' : model_name , 'pks' : list ( pks ) , } |
def stream_realtime ( self , stream , value ) :
"""Stream a realtime value as an IndividualReadingReport .
If the streaming interface of the VirtualInterface this
VirtualDevice is attached to is not opened , the realtime
reading may be dropped .
Args :
stream ( int ) : The stream id to send
value ( int ... | if not self . stream_iface_open :
return
reading = IOTileReading ( 0 , stream , value )
report = IndividualReadingReport . FromReadings ( self . iotile_id , [ reading ] )
self . stream ( report ) |
def Any ( * validators ) :
"""Combines all the given validator callables into one , running the given
value through them in sequence until a valid result is given .""" | @ wraps ( Any )
def built ( value ) :
error = None
for validator in validators :
try :
return validator ( value )
except Error as e :
error = e
raise error
return built |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.