signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def report_unknown ( bytes_so_far , total_size , speed , eta ) :
'''This callback for the download function is used
when the total size is unknown''' | sys . stdout . write ( "Downloading: {0} / Unknown - {1}/s " . format ( approximate_size ( bytes_so_far ) , approximate_size ( speed ) ) )
sys . stdout . write ( "\r" )
sys . stdout . flush ( ) |
def _acl_changes ( name , id = None , type = None , rules = None , consul_url = None , token = None ) :
'''return True if the acl need to be update , False if it doesn ' t need to be update''' | info = __salt__ [ 'consul.acl_info' ] ( id = id , token = token , consul_url = consul_url )
if info [ 'res' ] and info [ 'data' ] [ 0 ] [ 'Name' ] != name :
return True
elif info [ 'res' ] and info [ 'data' ] [ 0 ] [ 'Rules' ] != rules :
return True
elif info [ 'res' ] and info [ 'data' ] [ 0 ] [ 'Type' ] != ty... |
def safe_print ( text , file = sys . stdout , flush = False ) :
"""Prints a ( unicode ) string to the console , encoded depending on
the stdout / file encoding ( eg . cp437 on Windows ) . This is to avoid
encoding errors in case of funky path names .
Works with Python 2 and 3.""" | if not isinstance ( text , basestring ) :
return print ( text , file = file )
try :
file . write ( text )
except UnicodeEncodeError :
bytes_string = text . encode ( file . encoding , 'backslashreplace' )
if hasattr ( file , 'buffer' ) :
file . buffer . write ( bytes_string )
else :
t... |
def delay ( self , seconds = 0 , minutes = 0 ) :
"""Parameters
seconds : float
The number of seconds to freeze in place .""" | minutes += int ( seconds / 60 )
seconds = seconds % 60
seconds += float ( minutes * 60 )
self . robot . pause ( )
if not self . robot . is_simulating ( ) :
_sleep ( seconds )
self . robot . resume ( )
return self |
def _data_as_matrix ( self , X_keys , y_key = None , alias = None , legend = None , match_only = None , field = None , field_function = None , legend_field = None , table = None , basis = None , step = None , window_length = None , window_step = 1 , uwis = None , include_basis = False , include_index = False , include ... | alias = alias or self . alias
if include is not None :
include = np . array ( include )
if window_length is None :
window_length = 1
# Seed with known size .
cols = window_length * len ( X_keys )
cols += sum ( [ include_basis , include_index ] )
def get_cols ( q ) :
if q is None :
return 0
a = n... |
def posthoc_quade ( a , y_col = None , block_col = None , group_col = None , dist = 't' , melted = False , sort = False , p_adjust = None ) :
'''Calculate pairwise comparisons using Quade ' s post hoc test for
unreplicated blocked data . This test is usually conducted if significant
results were obtained by the... | if melted and not all ( [ block_col , group_col , y_col ] ) :
raise ValueError ( 'block_col, group_col, y_col should be explicitly specified if using melted data' )
def compare_stats_t ( i , j ) :
dif = np . abs ( S [ groups [ i ] ] - S [ groups [ j ] ] )
tval = dif / denom
pval = 2. * ss . t . sf ( np ... |
def tocimxml ( self ) :
"""Return the CIM - XML representation of this CIM qualifier type ,
as an object of an appropriate subclass of : term : ` Element ` .
The returned CIM - XML representation is a ` QUALIFIER . DECLARATION `
element consistent with : term : ` DSP0201 ` .
Returns :
The CIM - XML repres... | if self . value is None :
value_xml = None
elif isinstance ( self . value , ( tuple , list ) ) :
array_xml = [ ]
for v in self . value :
if v is None :
if SEND_VALUE_NULL :
array_xml . append ( cim_xml . VALUE_NULL ( ) )
else :
array_xml . appe... |
def parse_tags ( content , reference_id = None , canonicalize = True ) :
"""Returns the TAGS of a cable .
Acc . to the U . S . SD every cable needs at least one tag .
` content `
The content of the cable .
` reference _ id `
The reference identifier of the cable .
` canonicalize `
Indicates if duplica... | max_idx = _MAX_HEADER_IDX
m = _SUBJECT_MAX_PATTERN . search ( content )
if m :
max_idx = m . start ( )
m = _SUBJECT_PATTERN . search ( content , 0 , max_idx )
if m :
max_idx = min ( max_idx , m . start ( ) )
m = _TAGS_PATTERN . search ( content , 0 , max_idx )
if not m :
if reference_id not in _CABLES_WITHO... |
def stream_file ( self , url , folder = None , filename = None , overwrite = False ) : # type : ( str , Optional [ str ] , Optional [ str ] , bool ) - > str
"""Stream file from url and store in provided folder or temporary folder if no folder supplied .
Must call setup method first .
Args :
url ( str ) : URL ... | path = self . get_path_for_url ( url , folder , filename , overwrite )
f = None
try :
f = open ( path , 'wb' )
for chunk in self . response . iter_content ( chunk_size = 10240 ) :
if chunk : # filter out keep - alive new chunks
f . write ( chunk )
f . flush ( )
return f . nam... |
def compose ( * coros ) :
"""Creates a coroutine function based on the composition of the passed
coroutine functions .
Each function consumes the yielded result of the coroutine that follows .
Composing coroutine functions f ( ) , g ( ) , and h ( ) would produce
the result of f ( g ( h ( ) ) ) .
Arguments... | # Make list to inherit built - in type methods
coros = list ( coros )
@ asyncio . coroutine
def reducer ( acc , coro ) :
return ( yield from coro ( acc ) )
@ asyncio . coroutine
def wrapper ( acc ) :
return ( yield from reduce ( reducer , coros , initializer = acc , right = True ) )
return wrapper |
def cancel_per_farm_db_replication ( ) :
"""Cancel replication of the per - farm databases from the local server to the
cloud server .""" | cloud_url = config [ "cloud_server" ] [ "url" ]
local_url = config [ "local_server" ] [ "url" ]
server = Server ( local_url )
for db_name in per_farm_dbs :
server . cancel_replication ( db_name ) |
def drawDisplay ( self , painter , option , rect , text ) :
"""Overloads the drawDisplay method to render HTML if the rich text \
information is set to true .
: param painter | < QtGui . QPainter >
option | < QtGui . QStyleOptionItem >
rect | < QtCore . QRect >
text | < str >""" | if self . showRichText ( ) : # create the document
doc = QtGui . QTextDocument ( )
doc . setTextWidth ( float ( rect . width ( ) ) )
doc . setHtml ( text )
# draw the contents
painter . translate ( rect . x ( ) , rect . y ( ) )
doc . drawContents ( painter , QtCore . QRectF ( 0 , 0 , float ( rec... |
def expected_information_gain ( self , expparams ) :
r"""Calculates the expected information gain for each hypothetical experiment .
: param expparams : The experiments at which to compute expected
information gain .
: type expparams : : class : ` ~ numpy . ndarray ` of dtype given by the current
model ' s ... | # This is a special case of the KL divergence estimator ( see below ) ,
# in which the other distribution is guaranteed to share support .
# for models whose outcome number changes with experiment , we
# take the easy way out and for - loop over experiments
n_eps = expparams . size
if n_eps > 1 and not self . model . i... |
def _get_directory_path ( context ) :
"""Get the storage path fro the output .""" | path = os . path . join ( settings . BASE_PATH , 'store' )
path = context . params . get ( 'path' , path )
path = os . path . join ( path , context . crawler . name )
path = os . path . abspath ( os . path . expandvars ( path ) )
try :
os . makedirs ( path )
except Exception :
pass
return path |
def _get_cur_remotes ( path ) :
"""Retrieve remote references defined in the CWL .""" | cur_remotes = set ( [ ] )
if isinstance ( path , ( list , tuple ) ) :
for v in path :
cur_remotes |= _get_cur_remotes ( v )
elif isinstance ( path , dict ) :
for v in path . values ( ) :
cur_remotes |= _get_cur_remotes ( v )
elif path and isinstance ( path , six . string_types ) :
if path . ... |
def set_logxticks_for_all ( self , row_column_list = None , logticks = None ) :
"""Manually specify the x - axis log tick values .
: param row _ column _ list : a list containing ( row , column ) tuples to
specify the subplots , or None to indicate * all * subplots .
: type row _ column _ list : list or None ... | if row_column_list is None :
self . ticks [ 'x' ] = [ '1e%d' % u for u in logticks ]
else :
for row , column in row_column_list :
self . set_logxticks ( row , column , logticks ) |
def write_pad_codewords ( buff , version , capacity , length ) :
"""Writes the pad codewords iff the data does not fill the capacity of the
symbol .
: param buff : The byte buffer .
: param int version : The ( Micro ) QR Code version .
: param int capacity : The total capacity of the symbol ( incl . error c... | # ISO / IEC 18004:2015 ( E ) - - 7.4.10 Bit stream to codeword conversion ( page 32)
# The message bit stream shall then be extended to fill the data capacity
# of the symbol corresponding to the Version and Error Correction Level , as
# defined in Table 8 , by adding the Pad Codewords 11101100 and 00010001
# alternate... |
def HsvToRgb ( h , s , v ) :
'''Convert the color from RGB coordinates to HSV .
Parameters :
The Hus component value [ 0 . . . 1]
The Saturation component value [ 0 . . . 1]
The Value component [ 0 . . . 1]
Returns :
The color as an ( r , g , b ) tuple in the range :
r [ 0 . . . 1 ] ,
g [ 0 . . . 1 ... | if s == 0 :
return ( v , v , v )
# achromatic ( gray )
h /= 60.0
h = h % 6.0
i = int ( h )
f = h - i
if not ( i & 1 ) :
f = 1 - f
# if i is even
m = v * ( 1.0 - s )
n = v * ( 1.0 - ( s * f ) )
if i == 0 :
return ( v , n , m )
if i == 1 :
return ( n , v , m )
if i == 2 :
return ( m , v , n )
if i == ... |
def combine_heads ( self , x ) :
"""Combine tensor that has been split .
Args :
x : A tensor [ batch _ size , num _ heads , length , hidden _ size / num _ heads ]
Returns :
A tensor with shape [ batch _ size , length , hidden _ size ]""" | with tf . name_scope ( "combine_heads" ) :
batch_size = tf . shape ( x ) [ 0 ]
length = tf . shape ( x ) [ 2 ]
x = tf . transpose ( x , [ 0 , 2 , 1 , 3 ] )
# - - > [ batch , length , num _ heads , depth ]
return tf . reshape ( x , [ batch_size , length , self . hidden_size ] ) |
def line_similarity ( p1a , p1b , p2a , p2b , T = CLOSE_DISTANCE_THRESHOLD ) :
"""Similarity between two lines
Args :
p1a ( [ float , float ] ) : x and y coordinates . Line A start
p1b ( [ float , float ] ) : x and y coordinates . Line A end
p2a ( [ float , float ] ) : x and y coordinates . Line B start
p... | d = line_distance_similarity ( p1a , p1b , p2a , p2b , T = T )
a = abs ( angle_similarity ( normalize ( line ( p1a , p1b ) ) , normalize ( line ( p2a , p2b ) ) ) )
return d * a |
def _to_tonnetz ( chromagram ) :
"""Project a chromagram on the tonnetz .
Returned value is normalized to prevent numerical instabilities .""" | if np . sum ( np . abs ( chromagram ) ) == 0. : # The input is an empty chord , return zero .
return np . zeros ( 6 )
_tonnetz = np . dot ( __TONNETZ_MATRIX , chromagram )
one_norm = np . sum ( np . abs ( _tonnetz ) )
# Non - zero value
_tonnetz = _tonnetz / float ( one_norm )
# Normalize tonnetz vector
return _ton... |
def _drop_oldest_chunk ( self ) :
'''To handle the case when the items comming in the chunk
is more than the maximum capacity of the chunk . Our intent
behind is to remove the oldest chunk . So that the items come
flowing in .
> > > s = StreamCounter ( 5,5)
> > > data _ stream = [ ' a ' , ' b ' , ' c ' , ... | chunk_id = min ( self . chunked_counts . keys ( ) )
chunk = self . chunked_counts . pop ( chunk_id )
self . n_counts -= len ( chunk )
for k , v in list ( chunk . items ( ) ) :
self . counts [ k ] -= v
self . counts_total -= v |
def write ( self , fptr ) :
"""Write a data entry url box to file .""" | # Make sure it is written out as null - terminated .
url = self . url
if self . url [ - 1 ] != chr ( 0 ) :
url = url + chr ( 0 )
url = url . encode ( )
length = 8 + 1 + 3 + len ( url )
write_buffer = struct . pack ( '>I4sBBBB' , length , b'url ' , self . version , self . flag [ 0 ] , self . flag [ 1 ] , self . flag... |
def match ( self , * command_tokens , ** command_env ) :
""": meth : ` . WCommandProto . match ` implementation""" | command = self . command ( )
if len ( command_tokens ) >= len ( command ) :
return command_tokens [ : len ( command ) ] == command
return False |
def error ( self , message = None ) :
"""Delegates to ` ArgumentParser . error `""" | if self . __parser__ : # pylint : disable - msg = E1101
self . __parser__ . error ( message )
# pylint : disable - msg = E1101
else :
self . logger . error ( message )
sys . exit ( 2 ) |
def FilePrinter ( filename , mode = 'a' , closing = True ) :
path = os . path . abspath ( os . path . expanduser ( filename ) )
"""Opens the given file and returns a printer to it .""" | f = open ( path , mode )
return Printer ( f , closing ) |
def advance ( self , word_id : int ) -> 'ConstrainedHypothesis' :
"""Updates the constraints object based on advancing on word _ id .
There is a complication , in that we may have started but not
yet completed a multi - word constraint . We need to allow constraints
to be added as unconstrained words , so if ... | obj = copy . deepcopy ( self )
# First , check if we ' re updating a sequential constraint .
if obj . last_met != - 1 and obj . is_sequence [ obj . last_met ] == 1 :
if word_id == obj . constraints [ obj . last_met + 1 ] : # Here , the word matches what we expect next in the constraint , so we update everything
... |
def rename_window ( self , new_name ) :
"""Return : class : ` Window ` object ` ` $ tmux rename - window < new _ name > ` ` .
Parameters
new _ name : str
name of the window""" | import shlex
lex = shlex . shlex ( new_name )
lex . escape = ' '
lex . whitespace_split = False
try :
self . cmd ( 'rename-window' , new_name )
self [ 'window_name' ] = new_name
except Exception as e :
logger . error ( e )
self . server . _update_windows ( )
return self |
def spacetodepth ( attrs , inputs , proto_obj ) :
"""Rearranges blocks of spatial data into depth .""" | new_attrs = translation_utils . _fix_attribute_names ( attrs , { 'blocksize' : 'block_size' } )
return "space_to_depth" , new_attrs , inputs |
def trigger ( self , event : str , * args : T . Any , ** kw : T . Any ) -> bool :
"""Triggers all handlers which are subscribed to an event .
Returns True when there were callbacks to execute , False otherwise .""" | callbacks = list ( self . _events . get ( event , [ ] ) )
if not callbacks :
return False
for callback in callbacks :
callback ( * args , ** kw )
return True |
def format ( self , record ) :
"""Overridden method that applies SGR codes to log messages .""" | # XXX : idea , colorize message arguments
s = super ( ANSIFormatter , self ) . format ( record )
if hasattr ( self . context , 'ansi' ) :
s = self . context . ansi ( s , ** self . get_sgr ( record ) )
return s |
def export ( self ) :
"""returns a dictionary pre - seriasation of the field
: hide :
> > > from pprint import pprint
> > > from reliure . types import Text , Numeric
> > > doc = Doc ( docnum = ' 1 ' )
> > > doc . terms = Text ( multi = True , uniq = True , attrs = { ' tf ' : Numeric ( default = 1 ) } )
... | data = { }
data [ "keys" ] = dict ( zip ( self . keys ( ) , range ( len ( self ) ) ) )
# each attr
for name in self . _attrs . keys ( ) :
data [ name ] = self . get_attribute ( name ) . export ( )
return data |
def ssh_accept_sec_context ( self , hostname , recv_token , username = None ) :
"""Accept a GSS - API context ( server mode ) .
: param str hostname : The servers hostname
: param str username : The name of the user who attempts to login
: param str recv _ token : The GSS - API Token received from the server ... | # hostname and username are not required for GSSAPI , but for SSPI
self . _gss_host = hostname
self . _username = username
if self . _gss_srv_ctxt is None :
self . _gss_srv_ctxt = gssapi . AcceptContext ( )
token = self . _gss_srv_ctxt . step ( recv_token )
self . _gss_srv_ctxt_status = self . _gss_srv_ctxt . estab... |
def from_dict ( cls , dictionary ) :
"""Create a MetadataRb instance from a dict .""" | cookbooks = set ( )
# put these in order
groups = [ cookbooks ]
for key , val in dictionary . items ( ) :
if key == 'depends' :
cookbooks . update ( { cls . depends_statement ( cbn , meta ) for cbn , meta in val . items ( ) } )
body = ''
for group in groups :
if group :
body += '\n'
body += ... |
def logging_file_config ( self , config_file ) :
"""Setup logging via the logging module ' s fileConfig function with the
specified ` ` config _ file ` ` , if applicable .
ConfigParser defaults are specified for the special ` ` _ _ file _ _ ` `
and ` ` here ` ` variables , similar to PasteDeploy config loadin... | parser = ConfigParser . ConfigParser ( )
parser . read ( [ config_file ] )
if parser . has_section ( 'loggers' ) :
config_file = os . path . abspath ( config_file )
fileConfig ( config_file , dict ( __file__ = config_file , here = os . path . dirname ( config_file ) ) ) |
def load_scalars ( filename , strict_type_checks = True ) :
"""Parses a YAML file containing the scalar definition .
: param filename : the YAML file containing the scalars definition .
: raises ParserError : if the scalar file cannot be opened or parsed .""" | # Parse the scalar definitions from the YAML file .
scalars = None
try :
with open ( filename , 'r' ) as f :
scalars = yaml . safe_load ( f )
except IOError as e :
raise ParserError ( 'Error opening ' + filename + ': ' + e . message )
except ValueError as e :
raise ParserError ( 'Error parsing scala... |
def _node_has_namespace_helper ( node : BaseEntity , namespace : str ) -> bool :
"""Check that the node has namespace information .
Might have cross references in future .""" | return namespace == node . get ( NAMESPACE ) |
def _restore_coordinator ( self ) :
"""Do the coordinator - only part of the restore .""" | # Start by ensuring that the speaker is paused as we don ' t want
# things all rolling back when we are changing them , as this could
# include things like audio
transport_info = self . device . get_current_transport_info ( )
if transport_info is not None :
if transport_info [ 'current_transport_state' ] == 'PLAYIN... |
def ekrced ( handle , segno , recno , column , nelts = _SPICE_EK_EKRCEX_ROOM_DEFAULT ) :
"""Read data from a double precision column in a specified EK record .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / ekrced _ c . html
: param handle : Handle attached to EK file .
: type... | handle = ctypes . c_int ( handle )
segno = ctypes . c_int ( segno )
recno = ctypes . c_int ( recno )
column = stypes . stringToCharP ( column )
nvals = ctypes . c_int ( 0 )
dvals = stypes . emptyDoubleVector ( nelts )
isnull = ctypes . c_int ( )
libspice . ekrced_c ( handle , segno , recno , column , ctypes . byref ( n... |
def Gregory_Scott ( x , rhol , rhog ) :
r'''Calculates void fraction in two - phase flow according to the model of
[1 ] _ as given in [ 2 ] _ and [ 3 ] _ .
. . math : :
\ alpha = \ frac { x } { \ rho _ g } \ left [ C _ 0 \ left ( \ frac { x } { \ rho _ g } + \ frac { 1 - x }
{ \ rho _ l } \ right ) + \ frac... | C0 = 1.19
return x / rhog * ( C0 * ( x / rhog + ( 1 - x ) / rhol ) ) ** - 1 |
def wcs_pix_transform ( ct , i , format = 0 ) :
"""Computes the WCS corrected pixel value given a coordinate
transformation and the raw pixel value .
Input :
ct coordinate transformation . instance of coord _ tran .
i raw pixel intensity .
format format string ( optional ) .
Returns :
WCS corrected pi... | z1 = float ( ct . z1 )
z2 = float ( ct . z2 )
i = float ( i )
yscale = 128.0 / ( z2 - z1 )
if ( format == 'T' or format == 't' ) :
format = 1
if ( i == 0 ) :
t = 0.
else :
if ( ct . zt == W_LINEAR ) :
t = ( ( i - 1 ) * ( z2 - z1 ) / 199.0 ) + z1
t = max ( z1 , min ( z2 , t ) )
else :
... |
def encode ( self , data : mx . sym . Symbol , data_length : Optional [ mx . sym . Symbol ] , seq_len : int ) -> Tuple [ mx . sym . Symbol , mx . sym . Symbol , int ] :
"""Encodes data given sequence lengths of individual examples and maximum sequence length .
: param data : Input data .
: param data _ length :... | outputs , _ = self . rnn . unroll ( seq_len , inputs = data , merge_outputs = True , layout = self . layout )
return outputs , data_length , seq_len |
def multi_process ( func , data , num_process = None , verbose = True , ** args ) :
'''Function to use multiprocessing to process pandas Dataframe .
This function applies a function on each row of the input DataFrame by
multiprocessing .
Args :
func ( function ) : The function to apply on each row of the in... | # Check arguments value
assert isinstance ( data , pd . DataFrame ) , 'Input data must be a pandas.DataFrame instance'
if num_process is None :
num_process = multiprocessing . cpu_count ( )
# Establish communication queues
tasks = multiprocessing . JoinableQueue ( )
results = multiprocessing . Queue ( )
error_queue... |
def iteritems ( d , ** kw ) :
"""Return an iterator over the ( key , value ) pairs of a dictionary .""" | if not PY2 :
return iter ( d . items ( ** kw ) )
return d . iteritems ( ** kw ) |
def composite_qc ( df_orig , size = ( 16 , 12 ) ) :
"""Plot composite QC figures""" | df = df_orig . rename ( columns = { "hli_calc_age_sample_taken" : "Age" , "hli_calc_gender" : "Gender" , "eth7_max" : "Ethnicity" , "MeanCoverage" : "Mean coverage" , "Chemistry" : "Sequencing chemistry" , "Release Client" : "Cohort" , } )
fig = plt . figure ( 1 , size )
ax1 = plt . subplot2grid ( ( 2 , 7 ) , ( 0 , 0 )... |
def _serialize ( self ) :
"""A helper method to build a dict of all mutable Properties of
this object""" | result = { a : getattr ( self , a ) for a in type ( self ) . properties if type ( self ) . properties [ a ] . mutable }
for k , v in result . items ( ) :
if isinstance ( v , Base ) :
result [ k ] = v . id
return result |
def get_distutils_display_options ( ) :
"""Returns a set of all the distutils display options in their long and
short forms . These are the setup . py arguments such as - - name or - - version
which print the project ' s metadata and then exit .
Returns
opts : set
The long and short form display option ar... | short_display_opts = set ( '-' + o [ 1 ] for o in Distribution . display_options if o [ 1 ] )
long_display_opts = set ( '--' + o [ 0 ] for o in Distribution . display_options )
# Include - h and - - help which are not explicitly listed in
# Distribution . display _ options ( as they are handled by optparse )
short_disp... |
def message ( message_type , payload , payload_length ) :
"""Build a message .""" | return packet . build ( Container ( type = message_type , id = 1 , refer = 0 , sent = Container ( secs = 0 , usecs = 0 ) , recv = Container ( secs = 0 , usecs = 0 ) , payload_length = payload_length , payload = payload ) ) |
def one_vertical_total_stress ( self , z_c ) :
"""Determine the vertical total stress at a single depth z _ c .
: param z _ c : depth from surface""" | total_stress = 0.0
depths = self . depths
end = 0
for layer_int in range ( 1 , len ( depths ) + 1 ) :
l_index = layer_int - 1
if z_c > depths [ layer_int - 1 ] :
if l_index < len ( depths ) - 1 and z_c > depths [ l_index + 1 ] :
height = depths [ l_index + 1 ] - depths [ l_index ]
... |
def linesplit ( string , columns ) : # type : ( Union [ Text , FmtStr ] , int ) - > List [ FmtStr ]
"""Returns a list of lines , split on the last possible space of each line .
Split spaces will be removed . Whitespaces will be normalized to one space .
Spaces will be the color of the first whitespace character... | if not isinstance ( string , FmtStr ) :
string = fmtstr ( string )
string_s = string . s
matches = list ( re . finditer ( r'\s+' , string_s ) )
spaces = [ string [ m . start ( ) : m . end ( ) ] for m in matches if m . start ( ) != 0 and m . end ( ) != len ( string_s ) ]
words = [ string [ start : end ] for start , ... |
def where_clause ( self ) :
"""convert self . restriction to the SQL WHERE clause""" | cond = self . _make_condition ( self . restriction )
return '' if cond is True else ' WHERE %s' % cond |
def wait_for_boot_completion ( self , timeout = DEFAULT_TIMEOUT_BOOT_COMPLETION_SECOND ) :
"""Waits for Android framework to broadcast ACTION _ BOOT _ COMPLETED .
This function times out after 15 minutes .
Args :
timeout : float , the number of seconds to wait before timing out .
If not specified , no timeo... | timeout_start = time . time ( )
self . adb . wait_for_device ( timeout = timeout )
while time . time ( ) < timeout_start + timeout :
try :
if self . is_boot_completed ( ) :
return
except adb . AdbError : # adb shell calls may fail during certain period of booting
# process , which is nor... |
def parse_json ( json_file ) :
"""Parse a whole json record from the given file .
Return None if the json file does not exists or exception occurs .
Args :
json _ file ( str ) : File path to be parsed .
Returns :
A dict of json info .""" | if not os . path . exists ( json_file ) :
return None
try :
with open ( json_file , "r" ) as f :
info_str = f . readlines ( )
info_str = "" . join ( info_str )
json_info = json . loads ( info_str )
return unicode2str ( json_info )
except BaseException as e :
logging . error (... |
def isvalid ( path , access = None , extensions = None , filetype = None , minsize = None ) :
"""Check whether file meets access , extension , size , and type criteria .""" | return ( ( access is None or os . access ( path , access ) ) and ( extensions is None or checkext ( path , extensions ) ) and ( ( ( filetype == 'all' and os . path . exists ( path ) ) or ( filetype == 'dir' and os . path . isdir ( path ) ) or ( filetype == 'file' and os . path . isfile ( path ) ) ) or filetype is None ... |
def pick ( source , keys , * , transform = None ) :
"""Returns a dictionary including only specified keys from a source dictionary .
: source : a dictionary
: keys : a set of keys , or a predicate function that accepting a key
: transform : a function that transforms the values""" | check = keys if callable ( keys ) else lambda key : key in keys
return { key : transform ( source [ key ] ) if transform else source [ key ] for key in source if check ( key ) } |
def hash_key ( self , key ) :
"""" Hash " all keys in a timerange to the same value .""" | for i , destination_key in enumerate ( self . _dict ) :
if key < destination_key :
return destination_key
return key |
def pp_xml ( body ) :
"""Pretty print format some XML so it ' s readable .""" | pretty = xml . dom . minidom . parseString ( body )
return pretty . toprettyxml ( indent = " " ) |
def scan ( self , match = "*" , count = 1000 , cursor = 0 ) :
""": see : : RedisMap . scan""" | cursor , data = self . _client . sscan ( self . key_prefix , cursor = cursor , match = match , count = count )
return ( cursor , set ( map ( self . _loads , data ) ) ) |
def cpp_flag ( compiler ) :
"""Return the - std = c + + [ 0x / 11/14 ] compiler flag .
The c + + 14 is preferred over c + + 0x / 11 ( when it is available ) .""" | standards = [ '-std=c++14' , '-std=c++11' , '-std=c++0x' ]
for standard in standards :
if has_flag ( compiler , [ standard ] ) :
return standard
raise RuntimeError ( 'Unsupported compiler -- at least C++0x support ' 'is needed!' ) |
def ensure_num_chosen_alts_equals_num_obs ( obs_id_col , choice_col , df ) :
"""Checks that the total number of recorded choices equals the total number of
observations . If this is not the case , raise helpful ValueError messages .
Parameters
obs _ id _ col : str .
Denotes the column in ` df ` that contain... | num_obs = df [ obs_id_col ] . unique ( ) . shape [ 0 ]
num_choices = df [ choice_col ] . sum ( )
if num_choices < num_obs :
msg = "One or more observations have not chosen one "
msg_2 = "of the alternatives available to him/her"
raise ValueError ( msg + msg_2 )
if num_choices > num_obs :
msg = "One or m... |
def _add_internal_event ( self , name , send_event = False , internal_event_factory = None ) :
"""This is only here to ensure my constant hatred for Python 2 ' s horrid variable argument support .""" | if not internal_event_factory :
internal_event_factory = self . internal_event_factory
return self . add_event ( names , send_event = send_event , event_factory = internal_event_factory ) |
def add_issue_comment ( self , issue_id_or_key , content , extra_request_params = { } ) :
"""client = BacklogClient ( " your _ space _ name " , " your _ api _ key " )
client . add _ issue _ comment ( " YOUR _ PROJECT - 999 " , u " or . . . else e . " )""" | request_params = extra_request_params
request_params [ "content" ] = content
return self . do ( "POST" , "issues/{issue_id_or_key}/comments" , url_params = { "issue_id_or_key" : issue_id_or_key } , request_params = request_params , ) |
def wait_for_settle_all_channels ( raiden : 'RaidenService' , retry_timeout : float , ) -> None :
"""Wait until all channels are settled .
Note :
This does not time out , use gevent . Timeout .""" | chain_state = views . state_from_raiden ( raiden )
id_paymentnetworkstate = chain_state . identifiers_to_paymentnetworks . items ( )
for payment_network_id , payment_network_state in id_paymentnetworkstate :
id_tokennetworkstate = payment_network_state . tokenidentifiers_to_tokennetworks . items ( )
for token_n... |
def draw_commands ( self , surf ) :
"""Draw the list of available commands .""" | past_abilities = { act . ability for act in self . _past_actions if act . ability }
for y , cmd in enumerate ( sorted ( self . _abilities ( lambda c : c . name != "Smart" ) , key = lambda c : c . name ) , start = 2 ) :
if self . _queued_action and cmd == self . _queued_action :
color = colors . green
el... |
def features_properties_null_remove ( obj ) :
"""Remove any properties of features in the collection that have
entries mapping to a null ( i . e . , None ) value""" | features = obj [ 'features' ]
for i in tqdm ( range ( len ( features ) ) ) :
if 'properties' in features [ i ] :
properties = features [ i ] [ 'properties' ]
features [ i ] [ 'properties' ] = { p : properties [ p ] for p in properties if properties [ p ] is not None }
return obj |
def cluster_reset ( self , * , hard = False ) :
"""Reset a Redis Cluster node .""" | reset = hard and b'HARD' or b'SOFT'
fut = self . execute ( b'CLUSTER' , b'RESET' , reset )
return wait_ok ( fut ) |
def reduce ( self , func , dim = None , keep_attrs = None , ** kwargs ) :
"""Reduce the items in this group by applying ` func ` along some
dimension ( s ) .
Parameters
func : function
Function which can be called in the form
` func ( x , axis = axis , * * kwargs ) ` to return the result of collapsing
a... | if dim == DEFAULT_DIMS :
dim = ALL_DIMS
# TODO change this to dim = self . _ group _ dim after
# the deprecation process . Do not forget to remove _ reduce _ method
warnings . warn ( "Default reduction dimension will be changed to the " "grouped dimension in a future version of xarray. To " "silence thi... |
def _detailTuples ( self , uriRefs ) :
"""Given a list of uriRefs , return a list of dicts :
{ ' subject ' : s , ' predicate ' : p , ' object ' : o }
all values are strings""" | details = [ ]
for uriRef in uriRefs :
for subject , predicate , object_ in self . _rdfGraph . triples ( ( uriRef , None , None ) ) :
details . append ( { 'subject' : subject . toPython ( ) , 'predicate' : predicate . toPython ( ) , 'object' : object_ . toPython ( ) } )
return details |
def main ( title , authors , year , email , journal = '' , volume = '' , number = '' , pages = '' , publisher = '' , doi = '' , tags = [ ] , DFT_code = 'Quantum ESPRESSO' , DFT_functionals = [ 'BEEF-vdW' ] , reactions = [ { 'reactants' : [ '2.0H2Ogas' , '-1.5H2gas' , 'star' ] , 'products' : [ 'OOHstar@ontop' ] } ] , en... | for reaction in reactions :
check_reaction ( reaction [ 'reactants' ] , reaction [ 'products' ] )
# Set up directories
if custom_base is not None :
base = custom_base + '/'
else :
catbase = os . path . abspath ( os . path . curdir )
base = '%s/%s/' % ( catbase , username )
if not os . path . exists ( ba... |
def describe_spot_price_history ( DryRun = None , StartTime = None , EndTime = None , InstanceTypes = None , ProductDescriptions = None , Filters = None , AvailabilityZone = None , MaxResults = None , NextToken = None ) :
"""Describes the Spot price history . For more information , see Spot Instance Pricing History... | pass |
def check_coverage ( ) :
"""Checks if the coverage is 100 % .""" | with lcd ( settings . LOCAL_COVERAGE_PATH ) :
total_line = local ( 'grep -n Total index.html' , capture = True )
match = re . search ( r'^(\d+):' , total_line )
total_line_number = int ( match . groups ( ) [ 0 ] )
percentage_line_number = total_line_number + 5
percentage_line = local ( 'awk NR=={0} ... |
def bbox_vert_aligned ( box1 , box2 ) :
"""Returns true if the horizontal center point of either span is within the
horizontal range of the other""" | if not ( box1 and box2 ) :
return False
# NEW : any overlap counts
# return box1 . left < = box2 . right and box2 . left < = box1 . right
box1_left = box1 . left + 1.5
box2_left = box2 . left + 1.5
box1_right = box1 . right - 1.5
box2_right = box2 . right - 1.5
return not ( box1_left > box2_right or box2_left > box... |
def load_neighbour_info ( self , cache_dir , mask = None , ** kwargs ) :
"""Read index arrays from either the in - memory or disk cache .""" | mask_name = getattr ( mask , 'name' , None )
filename = self . _create_cache_filename ( cache_dir , mask = mask_name , ** kwargs )
if kwargs . get ( 'mask' ) in self . _index_caches :
self . _apply_cached_indexes ( self . _index_caches [ kwargs . get ( 'mask' ) ] )
elif cache_dir :
cache = np . load ( filename ... |
def cmd_iter_no_block ( self , tgt , fun , arg = ( ) , timeout = None , tgt_type = 'glob' , ret = '' , kwarg = None , show_jid = False , verbose = False , ** kwargs ) :
'''Yields the individual minion returns as they come in , or None
when no returns are available .
The function signature is the same as : py : ... | was_listening = self . event . cpub
try :
pub_data = self . run_job ( tgt , fun , arg , tgt_type , ret , timeout , kwarg = kwarg , listen = True , ** kwargs )
if not pub_data :
yield pub_data
else :
for fn_ret in self . get_iter_returns ( pub_data [ 'jid' ] , pub_data [ 'minions' ] , timeout... |
def coroutine ( func ) :
"""A decorator to wrap a generator function into a callable interface .
> > > @ coroutine
. . . def sum ( count ) :
. . . sum = 0
. . . for _ in range ( 0 , count ) :
. . . # note that generator arguments are passed as a tuple , hence ` num , = . . . ` instead of ` num = . . . `
... | def decorator ( * args , ** kwargs ) :
generator = func ( * args , ** kwargs )
next ( generator )
return lambda * args : generator . send ( args )
return decorator |
def source ( self ) :
"""Grab sources downloads links""" | source , source64 , = "" , ""
for line in self . SLACKBUILDS_TXT . splitlines ( ) :
if line . startswith ( self . line_name ) :
sbo_name = line [ 17 : ] . strip ( )
if line . startswith ( self . line_down ) :
if sbo_name == self . name and line [ 21 : ] . strip ( ) :
source = line [ ... |
def _postprocess_response ( self , result ) :
"""Apply fixups mimicking ActionBase . _ execute _ module ( ) ; this is copied
verbatim from action / _ _ init _ _ . py , the guts of _ parse _ returned _ data are
garbage and should be removed or reimplemented once tests exist .
: param dict result :
Dictionary... | data = self . _parse_returned_data ( result )
# Cutpasted from the base implementation .
if 'stdout' in data and 'stdout_lines' not in data :
data [ 'stdout_lines' ] = ( data [ 'stdout' ] or u'' ) . splitlines ( )
if 'stderr' in data and 'stderr_lines' not in data :
data [ 'stderr_lines' ] = ( data [ 'stderr' ]... |
def nl_socket_add_memberships ( sk , * group ) :
"""Join groups .
https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / socket . c # L417
Joins the specified groups using the modern socket option . The list of groups has to be terminated by 0.
Make sure to use the correct group definitions a... | if sk . s_fd == - 1 :
return - NLE_BAD_SOCK
for grp in group :
if not grp :
break
if grp < 0 :
return - NLE_INVAL
try :
sk . socket_instance . setsockopt ( SOL_NETLINK , NETLINK_ADD_MEMBERSHIP , grp )
except OSError as exc :
return - nl_syserr2nlerr ( exc . errno )
re... |
def get_events_for_blocks ( self , blocks , subscriptions ) :
"""Get a list of events associated with all the blocks .
Args :
blocks ( list of BlockWrapper ) : The blocks to search for events that
match each subscription .
subscriptions ( list of EventSubscriptions ) : EventFilter and
event type to filter... | events = [ ]
for blkw in blocks :
events . extend ( self . get_events_for_block ( blkw , subscriptions ) )
return events |
def from_cn ( cls , common_name ) :
"""Retrieve a certificate by its common name .""" | # search with cn
result_cn = [ ( cert [ 'id' ] , [ cert [ 'cn' ] ] + cert [ 'altnames' ] ) for cert in cls . list ( { 'status' : [ 'pending' , 'valid' ] , 'items_per_page' : 500 , 'cn' : common_name } ) ]
# search with altname
result_alt = [ ( cert [ 'id' ] , [ cert [ 'cn' ] ] + cert [ 'altnames' ] ) for cert in cls . ... |
def is_subnet_source_fw ( cls , tenant_id , subnet ) :
"""Check if the subnet is created as a result of any FW operation .""" | cfg = config . CiscoDFAConfig ( ) . cfg
subnet = subnet . split ( '/' ) [ 0 ]
in_sub_dict = cls . get_in_ip_addr ( tenant_id )
if not in_sub_dict :
return False
if in_sub_dict . get ( 'subnet' ) == subnet :
return True
out_sub_dict = cls . get_out_ip_addr ( tenant_id )
if not out_sub_dict :
return False
if ... |
def _setup_locale ( self , locale : str = locales . DEFAULT_LOCALE ) -> None :
"""Set up locale after pre - check .
: param str locale : Locale
: raises UnsupportedLocale : When locale is not supported .
: return : Nothing .""" | if not locale :
locale = locales . DEFAULT_LOCALE
locale = locale . lower ( )
if locale not in locales . SUPPORTED_LOCALES :
raise UnsupportedLocale ( locale )
self . locale = locale |
def inspect ( self , refresh = True ) :
"""provide metadata about the image ; flip refresh = True if cached metadata are enough
: param refresh : bool , update the metadata with up to date content
: return : dict""" | if refresh or not self . _inspect_data :
identifier = self . _id or self . get_full_name ( )
if not identifier :
raise ConuException ( "This image does not have a valid identifier." )
self . _inspect_data = self . d . inspect_image ( identifier )
return self . _inspect_data |
def decompose_once ( val : Any , default = RaiseTypeErrorIfNotProvided , ** kwargs ) :
"""Decomposes a value into operations , if possible .
This method decomposes the value exactly once , instead of decomposing it
and then continuing to decomposing the decomposed operations recursively
until some criteria is... | method = getattr ( val , '_decompose_' , None )
decomposed = NotImplemented if method is None else method ( ** kwargs )
if decomposed is not NotImplemented and decomposed is not None :
from cirq import ops
# HACK : Avoids circular dependencies .
return list ( ops . flatten_op_tree ( decomposed ) )
if defaul... |
def parse_yaml ( self , node ) :
'''Parse a YAML specification of a component group into this
object .''' | self . group_id = y [ 'groupId' ]
self . _members = [ ]
if 'members' in y :
for m in y . get ( 'members' ) :
self . _members . append ( TargetComponent ( ) . parse_yaml ( m ) )
return self |
def set_api_rpc ( self , rpc : str = None , rpctls : bool = False ) -> None :
"""Sets the RPC mode to either of ganache or infura
: param rpc : either of the strings - ganache , infura - mainnet , infura - rinkeby , infura - kovan , infura - ropsten""" | if rpc == "ganache" :
rpcconfig = ( "localhost" , 8545 , False )
else :
m = re . match ( r"infura-(.*)" , rpc )
if m and m . group ( 1 ) in [ "mainnet" , "rinkeby" , "kovan" , "ropsten" ] :
rpcconfig = ( m . group ( 1 ) + ".infura.io" , 443 , True )
else :
try :
host , port =... |
def hgetall ( key , host = None , port = None , db = None , password = None ) :
'''Get all fields and values from a redis hash , returns dict
CLI Example :
. . code - block : : bash
salt ' * ' redis . hgetall foo _ hash''' | server = _connect ( host , port , db , password )
return server . hgetall ( key ) |
def task_start ( self , ** kw ) :
"""Marks a task as started .""" | id , task = self . get_task ( ** kw )
self . _execute ( id , 'start' )
return self . get_task ( uuid = task [ 'uuid' ] ) [ 1 ] |
def clean_filter_dict ( filter_dict , strip = False ) :
'''Clear / del Django ORM filter kwargs dict queries like ` filter ( { " < field > _ _ in " : member _ list ` where ` member _ list ` is empty
Brute force processing of user - entered lists of query parameters can often produce null ` _ _ in ` filters
whic... | if not strip :
strip = lambda s : s
elif not callable ( strip ) :
strip = lambda s : str ( s ) . strip ( )
keys_to_del = set ( )
for k , values_list in filter_dict . iteritems ( ) :
if k . endswith ( '__in' ) :
if not values_list or not any ( ( v != None and strip ( v ) != '' ) for v in values_list ... |
def ip_address ( self ) :
"""The IP address of the first interface listed in the droplet ' s
` ` networks ` ` field ( ordering IPv4 before IPv6 ) , or ` None ` if there
are no interfaces""" | networks = self . get ( "networks" , { } )
v4nets = networks . get ( "v4" , [ ] )
v6nets = networks . get ( "v6" , [ ] )
try :
return ( v4nets + v6nets ) [ 0 ] . ip_address
except IndexError :
return None |
def _call_in_reactor_thread ( self , f , * args , ** kwargs ) :
"""Call the given function with args in the reactor thread .""" | self . _reactor . callFromThread ( f , * args , ** kwargs ) |
def min ( a , axis = None ) :
"""Request the minimum of an Array over any number of axes .
. . note : : Currently limited to operating on a single axis .
Parameters
a : Array object
The object whose minimum is to be found .
axis : None , or int , or iterable of ints
Axis or axes along which the operatio... | axes = _normalise_axis ( axis , a )
assert axes is not None and len ( axes ) == 1
return _Aggregation ( a , axes [ 0 ] , _MinStreamsHandler , _MinMaskedStreamsHandler , a . dtype , { } ) |
def _make_request ( self , url , params = None , opener = None ) :
"""Configure a HTTP request , fire it off and return the response .""" | # Create the request object
args = [ i for i in [ url , params ] if i ]
request = urllib . request . Request ( * args )
# If the client has credentials , include them as a header
if self . username and self . password :
credentials = '%s:%s' % ( self . username , self . password )
encoded_credentials = base64 .... |
def calibration ( date , satellite ) :
"""Return the calibration dictionary .
Keyword arguments :
satellite - - the name of the satellite .
date - - the datetime of an image .""" | counts_shift = CountsShift ( )
space_measurement = SpaceMeasurement ( )
prelaunch = PreLaunch ( )
postlaunch = PostLaunch ( )
return { 'counts_shift' : counts_shift . coefficient ( satellite ) , 'space_measurement' : space_measurement . coefficient ( satellite ) , 'prelaunch' : prelaunch . coefficient ( satellite ) , '... |
def get_formatted_value ( self , value ) :
"""Returns a string from datetime using : member : ` parse _ format ` .
: param value : Datetime to cast to string
: type value : datetime
: return : str""" | def get_formatter ( parser_desc ) :
try :
return parser_desc [ 'formatter' ]
except TypeError :
if isinstance ( parser_desc , str ) :
try :
return get_formatter ( self . date_parsers [ parser_desc ] )
except KeyError :
return parser_desc
... |
def get_change_type ( self , ref , a1 , a2 ) :
"""Given ref , allele1 , and allele2 , returns the type of change .
The only case of an amino acid insertion is when the ref is
represented as a ' . ' .""" | if ref == '.' :
return self . INSERTION
elif a1 == '.' or a2 == '.' :
return self . DELETION |
def get_supprates ( _ , data ) :
"""http : / / git . kernel . org / cgit / linux / kernel / git / jberg / iw . git / tree / scan . c ? id = v3.17 # n227.
Positional arguments :
data - - bytearray data to read .""" | answer = list ( )
for i in range ( len ( data ) ) :
r = data [ i ] & 0x7f
if r == BSS_MEMBERSHIP_SELECTOR_VHT_PHY and data [ i ] & 0x80 :
value = 'VHT'
elif r == BSS_MEMBERSHIP_SELECTOR_HT_PHY and data [ i ] & 0x80 :
value = 'HT'
else :
value = '{0}.{1}' . format ( int ( r / 2 ) ... |
def add_opinion ( self , opinion_obj ) :
"""Adds an opinion to the opinion layer
@ type opinion _ obj : L { Copinion }
@ param opinion _ obj : the opinion object""" | if self . opinion_layer is None :
self . opinion_layer = Copinions ( )
self . root . append ( self . opinion_layer . get_node ( ) )
self . opinion_layer . add_opinion ( opinion_obj ) |
def plot ( self ) :
"""Export a given dataset to a ` CSV ` file .
This method is a slot connected to the ` export ` QAction . See the
: meth : ` addEntry ` method for details .""" | # The PyTables node tied to the current leaf of the databases tree
current = self . vtgui . dbs_tree_view . currentIndex ( )
leaf = self . vtgui . dbs_tree_model . nodeFromIndex ( current ) . node
data_name = leaf . name
hists_1d = [ 'HistRelBcid' , 'HistErrorCounter' , 'HistTriggerErrorCounter' , 'HistServiceRecord' ,... |
def audio_open ( path , backends = None ) :
"""Open an audio file using a library that is available on this
system .
The optional ` backends ` parameter can be a list of audio file
classes to try opening the file with . If it is not provided ,
` audio _ open ` tries all available backends . If you call this... | if backends is None :
backends = available_backends ( )
for BackendClass in backends :
try :
return BackendClass ( path )
except DecodeError :
pass
# All backends failed !
raise NoBackendError ( ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.