signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def register_on_guest_keyboard ( self , callback ) :
"""Set the callback function to consume on guest keyboard events
Callback receives a IGuestKeyboardEvent object .
Example :
def callback ( event ) :
print ( event . scancodes )""" | return self . event_source . register_callback ( callback , library . VBoxEventType . on_guest_keyboard ) |
def get_and_clear_context ( self ) :
"""Get and clean all of our broks , actions , external commands and homerun
: return : list of all broks of the satellite link
: rtype : list""" | res = ( self . broks , self . actions , self . wait_homerun , self . pushed_commands )
self . broks = [ ]
self . actions = { }
self . wait_homerun = { }
self . pushed_commands = [ ]
return res |
def _check_module_is_image_embedding ( module_spec ) :
"""Raises ValueError if ` module _ spec ` is not usable as image embedding .
Args :
module _ spec : A ` _ ModuleSpec ` to test .
Raises :
ValueError : if ` module _ spec ` default signature is not compatible with
mappingan " images " input to a Tensor... | issues = [ ]
# Find issues with " default " signature inputs . The common signatures for
# image models prescribe a specific name ; we trust it if we find it
# and if we can do the necessary inference of input shapes from it .
input_info_dict = module_spec . get_input_info_dict ( )
if ( list ( input_info_dict . keys ( ... |
def get_processing_block_ids ( self ) :
"""Get list of processing block ids using the processing block id""" | # Initialise empty list
_processing_block_ids = [ ]
# Pattern used to search processing block ids
pattern = '*:processing_block:*'
block_ids = self . _db . get_ids ( pattern )
for block_id in block_ids :
id_split = block_id . split ( ':' ) [ - 1 ]
_processing_block_ids . append ( id_split )
return sorted ( _pro... |
def has_credentials ( self ) :
"""Does this session have valid credentials
: rtype : bool""" | return all ( [ getattr ( self , '_%s' % field , None ) is not None for field in self . CredentialMap . get ( self . provider_name ) ] ) |
def save ( self , * args , ** kwargs ) :
"""when creating a new record fill CPU and RAM info if available""" | adding_new = False
if not self . pk or ( not self . cpu and not self . ram ) : # if self . model . cpu is not empty
if self . model . cpu :
self . cpu = self . model . cpu
# if self . model . ram is not empty
if self . model . ram :
self . ram = self . model . ram
# mark to add a new ant... |
def pca_ellipse ( data , loc = None , ax = None , ** ellipse_kwargs ) :
'''Finds the 2d PCA ellipse of given data and plots it .
loc : center of the ellipse [ default : mean of the data ]''' | from sklearn . decomposition import PCA
# Late import ; sklearn is optional
pca = PCA ( n_components = 2 ) . fit ( data )
if loc is None :
loc = pca . mean_
if ax is None :
ax = plt . gca ( )
cov = pca . explained_variance_ * pca . components_ . T
u , s , v = np . linalg . svd ( cov )
width , height = 2 * np . ... |
def partitioned_iterator ( self , partition_size , shuffle = True , seed = None ) :
"""Return a partitioning : class : ` audiomate . feeding . FrameIterator ` for the dataset .
Args :
partition _ size ( str ) : Size of the partitions in bytes . The units ` ` k ` ` ( kibibytes ) , ` ` m ` `
( mebibytes ) and `... | return iterator . FrameIterator ( self . utt_ids , self . containers , partition_size , shuffle = shuffle , seed = seed ) |
def check ( self ) :
"""Determine how long until the next scheduled time for a Task .
Returns the number of seconds until the next scheduled time or zero
if the task needs to be run immediately .
If it ' s an hourly task and it ' s never been run , run it now .
If it ' s a daily task and it ' s never been r... | boto . log . info ( 'checking Task[%s]-now=%s, last=%s' % ( self . name , self . now , self . last_executed ) )
if self . hourly and not self . last_executed :
return 0
if self . daily and not self . last_executed :
if int ( self . hour ) == self . now . hour :
return 0
else :
return max ( (... |
def percentile_between ( self , min_percentile , max_percentile , mask = NotSpecified ) :
"""Construct a new Filter representing entries from the output of this
Factor that fall within the percentile range defined by min _ percentile
and max _ percentile .
Parameters
min _ percentile : float [ 0.0 , 100.0] ... | return PercentileFilter ( self , min_percentile = min_percentile , max_percentile = max_percentile , mask = mask , ) |
def logEndTime ( ) :
"""Write end info to log""" | logger . info ( '\n' + '#' * 70 )
logger . info ( 'Complete' )
logger . info ( datetime . today ( ) . strftime ( "%A, %d %B %Y %I:%M%p" ) )
logger . info ( '#' * 70 + '\n' ) |
def _valid_packet ( raw_packet ) :
"""Validate incoming packet .""" | if raw_packet [ 0 : 1 ] != b'\xcc' :
return False
if len ( raw_packet ) != 19 :
return False
checksum = 0
for i in range ( 1 , 17 ) :
checksum += raw_packet [ i ]
if checksum != raw_packet [ 18 ] :
return False
return True |
def _get_label_encoder_and_max ( self , x ) :
"""Return a mapping from values and its maximum of a column to integer labels .
Args :
x ( pandas . Series ) : a categorical column to encode .
Returns :
label _ encoder ( dict ) : mapping from values of features to integers
max _ label ( int ) : maximum label... | # NaN cannot be used as a key for dict . So replace it with a random integer .
label_count = x . fillna ( NAN_INT ) . value_counts ( )
n_uniq = label_count . shape [ 0 ]
label_count = label_count [ label_count >= self . min_obs ]
n_uniq_new = label_count . shape [ 0 ]
# If every label appears more than min _ obs , new ... |
def from_pandas ( cls , index ) :
"""Create baloo Index from pandas Index .
Parameters
index : pandas . base . Index
Returns
Index""" | from pandas import Index as PandasIndex
check_type ( index , PandasIndex )
return Index ( index . values , index . dtype , index . name ) |
def _get_key_info ( self ) :
"""Get key info appropriate for signing .""" | if self . _key_info_cache is None :
self . _key_info_cache = agent_key_info_from_key_id ( self . key_id )
return self . _key_info_cache |
def _observe_keep_screen_on ( self , change ) :
"""Sets or clears the flag to keep the screen on .""" | def set_screen_on ( window ) :
from . android_window import Window
window = Window ( __id__ = window )
if self . keep_screen_on :
window . addFlags ( Window . FLAG_KEEP_SCREEN_ON )
else :
window . clearFlags ( Window . FLAG_KEEP_SCREEN_ON )
self . widget . getWindow ( ) . then ( set_scre... |
def open_if_exists ( filename , mode = 'rb' ) :
"""Returns a file descriptor for the filename if that file exists ,
otherwise ` None ` .""" | try :
return open ( filename , mode )
except IOError , e :
if e . errno not in ( errno . ENOENT , errno . EISDIR ) :
raise |
def get_rva_from_offset ( self , offset ) :
"""Get the RVA corresponding to this file offset .""" | s = self . get_section_by_offset ( offset )
if not s :
if self . sections :
lowest_rva = min ( [ adjust_SectionAlignment ( s . VirtualAddress , self . OPTIONAL_HEADER . SectionAlignment , self . OPTIONAL_HEADER . FileAlignment ) for s in self . sections ] )
if offset < lowest_rva : # We will assume ... |
def mode_yubikey_otp ( self , private_uid , aes_key ) :
"""Set the YubiKey up for standard OTP validation .""" | if not self . capabilities . have_yubico_OTP ( ) :
raise yubikey_base . YubiKeyVersionError ( 'Yubico OTP not available in %s version %d.%d' % ( self . capabilities . model , self . ykver [ 0 ] , self . ykver [ 1 ] ) )
if private_uid . startswith ( b'h:' ) :
private_uid = binascii . unhexlify ( private_uid [ 2 ... |
def calculate_normals ( vertices ) :
"""Return Nx3 normal array from Nx3 vertex array .""" | verts = np . array ( vertices , dtype = float )
normals = np . zeros_like ( verts )
for start , end in pairwise ( np . arange ( 0 , verts . shape [ 0 ] + 1 , 3 ) ) :
vecs = np . vstack ( ( verts [ start + 1 ] - verts [ start ] , verts [ start + 2 ] - verts [ start ] ) )
# Get triangle of vertices and calculate ... |
def generate_make_string ( out_f , max_step ) :
"""Generate the make _ string template""" | steps = [ 2 ** n for n in xrange ( int ( math . log ( max_step , 2 ) ) , - 1 , - 1 ) ]
with Namespace ( out_f , [ 'boost' , 'metaparse' , 'v{0}' . format ( VERSION ) , 'impl' ] ) as nsp :
generate_take ( out_f , steps , nsp . prefix ( ) )
out_f . write ( '{0}template <int LenNow, int LenRemaining, char... Cs>\n... |
def make_ndarray ( tensor ) :
"""Create a numpy ndarray from a tensor .
Create a numpy ndarray with the same shape and data as the tensor .
Args :
tensor : A TensorProto .
Returns :
A numpy array with the tensor contents .
Raises :
TypeError : if tensor has unsupported type .""" | shape = [ d . size for d in tensor . tensor_shape . dim ]
num_elements = np . prod ( shape , dtype = np . int64 )
tensor_dtype = dtypes . as_dtype ( tensor . dtype )
dtype = tensor_dtype . as_numpy_dtype
if tensor . tensor_content :
return np . frombuffer ( tensor . tensor_content , dtype = dtype ) . copy ( ) . res... |
def poll ( target , step , args = ( ) , kwargs = None , timeout = None , max_tries = None , check_success = is_truthy , step_function = step_constant , ignore_exceptions = ( ) , poll_forever = False , collect_values = None , * a , ** k ) :
"""Poll by calling a target function until a certain condition is met . You ... | assert ( timeout is not None or max_tries is not None ) or poll_forever , ( 'You did not specify a maximum number of tries or a timeout. Without either of these set, the polling ' 'function will poll forever. If this is the behavior you want, pass "poll_forever=True"' )
assert not ( ( timeout is not None or max_tries i... |
def visit_and_update ( self , visitor_fn ) :
"""Create an updated version ( if needed ) of BetweenClause via the visitor pattern .""" | new_lower_bound = self . lower_bound . visit_and_update ( visitor_fn )
new_upper_bound = self . upper_bound . visit_and_update ( visitor_fn )
if new_lower_bound is not self . lower_bound or new_upper_bound is not self . upper_bound :
return visitor_fn ( BetweenClause ( self . field , new_lower_bound , new_upper_bou... |
def get_channel ( self , name ) :
"""Get a channel by name . To get the names , use get _ channels .
: param string name : Name of channel to get
: returns dict conn : A channel attribute dictionary .""" | name = quote ( name , '' )
path = Client . urls [ 'channels_by_name' ] % name
chan = self . _call ( path , 'GET' )
return chan |
def relative_to ( self , * other ) :
"""Return the relative path to another path identified by the passed
arguments . If the operation is not possible ( because this is not
a subpath of the other path ) , raise ValueError .""" | # For the purpose of this method , drive and root are considered
# separate parts , i . e . :
# Path ( ' c : / ' ) . relative _ to ( ' c : ' ) gives Path ( ' / ' )
# Path ( ' c : / ' ) . relative _ to ( ' / ' ) raise ValueError
if not other :
raise TypeError ( "need at least one argument" )
parts = self . _parts
dr... |
def create_cloud_user ( cfg , args ) :
"""Attempt to create the user on the cloud node .""" | url = cfg [ 'api_server' ] + "admin/add-user"
params = { 'user_email' : args . user_email , 'user_name' : args . user_name , 'user_role' : args . user_role , 'email' : cfg [ 'email' ] , 'api_key' : cfg [ 'api_key' ] }
headers = { 'Content-Type' : 'application/json' }
response = requests . post ( url , data = json . dum... |
def fetch ( self , transfer_id , data = { } , ** kwargs ) :
"""Fetch Transfer for given Id
Args :
transfer _ id : Id for which transfer object has to be retrieved
Returns :
Transfer dict for given transfer Id""" | return super ( Transfer , self ) . fetch ( transfer_id , data , ** kwargs ) |
def set_keywords ( self , keywords ) :
"""Pass an array to filter the result by keywords .
: param keywords""" | self . _query_params += str ( QueryParam . KEYWORDS ) + '+' . join ( keywords ) |
def get_osds ( service , device_class = None ) :
"""Return a list of all Ceph Object Storage Daemons currently in the
cluster ( optionally filtered by storage device class ) .
: param device _ class : Class of storage device for OSD ' s
: type device _ class : str""" | luminous_or_later = cmp_pkgrevno ( 'ceph-common' , '12.0.0' ) >= 0
if luminous_or_later and device_class :
out = check_output ( [ 'ceph' , '--id' , service , 'osd' , 'crush' , 'class' , 'ls-osd' , device_class , '--format=json' ] )
else :
out = check_output ( [ 'ceph' , '--id' , service , 'osd' , 'ls' , '--form... |
def vertices ( self ) :
'''A dictionary of four points where the axes intersect the ellipse , dict .''' | return { 'a' : self . a , 'a_neg' : self . a_neg , 'b' : self . b , 'b_neg' : self . b_neg } |
def rot_rads ( self , rads ) :
"""Rotate vector by angle in radians .""" | new_x = self . x * math . cos ( rads ) - self . y * math . sin ( rads )
self . y = self . x * math . sin ( rads ) + self . y * math . cos ( rads )
self . x = new_x |
def set_position_target_local_ned_send ( self , time_boot_ms , target_system , target_component , coordinate_frame , type_mask , x , y , z , vx , vy , vz , afx , afy , afz , yaw , yaw_rate , force_mavlink1 = False ) :
'''Sets a desired vehicle position in a local north - east - down coordinate
frame . Used by an ... | return self . send ( self . set_position_target_local_ned_encode ( time_boot_ms , target_system , target_component , coordinate_frame , type_mask , x , y , z , vx , vy , vz , afx , afy , afz , yaw , yaw_rate ) , force_mavlink1 = force_mavlink1 ) |
def projection ( self , exprs ) :
"""Like mutate , but do not include existing table columns""" | w = self . _get_window ( )
windowed_exprs = [ ]
exprs = self . table . _resolve ( exprs )
for expr in exprs :
expr = L . windowize_function ( expr , w = w )
windowed_exprs . append ( expr )
return self . table . projection ( windowed_exprs ) |
def replace_negative_size_with_batch_size ( shape , batch_size ) :
"""Replace all dimensions with negative values to batch size""" | sl = [ ]
for d in shape . dim :
if d < 0 : # Negative size means batch size
sl . append ( batch_size )
else :
sl . append ( d )
out_shape = nnabla_pb2 . Shape ( )
out_shape . dim . extend ( sl )
return out_shape |
def deprecated_opts_signature ( args , kwargs ) :
"""Utility to help with the deprecation of the old . opts method signature
Returns whether opts . apply _ groups should be used ( as a bool ) and the
corresponding options .""" | from . options import Options
groups = set ( Options . _option_groups )
opts = { kw for kw in kwargs if kw != 'clone' }
apply_groups = False
options = None
new_kwargs = { }
if len ( args ) > 0 and isinstance ( args [ 0 ] , dict ) :
apply_groups = True
if ( not set ( args [ 0 ] ) . issubset ( groups ) and all ( ... |
def reduce_hierarchy ( x , depth ) :
"""Reduce the hierarchy ( depth by ` | ` ) string to the specified level""" | _x = x . split ( '|' )
depth = len ( _x ) + depth - 1 if depth < 0 else depth
return '|' . join ( _x [ 0 : ( depth + 1 ) ] ) |
def unique ( seq ) :
"""Return the unique values in a sequence .
Parameters
seq : sequence
Sequence with ( possibly duplicate ) elements .
Returns
unique : list
Unique elements of ` ` seq ` ` .
Order is guaranteed to be the same as in seq .
Examples
Determine unique elements in list
> > > unique... | # First check if all elements are hashable , if so O ( n ) can be done
try :
return list ( OrderedDict . fromkeys ( seq ) )
except TypeError : # Unhashable , resort to O ( n ^ 2)
unique_values = [ ]
for i in seq :
if i not in unique_values :
unique_values . append ( i )
return unique... |
def get_authorizations_ids_by_vault ( self , vault_ids ) :
"""Gets the list of ` ` Authorization Ids ` ` corresponding to a list of ` ` Vault ` ` objects .
arg : vault _ ids ( osid . id . IdList ) : list of vault ` ` Ids ` `
return : ( osid . id . IdList ) - list of authorization ` ` Ids ` `
raise : NullArgum... | # Implemented from template for
# osid . resource . ResourceBinSession . get _ resource _ ids _ by _ bin
id_list = [ ]
for authorization in self . get_authorizations_by_vault ( vault_ids ) :
id_list . append ( authorization . get_id ( ) )
return IdList ( id_list ) |
def generate_all_kmers ( k ) :
"""Generate all possible k - mers
Example :
> > > generate _ all _ kmers ( 2)
[ ' AA ' , ' AC ' , ' AG ' , ' AT ' , ' CA ' , ' CC ' , ' CG ' , ' CT ' , ' GA ' , ' GC ' , ' GG ' , ' GT ' , ' TA ' , ' TC ' , ' TG ' , ' TT ' ]""" | bases = [ 'A' , 'C' , 'G' , 'T' ]
return [ '' . join ( p ) for p in itertools . product ( bases , repeat = k ) ] |
def do_prune ( self ) :
"""Return True if prune _ table , prune _ column , and prune _ date are implemented .
If only a subset of prune variables are override , an exception is raised to remind the user to implement all or none .
Prune ( data newer than prune _ date deleted ) before copying new data in .""" | if self . prune_table and self . prune_column and self . prune_date :
return True
elif self . prune_table or self . prune_column or self . prune_date :
raise Exception ( 'override zero or all prune variables' )
else :
return False |
def row ( values , width = WIDTH , format_spec = FMT , align = ALIGN , style = STYLE ) :
"""Returns a formatted row of data
Parameters
values : array _ like
An iterable array of data ( numbers or strings ) , each value is printed in a separate column
width : int
The width of each column ( Default : 11)
... | tablestyle = STYLES [ style ]
widths = parse_width ( width , len ( values ) )
assert isinstance ( format_spec , string_types ) | isinstance ( format_spec , list ) , "format_spec must be a string or list of strings"
if isinstance ( format_spec , string_types ) :
format_spec = [ format_spec ] * len ( list ( values ) ... |
def do_cp ( self , line ) :
"""cp SOURCE DEST Copy a single SOURCE file to DEST file .
cp SOURCE . . . DIRECTORY Copy multiple SOURCE files to a directory .
cp [ - r | - - recursive ] [ SOURCE | SOURCE _ DIR ] . . . DIRECTORY
cp [ - r ] PATTERN DIRECTORY Copy matching files to DIRECTORY .
The destination mu... | args = self . line_to_args ( line )
if len ( args . filenames ) < 2 :
print_err ( 'Missing destination file' )
return
dst_dirname = resolve_path ( args . filenames [ - 1 ] )
dst_mode = auto ( get_mode , dst_dirname )
d_dst = { }
# Destination directory : lookup stat by basename
if args . recursive :
dst_fil... |
def get ( self , deviceId , measurementId ) :
"""details the specific measurement .""" | record = self . measurements . get ( deviceId )
if record is not None :
return record . get ( measurementId )
return None |
def face_normals ( self ) :
"""Return the unit normal vector for each face .
If a face is degenerate and a normal can ' t be generated
a zero magnitude unit vector will be returned for that face .
Returns
normals : ( len ( self . faces ) , 3 ) np . float64
Normal vectors of each face""" | # check shape of cached normals
cached = self . _cache [ 'face_normals' ]
if np . shape ( cached ) == np . shape ( self . _data [ 'faces' ] ) :
return cached
log . debug ( 'generating face normals' )
# use cached triangle cross products to generate normals
# this will always return the correct shape but some values... |
def heartbeat ( request ) :
"""Runs all the Django checks and returns a JsonResponse with either
a status code of 200 or 500 depending on the results of the checks .
Any check that returns a warning or worse ( error , critical ) will
return a 500 response .""" | all_checks = checks . registry . registry . get_checks ( include_deployment_checks = not settings . DEBUG , )
details = { }
statuses = { }
level = 0
for check in all_checks :
detail = heartbeat_check_detail ( check )
statuses [ check . __name__ ] = detail [ 'status' ]
level = max ( level , detail [ 'level' ... |
def get_overlays ( self , ** kw ) :
"""See Overlay . match ( ) for arguments .""" | return [ o for o in self . overlays if o . match ( ** kw ) ] |
def check_move ( new , old , t ) :
"""Determines if a model will be accepted .""" | if ( t <= 0 ) or numpy . isclose ( t , 0.0 ) :
return False
K_BOLTZ = 1.9872041E-003
# kcal / mol . K
if new < old :
return True
else :
move_prob = math . exp ( - ( new - old ) / ( K_BOLTZ * t ) )
if move_prob > random . uniform ( 0 , 1 ) :
return True
return False |
def write_element ( elem_to_parse , file_or_path , encoding = DEFAULT_ENCODING ) :
"""Writes the contents of the parsed element to file _ or _ path
: see : get _ element ( parent _ to _ parse , element _ path )""" | xml_header = '<?xml version="1.0" encoding="{0}"?>' . format ( encoding )
get_element_tree ( elem_to_parse ) . write ( file_or_path , encoding , xml_header ) |
def open ( self ) :
"""Open the URL with urllib . request .""" | url = self . url
try :
request = urllib . request . Request ( url )
handle = urllib . request . build_opener ( )
except IOError :
return None
return ( request , handle ) |
def to_text ( self ) :
"""Render a Table MessageElement as plain text .
: returns : The text representation of the Table MessageElement
: rtype : basestring""" | table = ''
if self . caption is not None :
table += '%s</caption>\n' % self . caption
table += '\n'
for row in self . rows :
table += row . to_text ( )
return table |
def set_computable_distance ( self , value ) :
'''setter''' | if isinstance ( value , ComputableDistance ) is False :
raise TypeError ( )
self . __computable_distance = value |
def CheckRegistryKey ( javaKey ) :
"""Method checks for the java in the registry entries .""" | from _winreg import ConnectRegistry , HKEY_LOCAL_MACHINE , OpenKey , QueryValueEx
path = None
try :
aReg = ConnectRegistry ( None , HKEY_LOCAL_MACHINE )
rk = OpenKey ( aReg , javaKey )
for i in range ( 1024 ) :
currentVersion = QueryValueEx ( rk , "CurrentVersion" )
if currentVersion != None... |
def packet_meta_data ( self ) :
"""Pull out the metadata about each packet from the input _ stream
Args :
None
Returns :
generator ( dictionary ) : a generator that contains packet meta data in the form of a dictionary""" | # For each packet in the pcap process the contents
for item in self . input_stream : # Output object
output = { }
# Grab the fields I need
timestamp = item [ 'timestamp' ]
buf = item [ 'raw_buf' ]
# Print out the timestamp in UTC
output [ 'timestamp' ] = datetime . datetime . utcfromtimestamp ( ... |
def match_entries ( entries , pattern ) :
"""A drop - in replacement for fnmatch . filter that supports pattern
variants ( ie . { foo , bar } baz = foobaz or barbaz ) .""" | matching = [ ]
for variant in expand_braces ( pattern ) :
matching . extend ( fnmatch . filter ( entries , variant ) )
return list ( _deduplicate ( matching ) ) |
def check_valence ( self ) :
"""check valences of all atoms
: return : list of invalid atoms""" | return [ x for x , atom in self . atoms ( ) if not atom . check_valence ( self . environment ( x ) ) ] |
def last_bookmark ( bookmarks ) :
"""The bookmark returned by the last : class : ` . Transaction ` .""" | last = None
for bookmark in bookmarks :
if last is None :
last = bookmark
else :
last = _last_bookmark ( last , bookmark )
return last |
def findConnectedDevices ( self ) :
"""Find all the devices on the serial buss and store the results in a
class member object .""" | tmpTimeout = self . _serial . timeout
self . _serial . timeout = 0.01
for dev in range ( 128 ) :
device = self . _getDeviceID ( dev )
if device is not None and int ( device ) not in self . _deviceConfig :
config = self . _deviceConfig . setdefault ( int ( device ) , { } )
self . _deviceCallback ... |
def U ( self ) :
"""Property to support lazy evaluation of residuals""" | if self . _U is None :
sinv = N . diag ( 1 / self . singular_values )
self . _U = dot ( self . arr , self . V . T , sinv )
return self . _U |
def add_arg ( self , arg ) :
"""Add an argument""" | if not isinstance ( arg , File ) :
arg = str ( arg )
self . _args += [ arg ] |
def _gen_explain_command ( coll , spec , projection , skip , limit , batch_size , options , read_concern ) :
"""Generate an explain command document .""" | cmd = _gen_find_command ( coll , spec , projection , skip , limit , batch_size , options )
if read_concern . level :
return SON ( [ ( 'explain' , cmd ) , ( 'readConcern' , read_concern . document ) ] )
return SON ( [ ( 'explain' , cmd ) ] ) |
def client ( host = 'localhost' , port = 2379 , ca_cert = None , cert_key = None , cert_cert = None , timeout = None , user = None , password = None , grpc_options = None ) :
"""Return an instance of an Etcd3Client .""" | return Etcd3Client ( host = host , port = port , ca_cert = ca_cert , cert_key = cert_key , cert_cert = cert_cert , timeout = timeout , user = user , password = password , grpc_options = grpc_options ) |
def nodes_simple_info ( self , params = { } , ** kwargs ) :
"""Return a dictionary of the nodes simple info that key is a column name ,
such as [ { " http _ address " : " 192.111.111.111 " , " name " : " test " , . . . } , . . . ]""" | h = [ 'name' , 'pid' , 'http_address' , 'version' , 'jdk' , 'disk.total' , 'disk.used_percent' , 'heap.current' , 'heap.percent' , 'ram.current' , 'ram.percent' , 'uptime' , 'node.role' ]
result = self . client . cat . nodes ( v = True , h = h , ** kwargs , params = params )
result = [ x . strip ( ) . split ( ' ' ) for... |
def clear_grade_system ( self ) :
"""Clears the grading system .
raise : NoAccess - ` ` Metadata . isRequired ( ) ` ` or
` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` `
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for osid . resource . ResourceForm . clear _ avatar _ template
if ( self . get_grade_system_metadata ( ) . is_read_only ( ) or self . get_grade_system_metadata ( ) . is_required ( ) ) :
raise errors . NoAccess ( )
self . _my_map [ 'gradeSystemId' ] = self . _grade_system_default |
def close ( self ) :
"""Collects the result from the workers and closes the thread pool .""" | self . pool . close ( )
self . pool . terminate ( )
self . pool . join ( ) |
def find_library_linux ( cls ) :
"""Loads the SEGGER DLL from the root directory .
On Linux , the SEGGER tools are installed under the ` ` / opt / SEGGER ` `
directory with versioned directories having the suffix ` ` _ VERSION ` ` .
Args :
cls ( Library ) : the ` ` Library ` ` class
Returns :
The paths ... | dll = Library . JLINK_SDK_NAME
root = os . path . join ( '/' , 'opt' , 'SEGGER' )
for ( directory_name , subdirs , files ) in os . walk ( root ) :
fnames = [ ]
x86_found = False
for f in files :
path = os . path . join ( directory_name , f )
if os . path . isfile ( path ) and f . startswith ... |
def report_ports ( target , ports ) :
"""portscan a target and output a LaTeX table
report _ ports ( target , ports ) - > string""" | ans , unans = sr ( IP ( dst = target ) / TCP ( dport = ports ) , timeout = 5 )
rep = "\\begin{tabular}{|r|l|l|}\n\\hline\n"
for s , r in ans :
if not r . haslayer ( ICMP ) :
if r . payload . flags == 0x12 :
rep += r . sprintf ( "%TCP.sport% & open & SA \\\\\n" )
rep += "\\hline\n"
for s , r in a... |
def set_params ( self , subs = None , numticks = None ) :
"""Set parameters within this locator .
Parameters
subs : array , optional
Subtick values , as multiples of the main ticks .
numticks : array , optional
Number of ticks .""" | if numticks is not None :
self . numticks = numticks
if subs is not None :
self . _subs = subs |
def json_conversion ( obj ) :
"""Encode additional objects to JSON .""" | try : # numpy isn ' t an explicit dependency of bowtie
# so we can ' t assume it ' s available
import numpy as np
if isinstance ( obj , ( np . ndarray , np . generic ) ) :
return obj . tolist ( )
except ImportError :
pass
try : # pandas isn ' t an explicit dependency of bowtie
# so we can ' t assume... |
def safe_filepath ( file_path_name , dir_sep = None ) :
'''Input the full path and filename , splits on directory separator and calls safe _ filename _ leaf for
each part of the path . dir _ sep allows coder to force a directory separate to a particular character
. . versionadded : : 2017.7.2
: codeauthor : D... | if not dir_sep :
dir_sep = os . sep
# Normally if file _ path _ name or dir _ sep is Unicode then the output will be Unicode
# This code ensure the output type is the same as file _ path _ name
if not isinstance ( file_path_name , six . text_type ) and isinstance ( dir_sep , six . text_type ) :
dir_sep = dir_se... |
async def dump_variant ( obj , elem , elem_type = None , params = None , field_archiver = None ) :
"""Transform variant to the popo object representation .
: param obj :
: param elem :
: param elem _ type :
: param params :
: param field _ archiver :
: return :""" | field_archiver = field_archiver if field_archiver else dump_field
if isinstance ( elem , x . VariantType ) or elem_type . WRAPS_VALUE :
return { elem . variant_elem : await field_archiver ( None , getattr ( elem , elem . variant_elem ) , elem . variant_elem_type ) }
else :
fdef = elem_type . find_fdef ( elem_ty... |
def process_pgturl ( self , params ) :
"""Handle PGT request
: param dict params : A template context dict
: raises ValidateError : if pgtUrl is invalid or if TLS validation of the pgtUrl fails
: return : The rendering of ` ` cas _ server / serviceValidate . xml ` ` , using ` ` params ` `
: rtype : django .... | try :
pattern = ServicePattern . validate ( self . pgt_url )
if pattern . proxy_callback :
proxyid = utils . gen_pgtiou ( )
pticket = ProxyGrantingTicket . objects . create ( user = self . ticket . user , service = self . pgt_url , service_pattern = pattern , single_log_out = pattern . single_lo... |
def toProtocolElement ( self ) :
"""Converts this rnaQuant into its GA4GH protocol equivalent .""" | protocolElement = protocol . RnaQuantificationSet ( )
protocolElement . id = self . getId ( )
protocolElement . dataset_id = self . _parentContainer . getId ( )
protocolElement . name = self . _name
self . serializeAttributes ( protocolElement )
return protocolElement |
def delete_group ( self , name ) :
"""Delete contact group
: param name : of group
: type name : ` ` str ` ` , ` ` unicode ` `
: rtype : ` ` bool ` `""" | group = self . get_group ( name )
method , url = get_URL ( 'group_delete' )
payload = { 'apikey' : self . config . get ( 'apikey' ) , 'logintoken' : self . session . cookies . get ( 'logintoken' ) , 'contactgroupid' : group [ 'contactgroupid' ] }
res = getattr ( self . session , method ) ( url , params = payload )
if r... |
def addSquigglyAnnot ( self , rect ) :
"""Wavy underline content in a rectangle or quadrilateral .""" | CheckParent ( self )
val = _fitz . Page_addSquigglyAnnot ( self , rect )
if not val :
return
val . thisown = True
val . parent = weakref . proxy ( self )
self . _annot_refs [ id ( val ) ] = val
return val |
def get_F1_EM ( dataset , predict_data ) :
"""Calculate the F1 and EM scores of the predicted results .
Use only with the SQuAD1.1 dataset .
Parameters
dataset _ file : string
Path to the data file .
predict _ data : dict
All final predictions .
Returns
scores : dict
F1 and EM scores .""" | f1 = exact_match = total = 0
for record in dataset :
total += 1
if record [ 1 ] not in predict_data :
message = 'Unanswered question ' + record [ 1 ] + ' will receive score 0.'
print ( message )
continue
ground_truths = record [ 4 ]
prediction = predict_data [ record [ 1 ] ]
... |
def get_archs ( libname ) :
"""Return architecture types from library ` libname `
Parameters
libname : str
filename of binary for which to return arch codes
Returns
arch _ names : frozenset
Empty ( frozen ) set if no arch codes . If not empty , contains one or more
of ' ppc ' , ' ppc64 ' , ' i386 ' , ... | if not exists ( libname ) :
raise RuntimeError ( libname + " is not a file" )
try :
stdout = back_tick ( [ 'lipo' , '-info' , libname ] )
except RuntimeError :
return frozenset ( )
lines = [ line . strip ( ) for line in stdout . split ( '\n' ) if line . strip ( ) ]
# For some reason , output from lipo - inf... |
def install ( self ) :
"""Install the generated config file .""" | outs = super ( MyInstallLib , self ) . install ( )
infile = self . create_conf_file ( )
outfile = os . path . join ( self . install_dir , os . path . basename ( infile ) )
self . copy_file ( infile , outfile )
outs . append ( outfile )
return outs |
def get_repo_parent ( path ) :
"""Returns parent repo or input path if none found .
: return : grit . Local or path""" | # path is a repository
if is_repo ( path ) :
return Local ( path )
# path is inside a repository
elif not os . path . isdir ( path ) :
_rel = ''
while path and path != '/' :
if is_repo ( path ) :
return Local ( path )
else :
_rel = os . path . join ( os . path . basen... |
def reset ( self ) :
'''Reset list of terms and y - variable .''' | self . terms = OrderedDict ( )
self . y = None
self . backend = None
self . added_terms = [ ]
self . _added_priors = { }
self . completes = [ ]
self . clean_data = None |
def calculate_digit_distance ( number1 , number2 ) :
"""A python function which calculates the digit distance between two numbers by
adding the digits of the absolute difference between the numbers .
Example usage :
calculate _ digit _ distance ( 1 , 2 ) - > 1
calculate _ digit _ distance ( 23 , 56 ) - > 6 ... | return sum ( int ( digit ) for digit in str ( abs ( number1 - number2 ) ) ) |
def set_all_pattern_variables ( self , patternnumber , sp0 , ti0 , sp1 , ti1 , sp2 , ti2 , sp3 , ti3 , sp4 , ti4 , sp5 , ti5 , sp6 , ti6 , sp7 , ti7 , actual_step , additional_cycles , link_pattern ) :
"""Set all variables for a given pattern at one time .
Args :
* patternnumber ( integer ) : 0-7
* sp [ * n *... | _checkPatternNumber ( patternnumber )
self . set_pattern_step_setpoint ( patternnumber , 0 , sp0 )
self . set_pattern_step_setpoint ( patternnumber , 1 , sp1 )
self . set_pattern_step_setpoint ( patternnumber , 2 , sp2 )
self . set_pattern_step_setpoint ( patternnumber , 3 , sp3 )
self . set_pattern_step_setpoint ( pat... |
def find_behind_subscriptions ( ) :
"""Finds any subscriptions that are behind according to where they should be ,
and creates a BehindSubscription entry for them .""" | subscriptions = Subscription . objects . filter ( active = True , completed = False , process_status = 0 ) . values_list ( "id" , flat = True )
for subscription_id in subscriptions . iterator ( ) :
calculate_subscription_lifecycle . delay ( str ( subscription_id ) ) |
def _gatherDataFromLookups ( gpos , scriptOrder ) :
"""Gather kerning and classes from the applicable lookups
and return them in script order .""" | lookupIndexes = _gatherLookupIndexes ( gpos )
seenLookups = set ( )
kerningDictionaries = [ ]
leftClassDictionaries = [ ]
rightClassDictionaries = [ ]
for script in scriptOrder :
kerning = [ ]
leftClasses = [ ]
rightClasses = [ ]
for lookupIndex in lookupIndexes [ script ] :
if lookupIndex in se... |
def constant_fold ( code , silent = True , ignore_errors = True ) :
"""Constant - folds simple expressions like 2 3 + to 5.
Args :
code : Code in non - native types .
silent : Flag that controls whether to print optimizations made .
ignore _ errors : Whether to raise exceptions on found errors .""" | # Loop until we haven ' t done any optimizations . E . g . , " 2 3 + 5 * " will be
# optimized to " 5 5 * " and in the next iteration to 25 . Yes , this is
# extremely slow , big - O wise . We ' ll fix that some other time . ( TODO )
arithmetic = list ( map ( instructions . lookup , [ instructions . add , instructions ... |
def setup ( self ) :
"""Collect watchdog information .
Collect configuration files , custom executables for test - binary
and repair - binary , and stdout / stderr logs .""" | conf_file = self . get_option ( 'conf_file' )
log_dir = '/var/log/watchdog'
# Get service configuration and sysconfig files
self . add_copy_spec ( [ conf_file , '/etc/sysconfig/watchdog' , ] )
# Get custom executables
self . add_copy_spec ( [ '/etc/watchdog.d' , '/usr/libexec/watchdog/scripts' , ] )
# Get logs
try :
... |
def make ( self ) :
"""Make the lock file .""" | try : # Create the lock file
self . mkfile ( self . lock_file )
except Exception as e :
self . die ( 'Failed to generate lock file: {}' . format ( str ( e ) ) ) |
def set_instrumentation_callback ( self , callback ) :
"""Assign a method to invoke when a request has completed gathering
measurements .
: param method callback : The method to invoke""" | self . logger . debug ( 'Setting instrumentation callback: %r' , callback )
self . _instrumentation_callback = callback |
def schema ( self ) :
"""The DQL syntax for creating this item""" | if self . key_type is None :
return "%s %s" % ( self . name , self . data_type )
else :
return "%s %s %s KEY" % ( self . name , self . data_type , self . key_type ) |
def execute ( self , input_data ) :
'''Okay this worker is going build graphs from PCAP Bro output logs''' | # Grab the Bro log handles from the input
bro_logs = input_data [ 'pcap_bro' ]
# Weird log
if 'weird_log' in bro_logs :
stream = self . workbench . stream_sample ( bro_logs [ 'weird_log' ] )
self . weird_log_graph ( stream )
# HTTP log
gsleep ( )
stream = self . workbench . stream_sample ( bro_logs [ 'http_log'... |
def generate_sub_codons_left ( codons_dict ) :
"""Generate the sub _ codons _ left dictionary of codon prefixes .
Parameters
codons _ dict : dict
Dictionary , keyed by the allowed ' amino acid ' symbols with the values
being lists of codons corresponding to the symbol .
Returns
sub _ codons _ left : dic... | sub_codons_left = { }
for aa in codons_dict . keys ( ) :
sub_codons_left [ aa ] = list ( set ( [ x [ 0 ] for x in codons_dict [ aa ] ] + [ x [ : 2 ] for x in codons_dict [ aa ] ] ) )
return sub_codons_left |
def initialize_from_string ( content : str ) -> 'HomusSymbol' :
"""Create and initializes a new symbol from a string
: param content : The content of a symbol as read from the text - file
: return : The initialized symbol
: rtype : HomusSymbol""" | if content is None or content is "" :
return None
lines = content . splitlines ( )
min_x = sys . maxsize
max_x = 0
min_y = sys . maxsize
max_y = 0
symbol_name = lines [ 0 ]
strokes = [ ]
for stroke_string in lines [ 1 : ] :
stroke = [ ]
for point_string in stroke_string . split ( ";" ) :
if point_st... |
def update ( self ) :
"""Calculate the smoothing parameter value .
The following example is explained in some detail in module
| smoothtools | :
> > > from hydpy . models . dam import *
> > > parameterstep ( )
> > > highestremotedischarge ( 1.0)
> > > highestremotetolerance ( 0.0)
> > > derived . high... | control = self . subpars . pars . control
if numpy . isinf ( control . highestremotedischarge ) :
self ( 0.0 )
else :
self ( control . highestremotedischarge * smoothtools . calc_smoothpar_min1 ( control . highestremotetolerance ) ) |
def broadcast_transaction ( hex_tx , blockchain_client ) :
"""Dispatches a raw hex transaction to the network .""" | if isinstance ( blockchain_client , BlockcypherClient ) :
return blockcypher . broadcast_transaction ( hex_tx , blockchain_client )
elif isinstance ( blockchain_client , BlockchainInfoClient ) :
return blockchain_info . broadcast_transaction ( hex_tx , blockchain_client )
elif isinstance ( blockchain_client , C... |
def call_use_cached_files ( tup ) :
"""Importable helper for multi - proc calling of ArtifactCache . use _ cached _ files on a cache instance .
Multiprocessing map / apply / etc require functions which can be imported , not bound methods .
To call a bound method , instead call a helper like this and pass tuple ... | try :
cache , key , results_dir = tup
res = cache . use_cached_files ( key , results_dir )
if res :
sys . stderr . write ( '.' )
else :
sys . stderr . write ( ' ' )
sys . stderr . flush ( )
return res
except NonfatalArtifactCacheError as e :
logger . warn ( 'Error calling use... |
def print_version ( ) :
"""Print get _ version ( ) return value in a readable format .
Params :
None
Returns :
None""" | v = get_version ( )
try :
s = _STR_WIN [ v ]
except KeyError :
s = "Unknow OS"
print ( "-----------------------------------------------------------" )
print ( "###################### WinVer Report ######################" )
print ( "Python Version : {}.{}.{}" . format ( * sys . version_... |
def prime_factors ( n ) :
"""Lists prime factors of a given natural integer , from greatest to smallest
: param n : Natural integer
: rtype : list of all prime factors of the given natural n""" | i = 2
while i <= sqrt ( n ) :
if n % i == 0 :
l = prime_factors ( n / i )
l . append ( i )
return l
i += 1
return [ n ] |
def create_proxy_zip ( proxy_string , proxy_user , proxy_pass ) :
"""Implementation of https : / / stackoverflow . com / a / 35293284 for
https : / / stackoverflow . com / questions / 12848327/
( Run Selenium on a proxy server that requires authentication . )
Solution involves creating & adding a Chrome exten... | proxy_host = proxy_string . split ( ':' ) [ 0 ]
proxy_port = proxy_string . split ( ':' ) [ 1 ]
background_js = ( """var config = {\n""" """ mode: "fixed_servers",\n""" """ rules: {\n""" """ singleProxy: {\n""" """ scheme: "http",\n""" """ host: "%s",\n""" """ port: parseInt("%s")\n""" "... |
def configs ( self , filters = None ) :
"""List configs
Args :
filters ( dict ) : A map of filters to process on the configs
list . Available filters : ` ` names ` `
Returns ( list ) : A list of configs""" | url = self . _url ( '/configs' )
params = { }
if filters :
params [ 'filters' ] = utils . convert_filters ( filters )
return self . _result ( self . _get ( url , params = params ) , True ) |
def system_monitor_LineCard_threshold_marginal_threshold ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
system_monitor = ET . SubElement ( config , "system-monitor" , xmlns = "urn:brocade.com:mgmt:brocade-system-monitor" )
LineCard = ET . SubElement ( system_monitor , "LineCard" )
threshold = ET . SubElement ( LineCard , "threshold" )
marginal_threshold = ET . SubElement ( threshold , "... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.