signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def run ( self , graminit_h , graminit_c ) :
"""Load the grammar tables from the text files written by pgen .""" | self . parse_graminit_h ( graminit_h )
self . parse_graminit_c ( graminit_c )
self . finish_off ( ) |
async def reconnect ( self ) :
"""Force a reconnection .""" | monitor = self . monitor
if monitor . reconnecting . locked ( ) or monitor . close_called . is_set ( ) :
return
async with monitor . reconnecting :
await self . close ( )
await self . _connect_with_login ( [ ( self . endpoint , self . cacert ) ] ) |
def decode ( data , encoding = 'utf-8' , errors = 'strict' ) :
"""We need to convert a dictionary where keys and values
are bytes , to unicode strings . This happens when a
Python 2 worker sends a dictionary back to a Python 3 master .""" | data_type = type ( data )
if data_type == bytes :
return bytes2unicode ( data , encoding , errors )
if data_type in ( dict , list , tuple ) :
if data_type == dict :
data = data . items ( )
return data_type ( map ( decode , data ) )
return data |
def string_chain ( text , filters ) :
"""Chain several filters after each other , applies the filter on the entire string
: param text : String to format
: param filters : Sequence of filters to apply on String
: return : The formatted String""" | if filters is None :
return text
for filter_function in filters :
text = filter_function ( text )
return text |
def add ( self , item ) :
"""Adds the specified item to this queue if there is available space .
: param item : ( object ) , the specified item .
: return : ( bool ) , ` ` true ` ` if element is successfully added , ` ` false ` ` otherwise .""" | def result_fnc ( f ) :
if f . result ( ) :
return True
raise Full ( "Queue is full!" )
return self . offer ( item ) . continue_with ( result_fnc ) |
def entries ( self ) :
"""Return the entries that are published under this node .""" | # Since there is currently no filtering in place , return all entries .
EntryModel = get_entry_model ( )
qs = get_entry_model ( ) . objects . order_by ( '-publication_date' )
# Only limit to current language when this makes sense .
if issubclass ( EntryModel , TranslatableModel ) :
admin_form_language = self . get_... |
def complete_upload ( self ) :
"""Complete the MultiPart Upload operation . This method should
be called when all parts of the file have been successfully
uploaded to S3.
: rtype : : class : ` boto . s3 . multipart . CompletedMultiPartUpload `
: returns : An object representing the completed upload .""" | xml = self . to_xml ( )
return self . bucket . complete_multipart_upload ( self . key_name , self . id , xml ) |
def get_aliases ( self ) :
"""RETURN LIST OF { " alias " : a , " index " : i } PAIRS
ALL INDEXES INCLUDED , EVEN IF NO ALIAS { " alias " : Null }""" | for index , desc in self . get_metadata ( ) . indices . items ( ) :
if not desc [ "aliases" ] :
yield wrap ( { "index" : index } )
elif desc [ 'aliases' ] [ 0 ] == index :
Log . error ( "should not happen" )
else :
for a in desc [ "aliases" ] :
yield wrap ( { "index" : in... |
def index_sets ( self , as_set = False ) :
"""Return the series as list of index set tuples .""" | indexes = frozenset if as_set else tuple
return [ indexes ( b . iter_set ( ) ) for b in self ] |
def remove_sni_cert ( self , hostname ) :
"""Remove the SSL Server Name Indicator ( SNI ) certificate configuration for
the specified * hostname * .
. . warning : :
This method will raise a : py : exc : ` RuntimeError ` if either the SNI
extension is not available in the : py : mod : ` ssl ` module or if SS... | if not g_ssl_has_server_sni :
raise RuntimeError ( 'the ssl server name indicator extension is unavailable' )
if self . _ssl_sni_entries is None :
raise RuntimeError ( 'ssl was not enabled on initialization' )
sni_entry = self . _ssl_sni_entries . pop ( hostname , None )
if sni_entry is None :
raise ValueEr... |
def download ( self , data , um_update = False ) :
"""Used to download firmware or filter set .
: param data : binary string to push via serial
: param um _ update : flag whether to update umanager""" | self . open_umanager ( )
self . ser . write ( '' . join ( ( self . cmd_download , self . cr ) ) )
if self . read_loop ( lambda x : x . endswith ( self . xmodem_crc ) , self . timeout ) :
if self . xmodem . send ( StringIO . StringIO ( data ) ) :
log . info ( "Data sent" )
else :
raise Dam1021Err... |
def get_plot ( self , zero_to_efermi = True , ylim = None , smooth = False , vbm_cbm_marker = False , smooth_tol = None ) :
"""Get a matplotlib object for the bandstructure plot .
Blue lines are up spin , red lines are down
spin .
Args :
zero _ to _ efermi : Automatically subtract off the Fermi energy from ... | plt = pretty_plot ( 12 , 8 )
from matplotlib import rc
import scipy . interpolate as scint
# main internal config options
e_min = - 4
e_max = 4
if self . _bs . is_metal ( ) :
e_min = - 10
e_max = 10
# band _ linewidth = 3
band_linewidth = 1
data = self . bs_plot_data ( zero_to_efermi )
if not smooth :
for d... |
def get_main_app ( argv = [ ] ) :
"""Standard boilerplate Qt application code .
Do everything but app . exec _ ( ) - - so that we can test the application in one thread""" | app = QApplication ( argv )
app . setApplicationName ( __appname__ )
app . setWindowIcon ( newIcon ( "app" ) )
# Tzutalin 201705 + : Accept extra agruments to change predefined class file
# Usage : labelImg . py image predefClassFile saveDir
win = MainWindow ( argv [ 1 ] if len ( argv ) >= 2 else None , argv [ 2 ] if l... |
def top2_reduced ( votes ) :
"""Description :
Top 2 alternatives 12 moment conditions values calculation
Parameters :
votes : ordinal preference data ( numpy ndarray of integers )""" | res = np . zeros ( 12 )
for vote in votes : # the top ranked alternative is in vote [ 0 ] [ 0 ] , second in vote [ 1 ] [ 0]
if vote [ 0 ] [ 0 ] == 0 : # i . e . the first alt is ranked first
res [ 0 ] += 1
if vote [ 1 ] [ 0 ] == 2 :
res [ 4 ] += 1
elif vote [ 1 ] [ 0 ] == 3 :
... |
def GetArtifactsDependenciesClosure ( name_list , os_name = None ) :
"""For all the artifacts in the list returns them and their dependencies .""" | artifacts = set ( REGISTRY . GetArtifacts ( os_name = os_name , name_list = name_list ) )
dependencies = set ( )
for art in artifacts :
dependencies . update ( GetArtifactDependencies ( art , recursive = True ) )
if dependencies :
artifacts . update ( set ( REGISTRY . GetArtifacts ( os_name = os_name , name_lis... |
def _call ( self , path , method , body = None , headers = None ) :
"""Wrapper around http . do _ call that transforms some HTTPError into
our own exceptions""" | try :
resp = self . http . do_call ( path , method , body , headers )
except http . HTTPError as err :
if err . status == 401 :
raise PermissionError ( 'Insufficient permissions to query ' + '%s with user %s :%s' % ( path , self . user , err ) )
raise
return resp |
def defrise_ellipses ( ndim , nellipses = 8 , alternating = False ) :
"""Ellipses for the standard Defrise phantom in 2 or 3 dimensions .
Parameters
ndim : { 2 , 3}
Dimension of the space for the ellipses / ellipsoids .
nellipses : int , optional
Number of ellipses . If more ellipses are used , each ellip... | ellipses = [ ]
if ndim == 2 :
for i in range ( nellipses ) :
if alternating :
value = ( - 1.0 + 2.0 * ( i % 2 ) )
else :
value = 1.0
axis_1 = 0.5
axis_2 = 0.5 / ( nellipses + 1 )
center_x = 0.0
center_y = - 1 + 2.0 / ( nellipses + 1.0 ) * ( i +... |
def _estimate_param_scan_worker ( estimator , params , X , evaluate , evaluate_args , failfast , return_exceptions ) :
"""Method that runs estimation for several parameter settings .
Defined as a worker for parallelization""" | # run estimation
model = None
try : # catch any exception
estimator . estimate ( X , ** params )
model = estimator . model
except KeyboardInterrupt : # we want to be able to interactively interrupt the worker , no matter of failfast = False .
raise
except :
e = sys . exc_info ( ) [ 1 ]
if isinstance... |
def read_stream ( self , stream_id , size = None ) :
"""Read data from the given stream .
By default ( ` size = None ` ) , this returns all data left in current HTTP / 2
frame . In other words , default behavior is to receive frame by frame .
If size is given a number above zero , method will try to return as... | rv = [ ]
try :
with ( yield from self . _get_stream ( stream_id ) . rlock ) :
if size is None :
rv . append ( ( yield from self . _get_stream ( stream_id ) . read_frame ( ) ) )
self . _flow_control ( stream_id )
elif size < 0 :
while True :
rv . ex... |
def is_parseable ( self ) :
"""Check if content is parseable for recursion .
@ return : True if content is parseable
@ rtype : bool""" | if not self . valid :
return False
# some content types must be validated with the page content
if self . content_type in ( "application/xml" , "text/xml" ) :
rtype = mimeutil . guess_mimetype_read ( self . get_content )
if rtype is not None : # XXX side effect
self . content_type = rtype
if self . ... |
def from_qubo ( cls , Q , offset = 0.0 ) :
"""Create a binary quadratic model from a QUBO model .
Args :
Q ( dict ) :
Coefficients of a quadratic unconstrained binary optimization
( QUBO ) problem . Should be a dict of the form ` { ( u , v ) : bias , . . . } `
where ` u ` , ` v ` , are binary - valued var... | linear = { }
quadratic = { }
for ( u , v ) , bias in iteritems ( Q ) :
if u == v :
linear [ u ] = bias
else :
quadratic [ ( u , v ) ] = bias
return cls ( linear , quadratic , offset , Vartype . BINARY ) |
def get_binary ( self ) :
"""Return a binary buffer containing the file content""" | content_disp = 'Content-Disposition: form-data; name="file"; filename="{}"'
stream = io . BytesIO ( )
stream . write ( _string_to_binary ( '--{}' . format ( self . boundary ) ) )
stream . write ( _crlf ( ) )
stream . write ( _string_to_binary ( content_disp . format ( self . file_name ) ) )
stream . write ( _crlf ( ) )... |
def contraction_conical_Crane ( Di1 , Di2 , l = None , angle = None ) :
r'''Returns loss coefficient for a conical pipe contraction
as shown in Crane TP 410M [ 1 ] _ between 0 and 180 degrees .
If : math : ` \ theta < 45 ^ { \ circ } ` :
. . math : :
K _ 2 = { 0.8 \ sin \ frac { \ theta } { 2 } ( 1 - \ beta... | if l is None and angle is None :
raise Exception ( 'One of `l` or `angle` must be specified' )
beta = Di2 / Di1
beta2 = beta * beta
if angle is not None :
angle = radians ( angle )
# l = ( Di1 - Di2 ) / ( 2.0 * tan ( 0.5 * angle ) ) # L is not needed in this calculation
elif l is not None :
try :
... |
def impute_using_statistics ( df , method = 'min' ) :
"""Imputes the missing values by the selected statistical property of each column
: param df : The input dataframe that contains missing values
: param method : The imputation method ( min by default )
" zero " : fill missing entries with zeros
" mean " ... | sf = SimpleFill ( method )
imputed_matrix = sf . complete ( df . values )
imputed_df = pd . DataFrame ( imputed_matrix , df . index , df . columns )
return imputed_df |
def is_upstart ( conn ) :
"""This helper should only used as a fallback ( last resort ) as it is not
guaranteed that it will be absolutely correct .""" | # it may be possible that we may be systemd and the caller never checked
# before so lets do that
if is_systemd ( conn ) :
return False
# get the initctl executable , if it doesn ' t exist we can ' t proceed so we
# are probably not upstart
initctl = conn . remote_module . which ( 'initctl' )
if not initctl :
r... |
def attribute_labels ( self , attribute_id , params = None ) :
"""Gets the security labels from a attribute
Yields : Security label json""" | if params is None :
params = { }
if not self . can_update ( ) :
self . _tcex . handle_error ( 910 , [ self . type ] )
for al in self . tc_requests . attribute_labels ( self . api_type , self . api_sub_type , self . unique_id , attribute_id , owner = self . owner , params = params , ) :
yield al |
def create_id ( self , prefix = "guid" ) :
"""Create an ID .
Note that if ` prefix ` is not provided , it will be ` guid ` , even if the
` method ` is ` METHOD _ INT ` .""" | if self . method == IDGenerator . METHOD_UUID :
id_ = str ( uuid . uuid4 ( ) )
elif self . method == IDGenerator . METHOD_INT :
id_ = self . next_int
self . next_int += 1
else :
raise InvalidMethodError ( self . method )
return "%s:%s-%s" % ( self . namespace . prefix , prefix , id_ ) |
def lock ( self , block = True ) :
"""Lock connection from being used else where""" | self . _locked = True
return self . _lock . acquire ( block ) |
async def container_load ( self , container_type , params = None , container = None ) :
"""Loads container of elements from the reader . Supports the container ref .
Returns loaded container .
: param container _ type :
: param params :
: param container :
: param field _ archiver :
: return :""" | raw_container = container_is_raw ( container_type , params )
c_len = await load_uvarint ( self . iobj )
elem_ver = await load_uvarint ( self . iobj ) if not raw_container else 0
# if container and c _ len ! = len ( container ) :
# raise ValueError ( ' Size mismatch ' )
elem_type = x . container_elem_type ( container_ty... |
def error ( self , interface_id , errorcode , msg ) :
"""When some error occurs the CCU / Homegear will send it ' s error message here""" | LOG . debug ( "RPCFunctions.error: interface_id = %s, errorcode = %i, message = %s" % ( interface_id , int ( errorcode ) , str ( msg ) ) )
if self . systemcallback :
self . systemcallback ( 'error' , interface_id , errorcode , msg )
return True |
def addCustomOptions ( parser ) :
"""Adds custom options to a parser .
: param parser : the parser .
: type parser : argparse . parser""" | parser . add_argument ( "--format" , type = str , metavar = "FORMAT" , default = "png" , choices = [ "png" , "ps" , "pdf" , "X11" ] , help = "The output file format (png, ps, pdf, or X11 " "formats are available). [default: %(default)s]" )
parser . add_argument ( "--title" , type = str , metavar = "STRING" , default = ... |
def read_cifar10 ( filename_queue ) :
"""Reads and parses examples from CIFAR10 data files .
Recommendation : if you want N - way read parallelism , call this function
N times . This will give you N independent Readers reading different
files & positions within those files , which will give better mixing of
... | class CIFAR10Record ( object ) :
pass
result = CIFAR10Record ( )
# Dimensions of the images in the CIFAR - 10 dataset .
# See http : / / www . cs . toronto . edu / ~ kriz / cifar . html for a description of the
# input format .
label_bytes = 1
# 2 for CIFAR - 100
result . height = 32
result . width = 32
result . de... |
def is_valid_pentameter ( self , scanned_line : str ) -> bool :
"""Determine if a scansion pattern is one of the valid Pentameter metrical patterns
: param scanned _ line : a line containing a sequence of stressed and unstressed syllables
: return bool : whether or not the scansion is a valid pentameter
> > >... | line = scanned_line . replace ( self . constants . FOOT_SEPARATOR , "" )
line = line . replace ( " " , "" )
if len ( line ) < 10 :
return False
line = line [ : - 1 ] + self . constants . OPTIONAL_ENDING
return self . VALID_PENTAMETERS . __contains__ ( line ) |
def format_value ( value ) :
"""Convert a list into a comma separated string , for displaying
select multiple values in emails .""" | if isinstance ( value , list ) :
value = ", " . join ( [ v . strip ( ) for v in value ] )
return value |
def _check_ising_linear_ranges ( linear_ranges , graph ) :
"""check correctness / populate defaults for ising _ linear _ ranges .""" | if linear_ranges is None :
linear_ranges = { }
for v in graph :
if v in linear_ranges : # check
linear_ranges [ v ] = Specification . _check_range ( linear_ranges [ v ] )
else : # set default
linear_ranges [ v ] = [ - 2 , 2 ]
return linear_ranges |
def maturity_date ( self ) :
"""[ datetime ] 期货到期日 。 主力连续合约与指数连续合约都为 datetime ( 2999 , 12 , 31 ) ( 期货专用 )""" | try :
return self . __dict__ [ "maturity_date" ]
except ( KeyError , ValueError ) :
raise AttributeError ( "Instrument(order_book_id={}) has no attribute 'maturity_date' " . format ( self . order_book_id ) ) |
def browse_dailydeviations ( self ) :
"""Retrieves Daily Deviations""" | response = self . _req ( '/browse/dailydeviations' )
deviations = [ ]
for item in response [ 'results' ] :
d = Deviation ( )
d . from_dict ( item )
deviations . append ( d )
return deviations |
def get_parent_object ( self ) :
"""Lookup a parent object . If parent _ field is None
this will return None . Otherwise this will try to
return that object .
The filter arguments are found by using the known url
parameters of the bundle , finding the value in the url keyword
arguments and matching them w... | if self . parent_field : # Get the model we are querying on
if getattr ( self . model . _meta , 'init_name_map' , None ) : # pre - django - 1.8
cache = self . model . _meta . init_name_map ( )
field , mod , direct , m2m = cache [ self . parent_field ]
else : # 1.10
if DJANGO_VERSION [ 1 ... |
def __driver_stub ( self , text , state ) :
"""Display help messages or invoke the proper completer .
The interface of helper methods and completer methods are documented in
the helper ( ) decorator method and the completer ( ) decorator method ,
respectively .
Arguments :
text : A string , that is the cu... | origline = readline . get_line_buffer ( )
line = origline . lstrip ( )
if line and line [ - 1 ] == '?' :
self . __driver_helper ( line )
else :
toks = shlex . split ( line )
return self . __driver_completer ( toks , text , state ) |
def words ( self , fileids = None ) -> Generator [ str , str , None ] :
"""Provide the words of the corpus ; skipping any paragraphs flagged by keywords to the main
class constructor
: param fileids :
: return : words , including punctuation , one by one""" | if not fileids :
fileids = self . fileids ( )
for para in self . paras ( fileids ) :
flat_para = flatten ( para )
skip = False
if self . skip_keywords :
for keyword in self . skip_keywords :
if keyword in flat_para :
skip = True
if not skip :
for word in f... |
def update ( self , checked = False , labels = None , custom_labels = None ) :
"""Use this function when we make changes to the list of labels or when
we load a new dataset .
Parameters
checked : bool
argument from clicked . connect
labels : list of str
list of labels in the dataset ( default )
custom... | if labels is not None :
self . setEnabled ( True )
self . chan_name = labels
self . table . blockSignals ( True )
self . table . clearContents ( )
self . table . setRowCount ( len ( self . chan_name ) )
for i , label in enumerate ( self . chan_name ) :
old_label = QTableWidgetItem ( label )
old_label . ... |
def _get_bounds ( self , layers ) :
"""Return the bounds of all data layers involved in a cartoframes map .
Args :
layers ( list ) : List of cartoframes layers . See ` cartoframes . layers `
for all types .
Returns :
dict : Dictionary of northern , southern , eastern , and western bounds
of the superset... | extent_query = ( 'SELECT ST_EXTENT(the_geom) AS the_geom ' 'FROM ({query}) AS t{idx}\n' )
union_query = 'UNION ALL\n' . join ( [ extent_query . format ( query = layer . orig_query , idx = idx ) for idx , layer in enumerate ( layers ) if not layer . is_basemap ] )
extent = self . sql_client . send ( utils . minify_sql (... |
def analyze ( self , text ) :
"""Return the sentiment as a tuple of the form :
` ` ( polarity , subjectivity ) ` `
: param str text : A string .
. . todo : :
Figure out best format to be passed to the analyzer .
There might be a better format than a string of space separated
lemmas ( e . g . with pos ta... | if self . lemmatize :
text = self . _lemmatize ( text )
return self . RETURN_TYPE ( * pattern_sentiment ( text ) ) |
def token_cli ( self , eauth , load ) :
'''Create the token from the CLI and request the correct data to
authenticate via the passed authentication mechanism''' | load [ 'cmd' ] = 'mk_token'
load [ 'eauth' ] = eauth
tdata = self . _send_token_request ( load )
if 'token' not in tdata :
return tdata
try :
with salt . utils . files . set_umask ( 0o177 ) :
with salt . utils . files . fopen ( self . opts [ 'token_file' ] , 'w+' ) as fp_ :
fp_ . write ( tda... |
def _draw_label ( self , obj , count ) :
"""Helper method to draw on the current label . Not intended for external use .""" | # Start a drawing for the whole label .
label = Drawing ( float ( self . _lw ) , float ( self . _lh ) )
label . add ( self . _clip_label )
# And one for the available area ( i . e . , after padding ) .
available = Drawing ( float ( self . _dw ) , float ( self . _dh ) )
available . add ( self . _clip_drawing )
# Call th... |
def dump_zone_file ( self ) :
"""Generate a zoneinfo compatible zone description table .
Returns :
list : zoneinfo descriptions""" | data = [ ]
for zone in sorted ( self , key = attrgetter ( 'country' ) ) :
text = [ '%s %s %s' % ( zone . country , utils . to_iso6709 ( zone . latitude , zone . longitude , format = 'dms' ) [ : - 1 ] , zone . zone ) , ]
if zone . comments :
text . append ( ' %s' % ', ' . join ( zone . comments ) )
d... |
def _eval_wrapper ( self , fit_key , q , chiA , chiB , ** kwargs ) :
"""Evaluates the surfinBH3dq8 model .""" | chiA = np . array ( chiA )
chiB = np . array ( chiB )
# Warn / Exit if extrapolating
allow_extrap = kwargs . pop ( 'allow_extrap' , False )
self . _check_param_limits ( q , chiA , chiB , allow_extrap )
self . _check_unused_kwargs ( kwargs )
x = [ q , chiA [ 2 ] , chiB [ 2 ] ]
if fit_key == 'mf' or fit_key == 'all' :
... |
async def emit ( self , name ) :
"""Add a callback to the event named ' name ' .
Returns this object for chained ' on ' calls .""" | for cb in self . _event_list [ name ] :
if isawaitable ( cb ) :
await cb
else :
cb ( ) |
def forum_topic ( self ) :
"""| Comment : The topic this ticket originated from , if any""" | if self . api and self . forum_topic_id :
return self . api . _get_topic ( self . forum_topic_id ) |
def remove_permission ( self , file_id , permission_id ) :
"""Deletes a permission from a file .
: param file _ id : a spreadsheet ID ( aka file ID . )
: type file _ id : str
: param permission _ id : an ID for the permission .
: type permission _ id : str""" | url = '{0}/{1}/permissions/{2}' . format ( DRIVE_FILES_API_V2_URL , file_id , permission_id )
self . request ( 'delete' , url ) |
def _fill_auto_fields ( model , values ) :
"""Given a list of models , fill in auto _ now and auto _ now _ add fields
for upserts . Since django manager utils passes Django ' s ORM , these values
have to be automatically constructed""" | auto_field_names = [ f . attname for f in model . _meta . fields if getattr ( f , 'auto_now' , False ) or getattr ( f , 'auto_now_add' , False ) ]
now = timezone . now ( )
for value in values :
for f in auto_field_names :
setattr ( value , f , now )
return values |
def exclude_invert ( self ) : # type : ( ) - > None
"""Inverts the values in self . exclude
. . code - block : : python
> > > import pydarksky
> > > darksky = pydarksky . DarkSky ( ' 0 ' * 32)
> > > darksky . EXCLUDES
( ' currently ' , ' minutely ' , ' hourly ' , ' daily ' , ' alerts ' , ' flags ' )
> >... | tmp = self . exclude
self . _exclude = [ ]
for i in self . EXCLUDES :
if i not in tmp :
self . _exclude . append ( i ) |
def compress_and_upload ( data , compressed_file , s3_path , multipart_chunk_size_mb = 500 , method = 'gz' , delete = False , access_key = None , secret_key = None ) :
'''Compresses data and uploads to S3.
S3 upload uses ` ` s3cmd ` ` , so you must either :
1 ) Manually configure ` ` s3cmd ` ` prior to use ( ty... | logger = log . get_logger ( 's3' )
if all ( [ access_key , secret_key ] ) :
configure ( access_key = access_key , secret_key = secret_key , logger = logger )
compress ( data , compressed_file , fmt = method , logger = logger )
put ( compressed_file , s3_path , multipart_chunk_size_mb = multipart_chunk_size_mb , log... |
def _setup ( module , extras ) :
"""Install common submodules""" | Qt . __binding__ = module . __name__
for name in list ( _common_members ) + extras :
try :
submodule = _import_sub_module ( module , name )
except ImportError :
try : # For extra modules like sip and shiboken that may not be
# children of the binding .
submodule = __import__ ... |
def get_confirmed_blockhash ( self ) :
"""Gets the block CONFIRMATION _ BLOCKS in the past and returns its block hash""" | confirmed_block_number = self . web3 . eth . blockNumber - self . default_block_num_confirmations
if confirmed_block_number < 0 :
confirmed_block_number = 0
return self . blockhash_from_blocknumber ( confirmed_block_number ) |
def from_clock_time ( cls , clock_time , epoch ) :
"""Convert from a ClockTime relative to a given epoch .""" | try :
clock_time = ClockTime ( * clock_time )
except ( TypeError , ValueError ) :
raise ValueError ( "Clock time must be a 2-tuple of (s, ns)" )
else :
ordinal = clock_time . seconds // 86400
return Date . from_ordinal ( ordinal + epoch . date ( ) . to_ordinal ( ) ) |
def done ( self , warn = True ) :
"""Is the subprocess done ?""" | if not self . process :
raise Exception ( "Not implemented yet or process not started yet, make sure to overload the done() method in your Experiment class" )
self . process . poll ( )
if self . process . returncode == None :
return False
elif self . process . returncode > 0 :
raise ProcessFailed ( )
else :... |
def is_timeseries ( nc , variable ) :
'''Returns true if the variable is a time series feature type .
: param netCDF4 . Dataset nc : An open netCDF dataset
: param str variable : name of the variable to check''' | # x , y , z , t ( o )
# X ( o )
dims = nc . variables [ variable ] . dimensions
cmatrix = coordinate_dimension_matrix ( nc )
for req in ( 'x' , 'y' , 't' ) :
if req not in cmatrix :
return False
if len ( cmatrix [ 'x' ] ) != 0 :
return False
if len ( cmatrix [ 'y' ] ) != 0 :
return False
if 'z' in c... |
def virtual_networks_list_all ( ** kwargs ) :
'''. . versionadded : : 2019.2.0
List all virtual networks within a subscription .
CLI Example :
. . code - block : : bash
salt - call azurearm _ network . virtual _ networks _ list _ all''' | result = { }
netconn = __utils__ [ 'azurearm.get_client' ] ( 'network' , ** kwargs )
try :
vnets = __utils__ [ 'azurearm.paged_object_to_list' ] ( netconn . virtual_networks . list_all ( ) )
for vnet in vnets :
result [ vnet [ 'name' ] ] = vnet
except CloudError as exc :
__utils__ [ 'azurearm.log_cl... |
def step2 ( self , pub_key , salt ) :
"""Second authentication step .""" | self . _check_initialized ( )
pk_str = binascii . hexlify ( pub_key ) . decode ( )
salt = binascii . hexlify ( salt ) . decode ( )
self . client_session_key , _ , _ = self . session . process ( pk_str , salt )
_LOGGER . debug ( 'Client session key: %s' , self . client_session_key )
# Generate client public and session ... |
def get_lldp_status ( cls , intf ) :
"""Retrieves the LLDP status .""" | if intf not in cls . topo_intf_obj_dict :
LOG . error ( "Interface %s not configured at all" , intf )
return False
intf_obj = cls . topo_intf_obj_dict . get ( intf )
return intf_obj . get_lldp_status ( ) |
def parse_vote_info ( protobuf : bytes ) -> dict :
'''decode vote init tx op _ return protobuf message and validate it .''' | vote = pavoteproto . Vote ( )
vote . ParseFromString ( protobuf )
assert vote . version > 0 , { "error" : "Vote info incomplete, version can't be 0." }
assert vote . start_block < vote . end_block , { "error" : "vote can't end in the past." }
return { "version" : vote . version , "description" : vote . description , "c... |
def parse_content ( self , text ) :
"""parse section to formal format
raw _ content : { title : section ( with title ) } . For ` help ` access .
formal _ content : { title : section } but the section has been dedented
without title . For parse instance""" | raw_content = self . raw_content
raw_content . clear ( )
formal_collect = { }
with warnings . catch_warnings ( ) :
warnings . simplefilter ( "ignore" )
try :
split = self . visible_empty_line_re . split ( text )
except ValueError : # python > = 3.5
split = [ text ]
option_split_re = self . o... |
def _get_fields ( self , table_name , ** kwargs ) :
"""return all the fields for the given table""" | ret = { }
query_str = 'PRAGMA table_info({})' . format ( self . _normalize_table_name ( table_name ) )
fields = self . _query ( query_str , ** kwargs )
# pout . v ( [ dict ( d ) for d in fields ] )
query_str = 'PRAGMA foreign_key_list({})' . format ( self . _normalize_table_name ( table_name ) )
fks = { f [ "from" ] : ... |
def read ( path , corpus = True , index_by = 'uri' , follow_links = False , ** kwargs ) :
"""Read bibliographic data from Zotero RDF .
Examples
Assuming that the Zotero collection was exported to the directory
` ` / my / working / dir ` ` with the name ` ` myCollection ` ` , a subdirectory should
have been ... | # TODO : is there a case where ` from _ dir ` would make sense ?
parser = ZoteroParser ( path , index_by = index_by , follow_links = follow_links )
papers = parser . parse ( )
if corpus :
c = Corpus ( papers , index_by = index_by , ** kwargs )
if c . duplicate_papers :
warnings . warn ( "Duplicate paper... |
def check_perms ( perms , user , slug , raise_exception = False ) :
"""a helper user to check if a user has the permissions
for a given slug""" | if isinstance ( perms , string_types ) :
perms = { perms }
else :
perms = set ( perms )
allowed_users = ACLRule . get_users_for ( perms , slug )
if allowed_users :
return user in allowed_users
if perms . issubset ( set ( WALIKI_ANONYMOUS_USER_PERMISSIONS ) ) :
return True
if is_authenticated ( user ) an... |
def generate_srt_from_sjson ( sjson_subs ) :
"""Generate transcripts from sjson to SubRip ( * . srt ) .
Arguments :
sjson _ subs ( dict ) : ` sjson ` subs .
Returns :
Subtitles in SRT format .""" | output = ''
equal_len = len ( sjson_subs [ 'start' ] ) == len ( sjson_subs [ 'end' ] ) == len ( sjson_subs [ 'text' ] )
if not equal_len :
return output
for i in range ( len ( sjson_subs [ 'start' ] ) ) :
item = SubRipItem ( index = i , start = SubRipTime ( milliseconds = sjson_subs [ 'start' ] [ i ] ) , end = ... |
def run ( self ) :
"""Continually write images to the filename specified by a command queue .""" | if not self . camera . is_running :
self . camera . start ( )
while True :
if not self . cmd_q . empty ( ) :
cmd = self . cmd_q . get ( )
if cmd [ 0 ] == 'stop' :
self . out . close ( )
self . recording = False
elif cmd [ 0 ] == 'start' :
filename = cm... |
def _densMoments_approx_higherorder_gaussxpolyInts ( self , ll , ul , maxj ) :
"""Calculate all of the polynomial x Gaussian integrals occuring
in the higher - order terms , recursively""" | gaussxpolyInt = numpy . zeros ( ( maxj , len ( ul ) ) )
gaussxpolyInt [ - 1 ] = 1. / numpy . sqrt ( numpy . pi ) * ( numpy . exp ( - ll ** 2. ) - numpy . exp ( - ul ** 2. ) )
gaussxpolyInt [ - 2 ] = 1. / numpy . sqrt ( numpy . pi ) * ( numpy . exp ( - ll ** 2. ) * ll - numpy . exp ( - ul ** 2. ) * ul ) + 0.5 * ( specia... |
def parent ( self ) :
"""Cache a instance of self parent class .
: return object : instance of self . Meta . parent class""" | if not self . _meta . parent :
return None
if not self . __parent__ :
self . __parent__ = self . _meta . parent ( )
return self . __parent__ |
def getFreeEnergyDifferences ( self , compute_uncertainty = True , uncertainty_method = None , warning_cutoff = 1.0e-10 , return_theta = False ) :
"""Get the dimensionless free energy differences and uncertainties among all thermodynamic states .
Parameters
compute _ uncertainty : bool , optional
If False , t... | # Compute free energy differences .
f_i = np . matrix ( self . f_k )
Deltaf_ij = f_i - f_i . transpose ( )
# zero out numerical error for thermodynamically identical states
self . _zerosamestates ( Deltaf_ij )
returns = [ ]
returns . append ( np . array ( Deltaf_ij ) )
if compute_uncertainty or return_theta : # Compute... |
def rename ( self , source_col : str , dest_col : str ) :
"""Renames a column in the main dataframe
: param source _ col : name of the column to rename
: type source _ col : str
: param dest _ col : new name of the column
: type dest _ col : str
: example : ` ` ds . rename ( " Col 1 " , " New col " ) ` `"... | try :
self . df = self . df . rename ( columns = { source_col : dest_col } )
except Exception as e :
self . err ( e , self . rename , "Can not rename column" )
return
self . ok ( "Column" , source_col , "renamed" ) |
def to_binary ( value , encoding = 'utf-8' ) :
"""Convert value to binary string , default encoding is utf - 8
: param value : Value to be converted
: param encoding : Desired encoding""" | if not value :
return b''
if isinstance ( value , six . binary_type ) :
return value
if isinstance ( value , six . text_type ) :
return value . encode ( encoding )
return to_text ( value ) . encode ( encoding ) |
def get ( self , item ) :
"""Returns the container whose name is provided as ' item ' . If ' item ' is
not a string , the original item is returned unchanged .""" | if isinstance ( item , six . string_types ) :
item = super ( StorageClient , self ) . get ( item )
return item |
def make_tm_request ( method , uri , ** kwargs ) :
"""Make a request to TextMagic REST APIv2.
: param str method : " POST " , " GET " , " PUT " or " DELETE "
: param str uri : URI to process request .
: return : : class : ` Response `""" | headers = kwargs . get ( "headers" , { } )
user_agent = "textmagic-python/%s (Python %s)" % ( __version__ , platform . python_version ( ) )
headers [ "User-agent" ] = user_agent
headers [ "Accept-Charset" ] = "utf-8"
if "Accept-Language" not in headers :
headers [ "Accept-Language" ] = "en-us"
if ( method == "POST"... |
def ListChildren ( self , urn ) :
"""Lists children of a given urn . Resulting list is cached .""" | result = self . MultiListChildren ( [ urn ] )
try :
return result [ urn ]
except KeyError :
return [ ] |
def output ( self , _filename ) :
"""_ filename is not used
Args :
_ filename ( string )""" | txt = "Analyze of {}\n" . format ( self . slither . filename )
txt += self . get_detectors_result ( )
for contract in self . slither . contracts_derived :
txt += "\nContract {}\n" . format ( contract . name )
txt += self . is_complex_code ( contract )
is_erc20 = contract . is_erc20 ( )
txt += '\tNumber ... |
def _to_chimera ( M , N , L , q ) :
"Converts a qubit ' s linear index to chimera coordinates ." | return ( q // N // L // 2 , ( q // L // 2 ) % N , ( q // L ) % 2 , q % L ) |
def get_endpoint ( self , session , ** kwargs ) :
"""Get the HubiC storage endpoint uri .
If the current session has not been authenticated , this will trigger a
new authentication to the HubiC OAuth service .
: param keystoneclient . Session session : The session object to use for
queries .
: raises keys... | if self . endpoint is None :
try :
self . _refresh_tokens ( session )
self . _fetch_credentials ( session )
except :
raise AuthorizationFailure ( )
return self . endpoint |
def basic_auth_tween_factory ( handler , registry ) :
"""Do basic authentication , parse HTTP _ AUTHORIZATION and set remote _ user
variable to request""" | def basic_auth_tween ( request ) :
remote_user = get_remote_user ( request )
if remote_user is not None :
request . environ [ 'REMOTE_USER' ] = remote_user [ 0 ]
return handler ( request )
return basic_auth_tween |
def image ( self ) :
"""Returns a json - schema document that represents a single image entity .""" | uri = "/%s/image" % self . uri_base
resp , resp_body = self . api . method_get ( uri )
return resp_body |
def create_index ( self , index , index_type = GEO2D ) :
"""Create an index on a given attribute
: param str index : Attribute to set index on
: param str index _ type : See PyMongo index types for further information , defaults to GEO2D index .""" | self . logger . info ( "Adding %s index to stores on attribute: %s" % ( index_type , index ) )
yield self . collection . create_index ( [ ( index , index_type ) ] ) |
def extractFont ( self , xref = 0 , info_only = 0 ) :
"""extractFont ( self , xref = 0 , info _ only = 0 ) - > PyObject *""" | if self . isClosed or self . isEncrypted :
raise ValueError ( "operation illegal for closed / encrypted doc" )
return _fitz . Document_extractFont ( self , xref , info_only ) |
def _resolve_name ( name , package , level ) :
"""Return the absolute name of the module to be imported .""" | if not hasattr ( package , 'rindex' ) :
raise ValueError ( "'package' not set to a string" )
dot = len ( package )
for x in xrange ( level , 1 , - 1 ) :
try :
dot = package . rindex ( '.' , 0 , dot )
except ValueError :
raise ValueError ( "attempted relative import beyond top-level " "packag... |
def fast_lindblad_terms ( gamma , unfolding , matrix_form = False , file_name = None , return_code = False ) :
r"""Return a fast function that returns the Lindblad terms .
We test a basic two - level system .
> > > import numpy as np
> > > Ne = 2
> > > gamma21 = 2 * np . pi * 6e6
> > > gamma = np . array ... | Ne = unfolding . Ne
Nrho = unfolding . Nrho
Mu = unfolding . Mu
# We establish the arguments of the output function .
if True :
code = ""
code += "def lindblad_terms("
if not matrix_form :
code += "rho, "
if code [ - 2 : ] == ", " :
code = code [ : - 2 ]
code += "):\n"
# We initializ... |
def get_user_action_sets ( self , user_action_set_id , version = 'v1.0' ) :
"""获取数据源信息
: param user _ action _ set _ id : 数据源唯一ID
: param version : 版本号 v1.0""" | return self . _get ( 'user_action_sets/get' , params = { 'version' : version , 'user_action_set_id' : user_action_set_id } , result_processor = lambda x : x [ 'data' ] [ 'list' ] ) |
def pipe_fetchdata ( context = None , _INPUT = None , conf = None , ** kwargs ) :
"""A source that fetches and parses an XML or JSON file . Loopable .
Parameters
context : pipe2py . Context object
_ INPUT : pipeforever pipe or an iterable of items or fields
conf : {
' URL ' : { ' value ' : < url > } ,
'... | # todo : iCal and KML
funcs = get_splits ( None , conf , ** cdicts ( opts , kwargs ) )
parsed = get_parsed ( _INPUT , funcs [ 0 ] )
results = starmap ( parse_result , parsed )
items = imap ( utils . gen_items , results )
_OUTPUT = utils . multiplex ( items )
return _OUTPUT |
def unwrap ( self , message , signature ) :
"""[ MS - NLMP ] v28.0 2016-07-14
3.4.7 GSS _ UnwrapEx ( )
Emulates the GSS _ Unwrap ( ) implementation to unseal messages and verify the signature
sent matches what has been computed locally . Will throw an Exception if the signature
doesn ' t match
@ param mes... | if self . negotiate_flags & NegotiateFlags . NTLMSSP_NEGOTIATE_SEAL :
message = self . _unseal_message ( message )
self . _verify_signature ( message , signature )
elif self . negotiate_flags & NegotiateFlags . NTLMSSP_NEGOTIATE_SIGN :
self . _verify_signature ( message , signature )
return message |
def members ( self , is_manager = None ) :
"""Retrieve members of the scope .
: param is _ manager : ( optional ) set to True to return only Scope members that are also managers .
: type is _ manager : bool
: return : List of members ( usernames )
Examples
> > > members = project . members ( )
> > > man... | if not is_manager :
return [ member for member in self . _json_data [ 'members' ] if member [ 'is_active' ] ]
else :
return [ member for member in self . _json_data [ 'members' ] if member . get ( 'is_active' , False ) and member . get ( 'is_manager' , False ) ] |
def get_proxy_ticket_for ( self , service ) :
"""Verifies CAS 2.0 + XML - based authentication ticket .
: param : service
Returns username on success and None on failure .""" | if not settings . CAS_PROXY_CALLBACK :
raise CasConfigException ( "No proxy callback set in settings" )
params = { 'pgt' : self . tgt , 'targetService' : service }
url = ( urljoin ( settings . CAS_SERVER_URL , 'proxy' ) + '?' + urlencode ( params ) )
page = urlopen ( url )
try :
response = page . read ( )
t... |
def _create_tags ( ctx ) :
"create all classes and put them in ctx" | for ( tag , info ) in _TAGS . items ( ) :
class_name = tag . title ( )
quote_ , compact , self_closing , docs = info
def __init__ ( self , * childs , ** attrs ) :
TagBase . __init__ ( self , childs , attrs )
cls = type ( class_name , ( TagBase , ) , { "__doc__" : docs , "__init__" : __init__ } )... |
def se_clearing_code_bank_info ( clearing : str ) -> ( str , int ) :
"""Returns Sweden bank info by clearning code .
: param clearing : 4 - digit clearing code
: return : ( Bank name , account digit count ) or ( ' ' , None ) if not found""" | from jutil . bank_const_se import SE_BANK_CLEARING_LIST
for name , begin , end , acc_digits in SE_BANK_CLEARING_LIST :
if begin <= clearing <= end :
return name , acc_digits
return '' , None |
def build_ast_schema ( document_ast : DocumentNode , assume_valid : bool = False , assume_valid_sdl : bool = False , ) -> GraphQLSchema :
"""Build a GraphQL Schema from a given AST .
This takes the ast of a schema document produced by the parse function in
src / language / parser . py .
If no schema definitio... | if not isinstance ( document_ast , DocumentNode ) :
raise TypeError ( "Must provide a Document AST." )
if not ( assume_valid or assume_valid_sdl ) :
from . . validation . validate import assert_valid_sdl
assert_valid_sdl ( document_ast )
schema_def : Optional [ SchemaDefinitionNode ] = None
type_defs : List... |
def validate ( self , value , model_instance ) :
"""Check value is a valid JSON string , raise ValidationError on
error .""" | if isinstance ( value , six . string_types ) :
super ( JSONField , self ) . validate ( value , model_instance )
try :
json . loads ( value )
except Exception as err :
raise ValidationError ( str ( err ) ) |
def _storestr ( ins ) :
"""Stores a string value into a memory address .
It copies content of 2nd operand ( string ) , into 1st , reallocating
dynamic memory for the 1st str . These instruction DOES ALLOW
inmediate strings for the 2nd parameter , starting with ' # ' .
Must prepend ' # ' ( immediate sigil ) ... | op1 = ins . quad [ 1 ]
indirect = op1 [ 0 ] == '*'
if indirect :
op1 = op1 [ 1 : ]
immediate = op1 [ 0 ] == '#'
if immediate and not indirect :
raise InvalidIC ( 'storestr does not allow immediate destination' , ins . quad )
if not indirect :
op1 = '#' + op1
tmp1 , tmp2 , output = _str_oper ( op1 , ins . qu... |
def _compute_mean ( self , C , f0 , f1 , f2 , SC , mag , rrup , idxs , mean , scale_fac ) :
"""Compute mean value ( for a set of indexes ) without site amplification
terms . This is equation ( 5 ) , p . 2191 , without S term .""" | mean [ idxs ] = ( C [ 'c1' ] + C [ 'c2' ] * mag + C [ 'c3' ] * ( mag ** 2 ) + ( C [ 'c4' ] + C [ 'c5' ] * mag ) * f1 [ idxs ] + ( C [ 'c6' ] + C [ 'c7' ] * mag ) * f2 [ idxs ] + ( C [ 'c8' ] + C [ 'c9' ] * mag ) * f0 [ idxs ] + C [ 'c10' ] * rrup [ idxs ] + self . _compute_stress_drop_adjustment ( SC , mag , scale_fac ... |
def get_qemus ( self ) :
"""Get the maximum ID of the Qemu VMs
: return : Maximum Qemu VM ID
: rtype : int""" | qemu_vm_list = [ ]
qemu_vm_max = None
for node in self . nodes :
if node [ 'type' ] == 'QemuVM' :
qemu_vm_list . append ( node [ 'qemu_id' ] )
if len ( qemu_vm_list ) > 0 :
qemu_vm_max = max ( qemu_vm_list )
return qemu_vm_max |
def delete_custom_view ( auth , url , name ) :
"""function takes input of auth , url , and name and issues a RESTFUL call to delete a specific of custom views from HPE
IMC .
: param name : string containg the name of the desired custom view
: param auth : requests auth object # usually auth . creds from auth ... | view_id = get_custom_views ( auth , url , name ) [ 0 ] [ 'symbolId' ]
delete_custom_view_url = '/imcrs/plat/res/view/custom/' + str ( view_id )
f_url = url + delete_custom_view_url
r = requests . delete ( f_url , auth = auth , headers = HEADERS )
# creates the URL using the payload variable as the contents
try :
if... |
def iso_abundMulti ( self , cyclist , stable = False , amass_range = None , mass_range = None , ylim = [ 0 , 0 ] , ref = - 1 , decayed = False , include_title = False , title = None , pdf = False , color_plot = True , grid = False , point_set = 1 ) :
'''Method that plots figures and saves those figures to a . png
... | max_num = max ( cyclist )
for i in range ( len ( cyclist ) ) :
self . iso_abund ( cyclist [ i ] , stable , amass_range , mass_range , ylim , ref , decayed = decayed , show = False , color_plot = color_plot , grid = False , point_set = 1 , include_title = include_title )
if title != None :
pl . title ( t... |
def _compile_bus_injection ( self ) :
"""Impose injections on buses""" | string = '"""\n'
for device , series in zip ( self . devices , self . series ) :
if series :
string += 'system.' + device + '.gcall(system.dae)\n'
string += '\n'
string += 'system.dae.reset_small_g()\n'
string += self . gisland
string += '"""'
self . bus_injection = compile ( eval ( string ) , '' , 'exec' ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.