signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def pformat ( self ) :
"""Pretty string format""" | lines = [ ]
lines . append ( ( "%s (%s)" % ( self . name , self . status ) ) . center ( 50 , "-" ) )
lines . append ( "items: {0:,} ({1:,} bytes)" . format ( self . item_count , self . size ) )
cap = self . consumed_capacity . get ( "__table__" , { } )
read = "Read: " + format_throughput ( self . read_throughput , cap ... |
def assertDateTimesLagLessEqual ( self , sequence , lag , msg = None ) :
'''Fail if max element in ` ` sequence ` ` is separated from
the present by more than ` ` lag ` ` as determined by the ' < = '
operator .
If the max element is a datetime , " present " is defined as
` ` datetime . now ( ) ` ` ; if the ... | if not isinstance ( sequence , collections . Iterable ) :
raise TypeError ( 'First argument is not iterable' )
if not isinstance ( lag , timedelta ) :
raise TypeError ( 'Second argument is not a timedelta object' )
# Cannot compare datetime to date , so if dates are provided use
# date . today ( ) , if datetime... |
def override_colors ( self , colors ) :
"""Override default color of elements .
: param colors : New color value for given elements
: type colors : dict""" | if not isinstance ( colors , dict ) :
return
for key in self . _color [ True ] :
if key in colors :
self . _color [ True ] [ key ] = colors [ key ] |
def disconnect ( self , client ) :
"""Remove client from pool .""" | self . clients . remove ( client )
del self . connect_args [ client ]
client . disconnect ( ) |
def _a_pitch_kd_callback ( self , name , value ) :
"""Callback for pid _ attitude . pitch _ kd""" | print ( 'Readback: {0}={1}' . format ( name , value ) )
# End the example by closing the link ( will cause the app to quit )
self . _cf . close_link ( ) |
def load ( self , mdl_file ) :
"""load model from file . fv _ type is not set with this function . It is expected to set it before .""" | import dill as pickle
mdl_file_e = op . expanduser ( mdl_file )
sv = pickle . load ( open ( mdl_file_e , "rb" ) )
self . mdl = sv [ "mdl" ]
# self . mdl [ 2 ] = self . mdl [ 0]
# try :
# eval ( sv [ ' fv _ extern _ src ' ] )
# eval ( " fv _ extern _ temp _ name = " + sv [ ' fv _ extern _ src _ name ' ] )
# sv [ ' fv _ ... |
def append_update_buffer ( self , agent_id , key_list = None , batch_size = None , training_length = None ) :
"""Appends the buffer of an agent to the update buffer .
: param agent _ id : The id of the agent which data will be appended
: param key _ list : The fields that must be added . If None : all fields wi... | if key_list is None :
key_list = self [ agent_id ] . keys ( )
if not self [ agent_id ] . check_length ( key_list ) :
raise BufferException ( "The length of the fields {0} for agent {1} where not of same length" . format ( key_list , agent_id ) )
for field_key in key_list :
self . update_buffer [ field_key ]... |
def rapid_upload ( self ) :
'''快速上传 .
如果失败 , 就自动调用分片上传 .''' | info = pcs . rapid_upload ( self . cookie , self . tokens , self . row [ SOURCEPATH_COL ] , self . row [ PATH_COL ] , self . upload_mode )
if info and info [ 'md5' ] and info [ 'fs_id' ] :
self . emit ( 'uploaded' , self . row [ FID_COL ] )
else :
self . slice_upload ( ) |
def _iparam_namespace_from_namespace ( self , obj ) : # pylint : disable = invalid - name ,
"""Determine the namespace from a namespace string , or ` None ` . The
default namespace of the connection object is used , if needed .
Return the so determined namespace for use as an argument to
imethodcall ( ) .""" | if isinstance ( obj , six . string_types ) :
namespace = obj . strip ( '/' )
elif obj is None :
namespace = obj
else :
raise TypeError ( _format ( "The 'namespace' argument of the WBEMConnection " "operation has invalid type {0} (must be None, or a " "string)" , type ( obj ) ) )
if namespace is None :
n... |
def _parse_linux_cx_state ( self , lines , tcp_states , state_col , protocol = None , ip_version = None ) :
"""Parse the output of the command that retrieves the connection state ( either ` ss ` or ` netstat ` )
Returns a dict metric _ name - > value""" | metrics = { }
for _ , val in iteritems ( self . cx_state_gauge ) :
metrics [ val ] = 0
for l in lines :
cols = l . split ( )
if cols [ 0 ] . startswith ( 'tcp' ) or protocol == 'tcp' :
proto = "tcp{0}" . format ( ip_version ) if ip_version else ( "tcp4" , "tcp6" ) [ cols [ 0 ] == "tcp6" ]
if... |
def generate_accepted_kwargs ( function , * named_arguments ) :
"""Dynamically creates a function that when called with dictionary of arguments will produce a kwarg that ' s
compatible with the supplied function""" | if hasattr ( function , '__code__' ) and takes_kwargs ( function ) :
function_takes_kwargs = True
function_takes_arguments = [ ]
else :
function_takes_kwargs = False
function_takes_arguments = takes_arguments ( function , * named_arguments )
def accepted_kwargs ( kwargs ) :
if function_takes_kwargs ... |
def available_gpus ( ) :
"""List of GPU device names detected by TensorFlow .""" | local_device_protos = device_lib . list_local_devices ( )
return [ x . name for x in local_device_protos if x . device_type == 'GPU' ] |
def binaryRecordsStream ( self , directory , recordLength ) :
"""Create an input stream that monitors a Hadoop - compatible file system
for new files and reads them as flat binary files with records of
fixed length . Files must be written to the monitored directory by " moving "
them from another location wit... | return DStream ( self . _jssc . binaryRecordsStream ( directory , recordLength ) , self , NoOpSerializer ( ) ) |
def create_cluster_custom_object ( self , group , version , plural , body , ** kwargs ) : # noqa : E501
"""create _ cluster _ custom _ object # noqa : E501
Creates a cluster scoped Custom object # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , plea... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . create_cluster_custom_object_with_http_info ( group , version , plural , body , ** kwargs )
# noqa : E501
else :
( data ) = self . create_cluster_custom_object_with_http_info ( group , version , plural , body , ** kwa... |
async def del_alternative ( self , alt , timeout = OTGW_DEFAULT_TIMEOUT ) :
"""Remove the specified Data - ID from the list of alternative
commands . Only one occurrence is deleted . If the Data - ID
appears multiple times in the list of alternative commands ,
this command must be repeated to delete all occur... | cmd = OTGW_CMD_DEL_ALT
alt = int ( alt )
if alt < 1 or alt > 255 :
return None
ret = await self . _wait_for_cmd ( cmd , alt , timeout )
if ret is not None :
return int ( ret ) |
def natural_sort ( list_to_sort : Iterable [ str ] ) -> List [ str ] :
"""Sorts a list of strings case insensitively as well as numerically .
For example : [ ' a1 ' , ' A2 ' , ' a3 ' , ' A11 ' , ' a22 ' ]
To sort a list in place , don ' t call this method , which makes a copy . Instead , do this :
my _ list .... | return sorted ( list_to_sort , key = natural_keys ) |
def table_width ( self ) :
"""Return the width of the table including padding and borders .""" | outer_widths = max_dimensions ( self . table_data , self . padding_left , self . padding_right ) [ 2 ]
outer_border = 2 if self . outer_border else 0
inner_border = 1 if self . inner_column_border else 0
return table_width ( outer_widths , outer_border , inner_border ) |
def part ( self , channels , message = "" ) :
"""Send a PART command .""" | self . send_items ( 'PART' , ',' . join ( always_iterable ( channels ) ) , message ) |
def cast_request_param ( param_type , param_name , param_value ) :
"""Try to cast a request param ( e . g . query arg , POST data ) from a string to
its specified type in the schema . This allows validating non - string params .
: param param _ type : name of the type to be casted to
: type param _ type : str... | try :
return CAST_TYPE_TO_FUNC . get ( param_type , lambda x : x ) ( param_value )
except ValueError :
log . warn ( "Failed to cast %s value of %s to %s" , param_name , param_value , param_type )
# Ignore type error , let jsonschema validation handle incorrect types
return param_value |
def flush ( self ) :
"""This only needs to be called manually
from unit tests""" | self . logger . debug ( 'Flush joining' )
self . queue . join ( )
self . logger . debug ( 'Flush joining ready' ) |
def recover ( gzfile , last_good_position ) : # type : ( gzip . GzipFile , int ) - > gzip . GzipFile
"""Skip to the next possibly decompressable part of a gzip file .
Return a new GzipFile object if such part is found or None
if it is not found .""" | pos = get_recover_position ( gzfile , last_good_position = last_good_position )
if pos == - 1 :
return None
fp = gzfile . fileobj
fp . seek ( pos )
# gzfile . close ( )
return gzip . GzipFile ( fileobj = fp , mode = 'r' ) |
def prepare_params ( self ) :
"""Prepare the parameters passed to the templatetag""" | if self . options . resolve_fragment :
self . fragment_name = self . node . fragment_name . resolve ( self . context )
else :
self . fragment_name = str ( self . node . fragment_name )
# Remove quotes that surround the name
for char in '\'\"' :
if self . fragment_name . startswith ( char ) or se... |
def ManualUpdateTables ( self ) :
"""Allow user to manually update the database tables .
User options from initial prompt are :
- ' ls ' : print database contents
- ' a ' : add an row to a database table
- ' d ' : delete a single table row
- ' p ' : delete an entire table ( purge )
- ' f ' : finish upda... | goodlogging . Log . Info ( "DB" , "Starting manual database update:\n" )
updateFinished = False
# Loop until the user continues program flow or exits
while not updateFinished :
prompt = "Enter 'ls' to print the database contents, " "'a' to add a table entry, " "'d' to delete a single table row, " "'p' to select a e... |
def qteRunHook ( self , hookName : str , msgObj : QtmacsMessage = None ) :
"""Trigger the hook named ` ` hookName ` ` and pass on ` ` msgObj ` ` .
This will call all slots associated with ` ` hookName ` ` but
without calling the event loop in between . Therefore , if
one slots changes the state of the GUI , e... | # Shorthand .
reg = self . _qteRegistryHooks
# Do nothing if there are not recipients for the hook .
if hookName not in reg :
return
# Create an empty ` ` QtmacsMessage ` ` object if none was provided .
if msgObj is None :
msgObj = QtmacsMessage ( )
# Add information about the hook that will deliver ` ` msgObj ... |
def OnSelChanged ( self , event ) :
"""Method called when selected item is changed""" | # Get the selected item object
item = event . GetItem ( )
obj = self . leftPanel . model . ItemToObject ( item )
if isinstance ( obj , compass . Survey ) :
l = [ 'Survey Name: %s' % obj . name , 'Survey Date: %s' % obj . date , 'Comment: %s' % obj . comment , 'Team: %s' % ', ' . join ( obj . team ) , 'Surveyed Foot... |
def parse_route_name_and_version ( route_repr ) :
"""Parse a route representation string and return the route name and version number .
: param route _ repr : Route representation string .
: return : A tuple containing route name and version number .""" | if ':' in route_repr :
route_name , version = route_repr . split ( ':' , 1 )
try :
version = int ( version )
except ValueError :
raise ValueError ( 'Invalid route representation: {}' . format ( route_repr ) )
else :
route_name = route_repr
version = 1
return route_name , version |
def got_scheduler_module_type_defined ( self , module_type ) :
"""Check if a module type is defined in one of the schedulers
: param module _ type : module type to search for
: type module _ type : str
: return : True if mod _ type is found else False
: rtype : bool
TODO : Factorize it with got _ broker _... | for scheduler_link in self . schedulers :
for module in scheduler_link . modules :
if module . is_a_module ( module_type ) :
return True
return False |
def fix_config ( self , options ) :
"""Fixes the options , if necessary . I . e . , it adds all required elements to the dictionary .
: param options : the options to fix
: type options : dict
: return : the ( potentially ) fixed options
: rtype : dict""" | options = super ( ROC , self ) . fix_config ( options )
opt = "class_index"
if opt not in options :
options [ opt ] = [ 0 ]
if opt not in self . help :
self . help [ opt ] = "The list of 0-based class-label indices to display (list)."
opt = "key_loc"
if opt not in options :
options [ opt ] = "lower right"
i... |
def contrast ( self , level ) :
"""Switches the display contrast to the desired level , in the range
0-255 . Note that setting the level to a low ( or zero ) value will
not necessarily dim the display to nearly off . In other words ,
this method is * * NOT * * suitable for fade - in / out animation .
: para... | assert ( 0 <= level <= 255 )
self . command ( self . _const . SETCONTRAST , level ) |
def watch_transient_file ( self , filename , mask , proc_class ) :
"""Watch a transient file , which will be created and deleted frequently
over time ( e . g . pid file ) .
@ attention : Currently under the call to this function it is not
possible to correctly watch the events triggered into the same
base d... | dirname = os . path . dirname ( filename )
if dirname == '' :
return { }
# Maintains coherence with add _ watch ( )
basename = os . path . basename ( filename )
# Assuming we are watching at least for IN _ CREATE and IN _ DELETE
mask |= IN_CREATE | IN_DELETE
def cmp_name ( event ) :
if getattr ( event , 'na... |
def full_name ( self ) :
"""Fully - qualified name used in taskqueues / tasks APIs""" | if self . _full_name is None :
self . _full_name = 'projects/{project}/taskqueues/{taskqueue}' . format ( project = self . project , taskqueue = self . id )
return self . _full_name |
def get_next_step ( self ) :
"""Find the proper step when user clicks the Next button .
: returns : The step to be switched to
: rtype : WizardStep instance or None""" | if self . selected_purpose ( ) == layer_purpose_aggregation :
new_step = self . parent . step_kw_field
else :
new_step = self . parent . step_kw_subcategory
return new_step |
def delete_metadata_for_node ( self , node , keys = None ) :
"""Deletes metadata items specified by the ' keys ' parameter for
the specified node . If no value for ' keys ' is provided , all
metadata is deleted .""" | return self . manager . delete_metadata ( self , keys = keys , node = node ) |
def _configure_injector ( self , modules ) :
"""Create the injector and install the modules .
There is a necessary order of calls . First we have to bind ` Config ` and
` Zsl ` , then we need to register the app into the global stack and then
we can install all other modules , which can use ` Zsl ` and ` Conf... | self . _register ( )
self . _create_injector ( )
self . _bind_core ( )
self . _bind_modules ( modules )
self . logger . debug ( "Injector configuration with modules {0}." . format ( modules ) )
self . _dependencies_initialized = True |
def random_flip ( sequence , rnum = None ) :
"""Flip a sequence direction with 0.5 probability""" | randin = rnum
if not randin :
randin = RandomSource ( )
if randin . random ( ) < 0.5 :
return rc ( sequence )
return sequence |
def lint ( filename , lines , config ) :
"""Lints a file .
Args :
filename : string : filename to lint .
lines : list [ int ] | None : list of lines that we want to capture . If None ,
then all lines will be captured .
config : dict [ string : linter ] : mapping from extension to a linter
function .
R... | _ , ext = os . path . splitext ( filename )
if ext in config :
output = collections . defaultdict ( list )
for linter in config [ ext ] :
linter_output = linter ( filename , lines )
for category , values in linter_output [ filename ] . items ( ) :
output [ category ] . extend ( value... |
def package_to_directory ( package_path : str ) -> str :
"""Translate a package / path specification into a real file system pathname .
: param package _ path : a package name or a package / path specification like
` ` package . subpackage / directory / subdirectory ` `
: return : the translated path name
:... | if '/' in package_path :
pkgname , subpath = package_path . split ( '/' , 1 )
else :
pkgname , subpath = package_path , ''
module = import_module ( pkgname )
path = Path ( module . __spec__ . origin ) . parent / subpath
if path . exists ( ) :
if path . is_dir ( ) :
return str ( path )
else :
... |
def save_coef ( scoef , filename ) :
"""Saves ScalarCoeffs object ' scoef ' to file . The first line of the
file has the max number N and the max number M of the scoef structure
separated by a comma . The remaining lines have the form
3.14 , 2.718
The first number is the real part of the mode and the second... | nmax = scoef . nmax
mmax = scoef . mmax
frmstr = "{0:.16e},{1:.16e}\n"
L = ( nmax + 1 ) + mmax * ( 2 * nmax - mmax + 1 ) ;
with open ( filename , 'w' ) as f :
f . write ( "{0},{1}\n" . format ( nmax , mmax ) )
for n in xrange ( 0 , L ) :
f . write ( frmstr . format ( scoef . _vec [ n ] . real , scoef . ... |
def get ( self , endpoint : str , ** kwargs ) -> dict :
"""HTTP GET operation to API endpoint .""" | return self . _request ( 'GET' , endpoint , ** kwargs ) |
def get_action_arguments ( self , service_name , action_name ) :
"""Returns a list of tuples with all known arguments for the given
service - and action - name combination . The tuples contain the
argument - name , direction and data _ type .""" | return self . services [ service_name ] . actions [ action_name ] . info |
def from_keys ( cls , keys , loader_func , type_hint = None ) :
"""Factory method for ` LazyLoadedDict `
Accepts a ` ` loader _ func ` ` that is to be applied to all ` ` keys ` ` .
: param keys : List of keys to create the dictionary with
: type keys : iterable
: param loader _ func : Function to be applied... | return cls ( { k : LazyLoadedValue ( lambda k = k : loader_func ( k ) , type_hint = type_hint ) for k in keys } ) |
def arg_list ( self , ending_char = TokenTypes . RPAREN ) :
"""arglist : expression , arglist
arglist : expression
arglist :""" | args = [ ]
while not self . cur_token . type == ending_char :
args . append ( self . expression ( ) )
if self . cur_token . type == TokenTypes . COMMA :
self . eat ( TokenTypes . COMMA )
return args |
def to_tgt ( self ) :
"""Returns the native format of an AS _ REP message and the sessionkey in EncryptionKey native format""" | enc_part = EncryptedData ( { 'etype' : 1 , 'cipher' : b'' } )
tgt_rep = { }
tgt_rep [ 'pvno' ] = krb5_pvno
tgt_rep [ 'msg-type' ] = MESSAGE_TYPE . KRB_AS_REP . value
tgt_rep [ 'crealm' ] = self . server . realm . to_string ( )
tgt_rep [ 'cname' ] = self . client . to_asn1 ( ) [ 0 ]
tgt_rep [ 'ticket' ] = Ticket . load ... |
def initrd ( self , initrd ) :
"""Sets the initrd path for this QEMU VM .
: param initrd : QEMU initrd path""" | initrd = self . manager . get_abs_image_path ( initrd )
log . info ( 'QEMU VM "{name}" [{id}] has set the QEMU initrd path to {initrd}' . format ( name = self . _name , id = self . _id , initrd = initrd ) )
if "asa" in initrd :
self . project . emit ( "log.warning" , { "message" : "Warning ASA 8 is not supported by... |
def from_xarray ( cls , arr : "xarray.Dataset" ) -> "Histogram1D" :
"""Convert form xarray . Dataset
Parameters
arr : The data in xarray representation""" | kwargs = { 'frequencies' : arr [ "frequencies" ] , 'binning' : arr [ "bins" ] , 'errors2' : arr [ "errors2" ] , 'overflow' : arr . attrs [ "overflow" ] , 'underflow' : arr . attrs [ "underflow" ] , 'keep_missed' : arr . attrs [ "keep_missed" ] }
# TODO : Add stats
return cls ( ** kwargs ) |
def get_structure ( element , reference = None ) :
"""Get the element structure
: type element : : class : ` Element < hl7apy . core . Element > `
: param element : element having the given reference structure
: param reference : the element structure from : func : ` load _ reference < hl7apy . load _ referen... | if reference is None :
try :
reference = load_reference ( element . name , element . classname , element . version )
except ( ChildNotFound , KeyError ) :
raise InvalidName ( element . classname , element . name )
if not isinstance ( reference , collections . Sequence ) :
raise Exception
ret... |
def module_ids ( self , rev = False ) :
"""Gets a list of module ids guaranteed to be sorted by run _ order , ignoring conn modules
( run order < 0 ) .""" | shutit_global . shutit_global_object . yield_to_draw ( )
ids = sorted ( list ( self . shutit_map . keys ( ) ) , key = lambda module_id : self . shutit_map [ module_id ] . run_order )
if rev :
return list ( reversed ( ids ) )
return ids |
def increment ( cls , v ) :
"""Increment the version number of an object number of object number string""" | if not isinstance ( v , ObjectNumber ) :
v = ObjectNumber . parse ( v )
return v . rev ( v . revision + 1 ) |
def _finish ( self ) :
"""Closes and waits for subprocess to exit .""" | if self . _process . returncode is None :
self . _process . stdin . flush ( )
self . _process . stdin . close ( )
self . _process . wait ( )
self . closed = True |
def check_line_length ( self , splitted_line , expected_length ) :
"""Check if the line is correctly formated . Throw a SyntaxError if it is not .""" | if len ( splitted_line ) != expected_length :
raise WrongLineFormat ( message = 'WRONG FORMATED PED LINE!' , ped_line = '\t' . join ( splitted_line ) )
return |
def get_local_gb ( iLOIP , snmp_credentials ) :
"""Gets the maximum disk size among all disks .
: param iLOIP : IP address of the server on which SNMP discovery
has to be executed .
: param snmp _ credentials in a dictionary having following mandatory
keys .
auth _ user : SNMP user
auth _ protocol : Aut... | disk_sizes = _get_disksize_MiB ( iLOIP , snmp_credentials )
max_size = 0
for uuid in disk_sizes :
for key in disk_sizes [ uuid ] :
if int ( disk_sizes [ uuid ] [ key ] ) > max_size :
max_size = int ( disk_sizes [ uuid ] [ key ] )
max_size_gb = max_size / 1024
return max_size_gb |
def distributedConnectionMap ( names : List [ str ] ) -> OrderedDict :
"""Create a map where every node is connected every other node .
Assume each key in the returned dictionary to be connected to each item in
its value ( list ) .
: param names : a list of node names
: return : a dictionary of name - > lis... | names . sort ( )
combos = list ( itertools . combinations ( names , 2 ) )
maxPer = math . ceil ( len ( list ( combos ) ) / len ( names ) )
# maxconns = math . ceil ( len ( names ) / 2)
connmap = OrderedDict ( ( n , [ ] ) for n in names )
for a , b in combos :
if len ( connmap [ a ] ) < maxPer :
connmap [ a ... |
def update_payload ( self , fields = None ) :
"""Wrap submitted data within an extra dict .""" | org_payload = super ( Organization , self ) . update_payload ( fields )
payload = { u'organization' : org_payload }
if 'redhat_repository_url' in org_payload :
rh_repo_url = org_payload . pop ( 'redhat_repository_url' )
payload [ 'redhat_repository_url' ] = rh_repo_url
return payload |
def list_database_names ( self , session = None ) :
"""Get a list of the names of all databases on the connected server .
: Parameters :
- ` session ` ( optional ) : a
: class : ` ~ pymongo . client _ session . ClientSession ` .
. . versionadded : : 3.6""" | return [ doc [ "name" ] for doc in self . list_databases ( session , nameOnly = True ) ] |
def install_deny_hook ( api ) :
"""Install a deny import hook for Qt api .
Parameters
api : str
The Qt api whose import should be prevented
Example
> > > install _ deny _ import ( " pyqt4 " )
> > > import PyQt4
Traceback ( most recent call last ) : . . .
ImportError : Import of PyQt4 is denied .""" | if api == USED_API :
raise ValueError
sys . meta_path . insert ( 0 , ImportHookDeny ( api ) ) |
async def hset ( self , name , key , value ) :
"""Set ` ` key ` ` to ` ` value ` ` within hash ` ` name ` `
Returns 1 if HSET created a new field , otherwise 0""" | return await self . execute_command ( 'HSET' , name , key , value ) |
def add_line ( self , line , source , * lineno ) :
"""Append one line of generated reST to the output .""" | if 'conference_scheduler.scheduler' in source :
module = 'scheduler'
else :
module = 'resources'
rst [ module ] . append ( line )
self . directive . result . append ( self . indent + line , source , * lineno ) |
def request ( device , response_queue , payload , timeout_s = None , poll = POLL_QUEUES ) :
'''Send payload to serial device and wait for response .
Parameters
device : serial . Serial
Serial instance .
response _ queue : Queue . Queue
Queue to wait for response on .
payload : str or bytes
Payload to ... | device . write ( payload )
if poll : # Polling enabled . Wait for response in busy loop .
start = dt . datetime . now ( )
while not response_queue . qsize ( ) :
if ( dt . datetime . now ( ) - start ) . total_seconds ( ) > timeout_s :
raise queue . Empty ( 'No response received.' )
return... |
def connect ( self ) :
"""Establish the connection . This is done automatically for you .
If you lose the connection , you can manually run this to be re - connected .""" | self . conn = boto . connect_s3 ( self . AWS_ACCESS_KEY_ID , self . AWS_SECRET_ACCESS_KEY , debug = self . S3UTILS_DEBUG_LEVEL )
self . bucket = self . conn . get_bucket ( self . AWS_STORAGE_BUCKET_NAME )
self . k = Key ( self . bucket ) |
async def info ( self ) -> Optional [ JobDef ] :
"""All information on a job , including its result if it ' s available , does not wait for the result .""" | info = await self . result_info ( )
if not info :
v = await self . _redis . get ( job_key_prefix + self . job_id , encoding = None )
if v :
info = unpickle_job ( v )
if info :
info . score = await self . _redis . zscore ( queue_name , self . job_id )
return info |
def read_message_type ( file ) :
"""Read the message type from a file .""" | message_byte = file . read ( 1 )
if message_byte == b'' :
return ConnectionClosed
message_number = message_byte [ 0 ]
return _message_types . get ( message_number , UnknownMessage ) |
def from_array ( array ) :
"""Deserialize a new Chat from a given dictionary .
: return : new Chat instance .
: rtype : Chat""" | if array is None or not array :
return None
# end if
assert_type_or_raise ( array , dict , parameter_name = "array" )
from pytgbot . api_types . receivable . media import ChatPhoto
from pytgbot . api_types . receivable . updates import Message
data = { }
data [ 'id' ] = int ( array . get ( 'id' ) )
data [ 'type' ] ... |
def initialize ( self , length = None ) :
"""see ` ` _ _ init _ _ ` `""" | if length is None :
length = len ( self . bounds )
max_i = min ( ( len ( self . bounds ) - 1 , length - 1 ) )
self . _lb = array ( [ self . bounds [ min ( ( i , max_i ) ) ] [ 0 ] if self . bounds [ min ( ( i , max_i ) ) ] [ 0 ] is not None else - np . Inf for i in xrange ( length ) ] , copy = False )
self . _ub = a... |
def _clean_for_xml ( data ) :
"""Sanitize any user - submitted data to ensure that it can be used in XML""" | # If data is None or an empty string , don ' t bother
if data : # This turns a string like " Hello . . . " into " Hello & # 8230 ; "
data = data . encode ( "ascii" , "xmlcharrefreplace" ) . decode ( "ascii" )
# However it ' s still possible that there are invalid characters in the string ,
# so simply remov... |
def get_default_cassandra_connection ( ) :
"""Return first default cassandra connection
: return :""" | for alias , conn in get_cassandra_connections ( ) :
if conn . connection . default :
return alias , conn
return list ( get_cassandra_connections ( ) ) [ 0 ] |
def _runUnrealBuildTool ( self , target , platform , configuration , args , capture = False ) :
"""Invokes UnrealBuildTool with the specified parameters""" | platform = self . _transformBuildToolPlatform ( platform )
arguments = [ self . getBuildScript ( ) , target , platform , configuration ] + args
if capture == True :
return Utility . capture ( arguments , cwd = self . getEngineRoot ( ) , raiseOnError = True )
else :
Utility . run ( arguments , cwd = self . getEn... |
def calc_transition_to_state ( self , newstate ) :
"""Given a target state , generate the sequence of transitions that would move this state machine instance to that target state .
Args :
newstate : A str state name to calculate the path to .
Returns :
A bitarray containing the bits that would transition th... | cached_val = JTAGStateMachine . _lookup_cache . get ( ( self . state , newstate ) )
if cached_val :
return cached_val
if newstate not in self . states :
raise ValueError ( "%s is not a valid state for this state " "machine" % newstate )
path = self . _find_shortest_path ( self . _statestr , newstate )
if not pa... |
def get_subsequence ( self , resnums , new_id = None , copy_letter_annotations = True ) :
"""Get a subsequence as a new SeqProp object given a list of residue numbers""" | # XTODO : documentation
biop_compound_list = [ ]
for resnum in resnums : # XTODO can be sped up by separating into ranges based on continuous resnums
feat = FeatureLocation ( resnum - 1 , resnum )
biop_compound_list . append ( feat )
if len ( biop_compound_list ) == 0 :
log . debug ( 'Zero length subsequenc... |
def get_doc_indices ( self ) :
'''Returns
np . array
Integer document indices''' | if self . _document_category_df is None :
return pd . np . array ( [ ] )
categories_d = { d : i for i , d in enumerate ( self . get_categories ( ) ) }
return self . _document_category_df . category . apply ( categories_d . get ) . values |
def get_today_ipo_data ( ) :
"""查询今天可以申购的新股信息
: return : 今日可申购新股列表 apply _ code申购代码 price发行价格""" | agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:43.0) Gecko/20100101 Firefox/43.0"
send_headers = { "Host" : "xueqiu.com" , "User-Agent" : agent , "Accept" : "application/json, text/javascript, */*; q=0.01" , "Accept-Language" : "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3" , "Accept-Encoding" : "deflate" , "Cache-Co... |
def listDevices ( self , interface_id ) :
"""The CCU / Homegear asks for devices known to our XML - RPC server . We respond to that request using this method .""" | LOG . debug ( "RPCFunctions.listDevices: interface_id = %s, _devices_raw = %s" % ( interface_id , str ( self . _devices_raw ) ) )
remote = interface_id . split ( '-' ) [ - 1 ]
if remote not in self . _devices_raw :
self . _devices_raw [ remote ] = [ ]
if self . systemcallback :
self . systemcallback ( 'listDevi... |
def items ( self ) :
'''Return a list of tuples of all the keys and tasks''' | pairs = [ ]
for key , value in self . map . items ( ) :
if isinstance ( value , Shovel ) :
pairs . extend ( [ ( key + '.' + k , v ) for k , v in value . items ( ) ] )
else :
pairs . append ( ( key , value ) )
return sorted ( pairs ) |
def sockets ( self ) :
"""Returns the set of the sockets .""" | if self . listener is None :
return self . clients
else :
return self . clients . union ( [ self . listener ] ) |
def get_access_flags_string ( value ) :
"""Transform an access flag field to the corresponding string
: param value : the value of the access flags
: type value : int
: rtype : string""" | flags = [ ]
for k , v in ACCESS_FLAGS . items ( ) :
if ( k & value ) == k :
flags . append ( v )
return " " . join ( flags ) |
def timestamping_validate ( data , schema ) :
"""Custom validation function which inserts a timestamp for when the
validation occurred""" | jsonschema . validate ( data , schema )
data [ 'timestamp' ] = str ( time . time ( ) ) |
def failsafe_add ( _session , _instance , ** filters ) :
"""Add and commit a new instance in a nested transaction ( using SQL SAVEPOINT ) ,
gracefully handling failure in case a conflicting entry is already in the
database ( which may occur due to parallel requests causing race conditions
in a production envi... | if _instance in _session : # This instance is already in the session , most likely due to a
# save - update cascade . SQLAlchemy will flush before beginning a
# nested transaction , which defeats the purpose of nesting , so
# remove it for now and add it back inside the SAVEPOINT .
_session . expunge ( _instance )
... |
def main ( argv ) :
"""This will generate you a manifest file , and you need to modify it !
There are three category : files , untested , skipped .
You can reference current manifest . json .
usage : manifest _ parser . py ( GECKO LOCATION : / B2G / gecko / dom / webidl )
The generated file can then be used... | argparser = argparse . ArgumentParser ( )
argparser . add_argument ( "gecko" , help = "/B2G/gecko/dom/webidl" )
args = argparser . parse_args ( argv [ 1 : ] )
files = [ "gecko/dom/webidl/" + f for f in listdir ( args . gecko ) if isfile ( join ( args . gecko , f ) ) and f . endswith ( "webidl" ) ]
files . sort ( )
with... |
def evaluation_metrics ( predicted , actual , bow = True ) :
"""Input :
predicted , actual = lists of the predicted and actual tokens
bow : if true use bag of words assumption
Returns :
precision , recall , F1 , Levenshtein distance""" | if bow :
p = set ( predicted )
a = set ( actual )
true_positive = 0
for token in p :
if token in a :
true_positive += 1
else : # shove actual into a hash , count up the unique occurances of each token
# iterate through predicted , check which occur in actual
from collections impo... |
def _auth_key ( nonce , username , password ) :
"""Get an auth key to use for authentication .""" | digest = _password_digest ( username , password )
md5hash = hashlib . md5 ( )
md5hash . update ( "%s%s%s" % ( nonce , unicode ( username ) , digest ) )
return unicode ( md5hash . hexdigest ( ) ) |
def readout ( self ) :
"""Readout the detector .""" | elec = self . simulate_poisson_variate ( )
elec_pre = self . saturate ( elec )
elec_f = self . pre_readout ( elec_pre )
adu_r = self . base_readout ( elec_f )
adu_p = self . post_readout ( adu_r )
self . clean_up ( )
return adu_p |
def cd ( i ) :
"""Input : {
( repo _ uoa ) - repo UOA
module _ uoa - module UOA
data _ uoa - data UOA
or
cid
Output : {
Output of the ' load ' function
string - prepared string ' cd { path to entry } '""" | o = i . get ( 'out' , '' )
i [ 'out' ] = ''
r = find ( i )
i [ 'out' ] = o
if r [ 'return' ] > 0 :
return r
noe = r . get ( 'number_of_entries' , '' )
if noe == '' :
noe = 0
if noe > 1 and o == 'con' :
out ( 'CK warning: ' + str ( noe ) + ' entries found! Selecting the first one ...' )
out ( '' )
p = r ... |
def matches_sample ( output , target , threshold , is_correct , actual_output ) :
"""Check if a sample with the given network output , target output , and threshold
is the classification ( is _ correct , actual _ output ) like true positive or false negative""" | return ( bool ( output > threshold ) == bool ( target ) ) == is_correct and actual_output == bool ( output > threshold ) |
def idle_task ( self ) :
'''called on idle''' | if self . sock is None :
return
try :
pkt = self . sock . recv ( 10240 )
except Exception :
return
try :
if pkt . startswith ( b'PICKLED:' ) :
pkt = pkt [ 8 : ]
# pickled packet
try :
amsg = [ pickle . loads ( pkt ) ]
except pickle . UnpicklingError :
... |
def getUTC ( self ) :
"""Returns this Datetime localized for UTC .""" | timeUTC = self . time . getUTC ( self . utcoffset )
dateUTC = Date ( round ( self . jd ) )
return Datetime ( dateUTC , timeUTC ) |
def get ( self , instance , ** kwargs ) :
"""retrieves the value of the same named field on the proxy object""" | # The default value
default = self . getDefault ( instance )
# Retrieve the proxy object
proxy_object = self . get_proxy ( instance )
# Return None if we could not find a proxied object , e . g . through
# the proxy expression ' context . getSample ( ) ' on an AR
if proxy_object is None :
logger . debug ( "Expressi... |
def get_common_parameters ( input_files , collection = None ) :
"""Gets a list of variable params that are common across all input files .
If no common parameters are found , a ` ` ValueError ` ` is raised .
Parameters
input _ files : list of str
List of input files to load .
collection : str , optional
... | if collection is None :
collection = "all"
parameters = [ ]
for fn in input_files :
fp = loadfile ( fn , 'r' )
if collection == 'all' :
ps = fp [ fp . samples_group ] . keys ( )
else :
ps = fp . attrs [ collection ]
parameters . append ( set ( ps ) )
fp . close ( )
parameters = l... |
def convert ( self , pedalboard_path , system_effect = None ) :
""": param Path pedalboard _ path : Path that the pedalboard has been persisted .
Generally is in format ` path / to / pedalboard / name . pedalboard `
: param SystemEffect system _ effect : Effect that contains the audio interface outputs and inpu... | info = self . get_pedalboard_info ( pedalboard_path )
if system_effect is None :
system_effect = self . discover_system_effect ( info )
pedalboard = Pedalboard ( info [ 'title' ] )
effects_instance = { }
for effect_data in info [ 'plugins' ] :
effect = self . _generate_effect ( effect_data )
pedalboard . ap... |
def IsCloud ( self , request , bios_version , services ) :
"""Test to see if we ' re on a cloud machine .""" | if request . bios_version_regex and bios_version :
if re . match ( request . bios_version_regex , bios_version ) :
return True
if request . service_name_regex and services :
if re . search ( request . service_name_regex , services ) :
return True
return False |
def apply_effect_expression_filters ( effects , gene_expression_dict , gene_expression_threshold , transcript_expression_dict , transcript_expression_threshold ) :
"""Filter collection of varcode effects by given gene
and transcript expression thresholds .
Parameters
effects : varcode . EffectCollection
gen... | if gene_expression_dict :
effects = apply_filter ( lambda effect : ( gene_expression_dict . get ( effect . gene_id , 0.0 ) >= gene_expression_threshold ) , effects , result_fn = effects . clone_with_new_elements , filter_name = "Effect gene expression (min = %0.4f)" % gene_expression_threshold )
if transcript_expre... |
def build ( self , tool ) :
"""build the project""" | tools = self . _validate_tools ( tool )
if tools == - 1 :
return - 1
result = 0
for build_tool in tools :
builder = ToolsSupported ( ) . get_tool ( build_tool )
# None is an error
if builder is None :
logger . debug ( "Tool: %s was not found" % builder )
result = - 1
continue
... |
def purge_old_files ( date_time , directory_path , custom_prefix = "backup" ) :
"""Takes a datetime object and a directory path , runs through files in the
directory and deletes those tagged with a date from before the provided
datetime .
If your backups have a custom _ prefix that is not the default ( " back... | for file_name in listdir ( directory_path ) :
try :
file_date_time = get_backup_file_time_tag ( file_name , custom_prefix = custom_prefix )
except ValueError as e :
if "does not match format" in e . message :
print ( "WARNING. file(s) in %s do not match naming convention." % ( direct... |
def import_comments ( self , entry , comment_nodes ) :
"""Loops over comments nodes and import then
in django _ comments .""" | for comment_node in comment_nodes :
is_pingback = comment_node . find ( '{%s}comment_type' % WP_NS ) . text == PINGBACK
is_trackback = comment_node . find ( '{%s}comment_type' % WP_NS ) . text == TRACKBACK
title = 'Comment #%s' % ( comment_node . find ( '{%s}comment_id' % WP_NS ) . text )
self . write_o... |
def post ( self , path , data = None , ** kwargs ) :
"""HTTP post on the node""" | if data :
return ( yield from self . _compute . post ( "/projects/{}/{}/nodes/{}{}" . format ( self . _project . id , self . _node_type , self . _id , path ) , data = data , ** kwargs ) )
else :
return ( yield from self . _compute . post ( "/projects/{}/{}/nodes/{}{}" . format ( self . _project . id , self . _n... |
def _init_settings ( self ) :
"""Init setting""" | self . _show_whitespaces = False
self . _tab_length = 4
self . _use_spaces_instead_of_tabs = True
self . setTabStopWidth ( self . _tab_length * self . fontMetrics ( ) . width ( " " ) )
self . _set_whitespaces_flags ( self . _show_whitespaces ) |
def parse_data_directories ( self , directories = None , forwarded_exports_only = False , import_dllnames_only = False ) :
"""Parse and process the PE file ' s data directories .
If the optional argument ' directories ' is given , only
the directories at the specified indexes will be parsed .
Such functionali... | directory_parsing = ( ( 'IMAGE_DIRECTORY_ENTRY_IMPORT' , self . parse_import_directory ) , ( 'IMAGE_DIRECTORY_ENTRY_EXPORT' , self . parse_export_directory ) , ( 'IMAGE_DIRECTORY_ENTRY_RESOURCE' , self . parse_resources_directory ) , ( 'IMAGE_DIRECTORY_ENTRY_DEBUG' , self . parse_debug_directory ) , ( 'IMAGE_DIRECTORY_... |
def wait_for_setting_value ( self , section , setting , value , wait_time = 5.0 ) :
"""Function to wait wait _ time seconds to see a
SBP _ MSG _ SETTINGS _ READ _ RESP message with a user - specified value""" | expire = time . time ( ) + wait_time
ok = False
while not ok and time . time ( ) < expire :
settings = [ x for x in self . settings if ( x [ 0 ] , x [ 1 ] ) == ( section , setting ) ]
# Check to see if the last setting has the value we want
if len ( settings ) > 0 :
ok = settings [ - 1 ] [ 2 ] == va... |
def calculate_size ( name , expected ) :
"""Calculates the request payload size""" | data_size = 0
data_size += calculate_size_str ( name )
data_size += BOOLEAN_SIZE_IN_BYTES
if expected is not None :
data_size += calculate_size_data ( expected )
return data_size |
def get_subscribers ( object_type : str ) -> List [ str ] :
"""Get the list of subscribers to events of the object type .
Args :
object _ type ( str ) : Type of object .
Returns :
List [ str ] , list of subscriber names .""" | return DB . get_list ( _keys . subscribers ( object_type ) ) |
def green ( cls , string , auto = False ) :
"""Color - code entire string .
: param str string : String to colorize .
: param bool auto : Enable auto - color ( dark / light terminal ) .
: return : Class instance for colorized string .
: rtype : Color""" | return cls . colorize ( 'green' , string , auto = auto ) |
def acquire ( self , block = True ) :
"""Acquire the lock . The lock will be held until it is released
by calling : py : meth : ` Lock . release ` . If the lock was
initialized with a ` ` ttl ` ` , then the lock will be released
automatically after the given number of milliseconds .
By default this method w... | while True :
acquired = self . database . run_script ( 'lock_acquire' , keys = [ self . key ] , args = [ self . _lock_id , self . ttl ] )
if acquired == 1 or not block :
return acquired == 1
# Perform a blocking pop on the event key . When a lock
# is released , a value is pushed into the list ,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.