signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_mean ( self , distribution_function ) :
"""Get the mean value for a distribution .
If the distribution function is [ normal , uniform , choice , triangular ] the analytic value is being calculted .
Else , the distribution is instantiated and then the mean is being calculated .
: param distribution _ f... | name = self . distribution_name
params = self . random_function_params
if name == 'normal' :
return params [ 0 ]
if name == 'uniform' :
return ( params [ 0 ] + params [ 1 ] ) / 2.
if name == 'choice' :
return params [ 0 ] . mean ( )
if name == 'triangular' :
return ( params [ 0 ] + params [ 1 ] + params... |
def guess_series ( input_string ) :
u"""Tries to convert < input _ string > into a list of floats .
Example :
> > > guess _ series ( " 0.5 1.2 3.5 7.3 8 12.5 , 13.2 , "
. . . " 15.0 , 14.2 , 11.8 , 6.1 , 1.9 " )
[0.5 , 1.2 , 3.5 , 7.3 , 8.0 , 12.5 , 13.2 , 15.0 , 14.2 , 11.8 , 6.1 , 1.9]""" | float_finder = re . compile ( "([-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?)" )
return ( [ i for i in [ _convert_to_float ( j ) for j in float_finder . findall ( input_string ) # Remove entires we couldn ' t convert to a sensible value .
] if i is not None and not math . isnan ( i ) and not math . isinf ( i ) ] ) |
def put_key ( self , source , rel_path ) :
'''Copy a file to the repository
Args :
source : Absolute path to the source file , or a file - like object
rel _ path : path relative to the root of the repository''' | k = self . _get_boto_key ( rel_path )
try :
k . set_contents_from_file ( source )
except AttributeError :
if os . path . getsize ( source ) > 4.8 * 1024 * 1024 * 1024 : # Need to do multi - part uploads here
k . set_contents_from_filename ( source )
else :
k . set_contents_from_filename ( so... |
def build_transitive_closure ( self , rel , tc_dict ) :
"""Build a transitive closure for a given relation in a given dict .""" | # Make a function with the righ argument structure
rel_fun = lambda node , graph : rel ( node )
for x in self . graph . all_nodes ( ) :
rel_closure = self . graph . transitiveClosure ( rel_fun , x )
xs = x . toPython ( )
for y in rel_closure :
ys = y . toPython ( )
if xs == ys :
... |
def get_vault_form_for_update ( self , vault_id ) :
"""Gets the vault form for updating an existing vault .
A new vault form should be requested for each update
transaction .
arg : vault _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Vault ` `
return : ( osid . authorization . VaultForm ) - the vault f... | # Implemented from template for
# osid . resource . BinAdminSession . get _ bin _ form _ for _ update _ template
if self . _catalog_session is not None :
return self . _catalog_session . get_catalog_form_for_update ( catalog_id = vault_id )
collection = JSONClientValidated ( 'authorization' , collection = 'Vault' ,... |
def add ( self ) :
"""Add service definition to hierarchy .""" | yield self . client . create ( self . path )
yield self . client . create ( self . path + "/type" , self . name )
yield self . client . create ( self . path + "/state" )
yield self . client . create ( self . path + "/machines" , "[]" )
log . debug ( "registered service '%s' at %s." % ( self . name , self . path ) ) |
def flatten ( repertoire , big_endian = False ) :
"""Flatten a repertoire , removing empty dimensions .
By default , the flattened repertoire is returned in little - endian order .
Args :
repertoire ( np . ndarray or None ) : A repertoire .
Keyword Args :
big _ endian ( boolean ) : If ` ` True ` ` , flatt... | if repertoire is None :
return None
order = 'C' if big_endian else 'F'
# For efficiency , use ` ravel ` ( which returns a view of the array ) instead
# of ` np . flatten ` ( which copies the whole array ) .
return repertoire . squeeze ( ) . ravel ( order = order ) |
def get_symbol_dict ( self , voigt = True , zero_index = False , ** kwargs ) :
"""Creates a summary dict for tensor with associated symbol
Args :
voigt ( bool ) : whether to get symbol dict for voigt
notation tensor , as opposed to full notation ,
defaults to true
zero _ index ( bool ) : whether to set in... | d = { }
if voigt :
array = self . voigt
else :
array = self
grouped = self . get_grouped_indices ( voigt = voigt , ** kwargs )
if zero_index :
p = 0
else :
p = 1
for indices in grouped :
sym_string = self . symbol + '_'
sym_string += '' . join ( [ str ( i + p ) for i in indices [ 0 ] ] )
val... |
def cost_zerg_corrected ( self ) -> "Cost" :
"""This returns 25 for extractor and 200 for spawning pool instead of 75 and 250 respectively""" | if self . race == Race . Zerg and Attribute . Structure . value in self . attributes : # a = self . _ game _ data . units ( UnitTypeId . ZERGLING )
# print ( a )
# print ( vars ( a ) )
return Cost ( self . _proto . mineral_cost - 50 , self . _proto . vespene_cost , self . _proto . build_time )
else :
return sel... |
def setupModule ( self ) :
"""* The setupModule method *
* * Return : * *
- ` ` log ` ` - - a logger
- ` ` dbConn ` ` - - a database connection to a test database ( details from yaml settings file )
- ` ` pathToInputDir ` ` - - path to modules own test input directory
- ` ` pathToOutputDir ` ` - - path to... | import pymysql as ms
# # VARIABLES # #
logging . config . dictConfig ( yaml . load ( self . loggerConfig ) )
log = logging . getLogger ( __name__ )
connDict = yaml . load ( self . dbConfig )
dbConn = ms . connect ( host = connDict [ 'host' ] , user = connDict [ 'user' ] , passwd = connDict [ 'password' ] , db = connDic... |
def _pairwise_chisq ( self ) :
"""Pairwise comparisons ( Chi - Square ) along axis , as numpy . ndarray .
Returns a list of square and symmetric matrices of test statistics for the null
hypothesis that each vector along * axis * is equal to each other .""" | return [ self . _chi_squared ( mr_subvar_proportions , self . _margin [ idx ] , self . _opposite_axis_margin [ idx ] / np . sum ( self . _opposite_axis_margin [ idx ] ) , ) for ( idx , mr_subvar_proportions ) in enumerate ( self . _proportions ) ] |
def intersperse ( iterable , element ) :
"""Generator yielding all elements of ` iterable ` , but with ` element `
inserted between each two consecutive elements""" | iterable = iter ( iterable )
yield next ( iterable )
while True :
next_from_iterable = next ( iterable )
yield element
yield next_from_iterable |
def _get_bookmark ( repo , name ) :
'''Find the requested bookmark in the specified repo''' | try :
return [ x for x in _all_bookmarks ( repo ) if x [ 0 ] == name ] [ 0 ]
except IndexError :
return False |
def qindex2index ( index ) :
"""from a QIndex ( row / column coordinate system ) , get the buffer index of the byte""" | r = index . row ( )
c = index . column ( )
if c > 0x10 :
return ( 0x10 * r ) + c - 0x11
else :
return ( 0x10 * r ) + c |
def layer_register ( log_shape = False , use_scope = True ) :
"""Args :
log _ shape ( bool ) : log input / output shape of this layer
use _ scope ( bool or None ) :
Whether to call this layer with an extra first argument as variable scope .
When set to None , it can be called either with or without
the sc... | def wrapper ( func ) :
@ wraps ( func )
def wrapped_func ( * args , ** kwargs ) :
assert args [ 0 ] is not None , args
if use_scope :
name , inputs = args [ 0 ] , args [ 1 ]
args = args [ 1 : ]
# actual positional args used to call func
assert isin... |
def get_form ( formcls ) :
"""get form class according form class path or form class object""" | from uliweb . form import Form
import inspect
if inspect . isclass ( formcls ) and issubclass ( formcls , Form ) :
return formcls
elif isinstance ( formcls , ( str , unicode ) ) :
path = settings . FORMS . get ( formcls )
if path :
_cls = import_attr ( path )
return _cls
else :
r... |
def taper ( path , length , final_width , final_distance , direction = None , layer = 0 , datatype = 0 ) :
'''Linear tapers for the lazy .
path : ` gdspy . Path ` to append the taper
length : total length
final _ width : final width of th taper
direction : taper direction
layer : GDSII layer number ( int ... | if layer . __class__ == datatype . __class__ == [ ] . __class__ :
assert len ( layer ) == len ( datatype )
elif isinstance ( layer , int ) and isinstance ( datatype , int ) :
layer = [ layer ]
datatype = [ datatype ]
else :
raise ValueError ( 'Parameters layer and datatype must have the same ' 'type (ei... |
def _mean_prediction ( self , mu , Y , h , t_z ) :
"""Creates a h - step ahead mean prediction
Parameters
mu : np . ndarray
The past predicted values
Y : np . ndarray
The past data
h : int
How many steps ahead for the prediction
t _ z : np . ndarray
A vector of ( transformed ) latent variables
R... | # Create arrays to iteratre over
Y_exp = Y . copy ( )
# Loop over h time periods
for t in range ( 0 , h ) :
if self . ar != 0 :
Y_exp_normalized = ( Y_exp [ - self . ar : ] [ : : - 1 ] - self . _norm_mean ) / self . _norm_std
new_value = self . predict_new ( np . append ( 1.0 , Y_exp_normalized ) , ... |
def _process_prb_strain_genotype_view ( self , limit = None ) :
"""Here we fetch the free text descriptions of the phenotype associations .
Triples :
< annot _ id > dc : description " description text "
: param limit :
: return :""" | line_counter = 0
if self . test_mode :
graph = self . testgraph
else :
graph = self . graph
LOG . info ( "Getting genotypes for strains" )
raw = '/' . join ( ( self . rawdir , 'prb_strain_genotype_view' ) )
with open ( raw , 'r' , encoding = "utf8" ) as csvfile :
filereader = csv . reader ( csvfile , delimi... |
def from_networkx ( cls , graph , weight = 'weight' ) :
r"""Import a graph from NetworkX .
Edge weights are retrieved as an edge attribute ,
under the name specified by the ` ` weight ` ` parameter .
Signals are retrieved from node attributes ,
and stored in the : attr : ` signals ` dictionary under the att... | nx = _import_networkx ( )
from . graph import Graph
adjacency = nx . to_scipy_sparse_matrix ( graph , weight = weight )
graph_pg = Graph ( adjacency )
for i , node in enumerate ( graph . nodes ( ) ) :
for name in graph . nodes [ node ] . keys ( ) :
try :
signal = graph_pg . signals [ name ]
... |
def targets_by_artifact_set ( self , targets ) :
"""Partitions the input targets by the sets of pinned artifacts they are managed by .
: param collections . Iterable targets : the input targets ( typically just JarLibrary targets ) .
: return : a mapping of PinnedJarArtifactSet - > list of targets .
: rtype :... | sets_to_targets = defaultdict ( list )
for target in targets :
sets_to_targets [ self . for_target ( target ) ] . append ( target )
return dict ( sets_to_targets ) |
def create_autosummary_file ( modules , opts ) : # type : ( List [ unicode ] , Any , unicode ) - > None
"""Create the module ' s index .""" | lines = [ 'API Reference' , '=============' , '' , '.. autosummary::' , ' :template: api_module.rst' , ' :toctree: {}' . format ( opts . destdir ) , '' , ]
modules . sort ( )
for module in modules :
lines . append ( ' {}' . format ( module ) )
lines . append ( '' )
fname = path . join ( opts . srcdir , '{}.rs... |
def run_from_argv ( self , argv ) :
"""Overriden in order to access the command line arguments .""" | self . argv_string = ' ' . join ( argv )
super ( EmailNotificationCommand , self ) . run_from_argv ( argv ) |
def _initialize_pop ( self , pop_size ) :
"""Assigns indices to individuals in population .""" | self . toolbox . register ( "individual" , self . _generate )
self . toolbox . register ( "population" , tools . initRepeat , list , self . toolbox . individual )
self . population = self . toolbox . population ( n = pop_size )
self . assign_fitnesses ( self . population )
self . _model_count += len ( self . population... |
def close ( self ) :
'''Closes the CDF Class .
1 . If compression was set , this is where the compressed file is
written .
2 . If a checksum is needed , this will place the checksum at the end
of the file .''' | if self . compressed_file is None :
with self . path . open ( 'rb+' ) as f :
f . seek ( 0 , 2 )
eof = f . tell ( )
self . _update_offset_value ( f , self . gdr_head + 36 , 8 , eof )
if self . checksum :
f . write ( self . _md5_compute ( f ) )
return
with self . path .... |
def configure ( self , cnf = { } , ** kw ) :
"""Configure resources of the widget .
To get the list of options for this widget , call the method : meth : ` ~ TickScale . keys ` .
See : meth : ` ~ TickScale . _ _ init _ _ ` for a description of the widget specific option .""" | kw . update ( cnf )
reinit = False
if 'orient' in kw :
if kw [ 'orient' ] == 'vertical' :
self . _style_name = self . _style_name . replace ( 'Horizontal' , 'Vertical' )
if 'tickpos' not in kw :
self . _tickpos = 'w'
else :
self . _style_name = self . _style_name . replace ( ... |
def GetAlias ( session = None ) :
"""Return specified alias or if none the alias associated with the provided credentials .
> > > clc . v2 . Account . GetAlias ( )
u ' BTDI '""" | if session is not None :
return session [ 'alias' ]
if not clc . ALIAS :
clc . v2 . API . _Login ( )
return ( clc . ALIAS ) |
def run_dot ( dot ) :
"""Converts a graph in DOT format into an IPython displayable object .""" | global impl
if impl is None :
impl = guess_impl ( )
if impl == "dot" :
return run_dot_dot ( dot )
elif impl == "js" :
return run_dot_js ( dot )
else :
raise ValueError ( "unknown implementation {}" . format ( impl ) ) |
def options ( argv = [ ] ) :
"""A helper function that returns a dictionary of the default key - values pairs""" | parser = HendrixOptionParser
parsed_args = parser . parse_args ( argv )
return vars ( parsed_args [ 0 ] ) |
def error_unzip_helper ( values , func , func_kwargs ) :
'''Splits [ ( x1 , y1 ) , ( x2 , y2 ) , . . . ] and gives to func''' | x_values = [ x for x , y in values ]
y_values = [ y for x , y in values ]
result = func ( x_values , y_values , ** func_kwargs )
if isinstance ( result , float ) :
return result
else :
return result [ 0 ] |
def filter ( self , * args , ** kwargs ) :
"""Adds WHERE arguments to the queryset , returning a new queryset
# TODO : show examples
: rtype : AbstractQuerySet""" | # add arguments to the where clause filters
if len ( [ x for x in kwargs . values ( ) if x is None ] ) :
raise CQLEngineException ( "None values on filter are not allowed" )
clone = copy . deepcopy ( self )
for operator in args :
if not isinstance ( operator , WhereClause ) :
raise QueryException ( '{} ... |
def getPorts ( self ) :
"""acquire ports to be used by the SC2 client launched by this process""" | if self . ports : # no need to get ports if ports are al
return self . ports
if not self . _gotPorts :
self . ports = [ portpicker . pick_unused_port ( ) , # game _ port
portpicker . pick_unused_port ( ) , # base _ port
portpicker . pick_unused_port ( ) , # shared _ port / init port
]
self . _go... |
def _extract_cause ( cls , exc_val ) :
"""Helper routine to extract nested cause ( if any ) .""" | # See : https : / / www . python . org / dev / peps / pep - 3134 / for why / what
# these are . . .
# ' _ _ cause _ _ ' attribute for explicitly chained exceptions
# ' _ _ context _ _ ' attribute for implicitly chained exceptions
# ' _ _ traceback _ _ ' attribute for the traceback
# See : https : / / www . python . org... |
def get_distance_function ( distance ) :
"""Returns the distance function from the string name provided
: param distance : The string name of the distributions
: return :""" | # If we provided distance function ourselves , use it
if callable ( distance ) :
return distance
try :
return _supported_distances_lookup ( ) [ distance ]
except KeyError :
raise KeyError ( 'Unsupported distance function {0!r}' . format ( distance . lower ( ) ) ) |
def _join_parameters ( base , nxt ) :
"""join parameters from the lhs to the rhs , if compatible .""" | if nxt is None :
return base
if isinstance ( base , set ) and isinstance ( nxt , set ) :
return base | nxt
else :
return nxt |
def error_response ( self , kwargs_lens , kwargs_ps ) :
"""returns the 1d array of the error estimate corresponding to the data response
: return : 1d numpy array of response , 2d array of additonal errors ( e . g . point source uncertainties )""" | model_error = self . error_map ( kwargs_lens , kwargs_ps )
error_map_1d = self . ImageNumerics . image2array ( model_error )
C_D_response = self . ImageNumerics . C_D_response + error_map_1d
return C_D_response , model_error |
def complement_alleles ( self ) :
"""Complement the alleles of this variant .
This will call this module ' s ` complement _ alleles ` function .
Note that this will not create a new object , but modify the state of
the current instance .""" | self . alleles = self . _encode_alleles ( [ complement_alleles ( i ) for i in self . alleles ] ) |
def _url_collapse_path ( path ) :
"""Given a URL path , remove extra ' / ' s and ' . ' path elements and collapse
any ' . . ' references and returns a colllapsed path .
Implements something akin to RFC - 2396 5.2 step 6 to parse relative paths .
The utility of this function is limited to is _ cgi method and h... | # Similar to os . path . split ( os . path . normpath ( path ) ) but specific to URL
# path semantics rather than local operating system semantics .
path_parts = path . split ( '/' )
head_parts = [ ]
for part in path_parts [ : - 1 ] :
if part == '..' :
head_parts . pop ( )
# IndexError if more ' . .... |
def copy_data ( self , project , logstore , from_time , to_time = None , to_client = None , to_project = None , to_logstore = None , shard_list = None , batch_size = None , compress = None , new_topic = None , new_source = None ) :
"""copy data from one logstore to another one ( could be the same or in different re... | return copy_data ( self , project , logstore , from_time , to_time = to_time , to_client = to_client , to_project = to_project , to_logstore = to_logstore , shard_list = shard_list , batch_size = batch_size , compress = compress , new_topic = new_topic , new_source = new_source ) |
def _get_named_graph ( context ) :
"""Returns the named graph for this context .""" | if context is None :
return None
return models . NamedGraph . objects . get_or_create ( identifier = context . identifier ) [ 0 ] |
def _split_response ( self , data ) :
"""_ split _ response : binary data - > { ' id ' : str ,
' param ' : binary data ,
_ split _ response takes a data packet received from an XBee device
and converts it into a dictionary . This dictionary provides
names for each segment of binary data as specified in the ... | # Fetch the first byte , identify the packet
# If the spec doesn ' t exist , raise exception
packet_id = data [ 0 : 1 ]
try :
packet = self . api_responses [ packet_id ]
except AttributeError :
raise NotImplementedError ( "API response specifications could not " "be found; use a derived class which " "defines '... |
def create_signed_url ( self , url , keypair_id , expire_time = None , valid_after_time = None , ip_address = None , policy_url = None , private_key_file = None , private_key_string = None ) :
"""Creates a signed CloudFront URL that is only valid within the specified
parameters .
: type url : str
: param url ... | # Get the required parameters
params = self . _create_signing_params ( url = url , keypair_id = keypair_id , expire_time = expire_time , valid_after_time = valid_after_time , ip_address = ip_address , policy_url = policy_url , private_key_file = private_key_file , private_key_string = private_key_string )
# combine the... |
def nearest_point ( query , root_id , get_properties , dist_fun = euclidean_dist ) :
"""Find the point in the tree that minimizes the distance to the query .
This method implements the nearest _ point query for any structure
implementing a kd - tree . The only requirement is a function capable to
extract the ... | k = len ( query )
dist = math . inf
nearest_node_id = None
# stack _ node : stack of identifiers to nodes within a region that
# contains the query .
# stack _ look : stack of identifiers to nodes within a region that
# does not contains the query .
stack_node = deque ( [ root_id ] )
stack_look = deque ( )
while stack_... |
def get_TRM_star ( C , ptrms_vectors , start , end ) :
"""input : C , ptrms _ vectors , start , end
output : TRM _ star , x _ star ( for delta _ pal statistic )""" | TRM_star = numpy . zeros ( [ len ( ptrms_vectors ) , 3 ] )
TRM_star [ 0 ] = [ 0. , 0. , 0. ]
x_star = numpy . zeros ( len ( ptrms_vectors ) )
for num , vec in enumerate ( ptrms_vectors [ 1 : ] ) :
TRM_star [ num + 1 ] = vec + C [ num ]
# print ' vec ' , vec
# print ' C ' , C [ num ]
for num , trm in enumerate ( TRM... |
def normalize ( vectors ) :
"""Normalize a matrix of row vectors to unit length .
Contains a shortcut if there are no zero vectors in the matrix .
If there are zero vectors , we do some indexing tricks to avoid
dividing by 0.
Parameters
vectors : np . array
The vectors to normalize .
Returns
vectors... | if np . ndim ( vectors ) == 1 :
norm = np . linalg . norm ( vectors )
if norm == 0 :
return np . zeros_like ( vectors )
return vectors / norm
norm = np . linalg . norm ( vectors , axis = 1 )
if np . any ( norm == 0 ) :
nonzero = norm > 0
result = np . zeros_like ( vectors )
n = norm [ no... |
def get_token_details ( self , show_listing_details = False , show_inactive = False ) :
"""Function to fetch the available tokens available to trade on the Switcheo exchange .
Execution of this function is as follows : :
get _ token _ details ( )
get _ token _ details ( show _ listing _ details = True )
get... | api_params = { "show_listing_details" : show_listing_details , "show_inactive" : show_inactive }
return self . request . get ( path = '/exchange/tokens' , params = api_params ) |
def get_port_bindings ( container_config , client_config ) :
"""Generates the input dictionary contents for the ` ` port _ bindings ` ` argument .
: param container _ config : Container configuration .
: type container _ config : dockermap . map . config . container . ContainerConfiguration
: param client _ c... | port_bindings = { }
if_ipv4 = client_config . interfaces
if_ipv6 = client_config . interfaces_ipv6
for exposed_port , ex_port_bindings in itertools . groupby ( sorted ( container_config . exposes , key = _get_ex_port ) , _get_ex_port ) :
bind_list = list ( _get_port_bindings ( ex_port_bindings , if_ipv4 , if_ipv6 )... |
def path ( self ) :
"""Absolute path to the directory on the camera ' s filesystem .""" | if self . parent is None :
return "/"
else :
return os . path . join ( self . parent . path , self . name ) |
def open_scene ( f , kwargs = None ) :
"""Opens the given JB _ File
: param f : the file to open
: type f : : class : ` jukeboxcore . filesys . JB _ File `
: param kwargs : keyword arguments for the command maya . cmds file .
defaultflags that are always used :
: open : ` ` True ` `
e . g . to force the... | defaultkwargs = { 'open' : True }
if kwargs is None :
kwargs = { }
kwargs . update ( defaultkwargs )
fp = f . get_fullpath ( )
mayafile = cmds . file ( fp , ** kwargs )
msg = "Successfully opened file %s with arguments: %s" % ( fp , kwargs )
return ActionStatus ( ActionStatus . SUCCESS , msg , returnvalue = mayafil... |
def focal ( self ) :
"""Get the focal length in pixels for the camera .
Returns
focal : ( 2 , ) float
Focal length in pixels""" | if self . _focal is None : # calculate focal length from FOV
focal = [ ( px / 2.0 ) / np . tan ( np . radians ( fov / 2.0 ) ) for px , fov in zip ( self . _resolution , self . fov ) ]
# store as correct dtype
self . _focal = np . asanyarray ( focal , dtype = np . float64 )
return self . _focal |
def compile ( self , X , verbose = False ) :
"""method to validate and prepare data - dependent parameters
Parameters
X : array - like
Input dataset
verbose : bool
whether to show warnings
Returns
None""" | for term in self . _terms :
term . compile ( X , verbose = False )
if self . by is not None and self . by >= X . shape [ 1 ] :
raise ValueError ( 'by variable requires feature {}, ' 'but X has only {} dimensions' . format ( self . by , X . shape [ 1 ] ) )
return self |
def generate_listall_output ( lines , resources , aws_config , template , arguments , nodup = False ) :
"""Format and print the output of ListAll
: param lines :
: param resources :
: param aws _ config :
: param template :
: param arguments :
: param nodup :
: return :""" | for line in lines :
output = [ ]
for resource in resources :
current_path = resource . split ( '.' )
outline = line [ 1 ]
for key in line [ 2 ] :
outline = outline . replace ( '_KEY_(' + key + ')' , get_value_at ( aws_config [ 'services' ] , current_path , key , True ) )
... |
def manual ( cls , node , tval , ns = None ) :
"""Set the node ' s xsi : type attribute based on either I { value } ' s or the
node text ' s class . Then adds the referenced prefix ( s ) to the node ' s
prefix mapping .
@ param node : XML node .
@ type node : L { sax . element . Element }
@ param tval : X... | xta = ":" . join ( ( Namespace . xsins [ 0 ] , "type" ) )
node . addPrefix ( Namespace . xsins [ 0 ] , Namespace . xsins [ 1 ] )
if ns is None :
node . set ( xta , tval )
else :
ns = cls . genprefix ( node , ns )
qname = ":" . join ( ( ns [ 0 ] , tval ) )
node . set ( xta , qname )
node . addPrefix ... |
def disable_paging ( self , command = "terminal length 999" , delay_factor = 1 ) :
"""Disable paging default to a Cisco CLI method .""" | delay_factor = self . select_delay_factor ( delay_factor )
time . sleep ( delay_factor * 0.1 )
self . clear_buffer ( )
command = self . normalize_cmd ( command )
log . debug ( "In disable_paging" )
log . debug ( "Command: {0}" . format ( command ) )
self . write_channel ( command )
output = self . read_until_prompt ( )... |
def _pipe_stdio ( cls , sock , stdin_isatty , stdout_isatty , stderr_isatty , handle_stdin ) :
"""Handles stdio redirection in the case of pipes and / or mixed pipes and ttys .""" | stdio_writers = ( ( ChunkType . STDOUT , stdout_isatty ) , ( ChunkType . STDERR , stderr_isatty ) )
types , ttys = zip ( * ( stdio_writers ) )
@ contextmanager
def maybe_handle_stdin ( want ) :
if want : # TODO : Launching this thread pre - fork to handle @ rule input currently results
# in an unhandled SIGILL ... |
def cira_stretch ( img , ** kwargs ) :
"""Logarithmic stretch adapted to human vision .
Applicable only for visible channels .""" | LOG . debug ( "Applying the cira-stretch" )
def func ( band_data ) :
log_root = np . log10 ( 0.0223 )
denom = ( 1.0 - log_root ) * 0.75
band_data *= 0.01
band_data = band_data . clip ( np . finfo ( float ) . eps )
band_data = xu . log10 ( band_data )
band_data -= log_root
band_data /= denom
... |
def get_logging_dir ( appname = 'default' ) :
"""The default log dir is in the system resource directory
But the utool global cache allows for the user to override
where the logs for a specific app should be stored .
Returns :
log _ dir _ realpath ( str ) : real path to logging directory""" | from utool . _internal import meta_util_cache
from utool . _internal import meta_util_cplat
from utool import util_cache
if appname is None or appname == 'default' :
appname = util_cache . get_default_appname ( )
resource_dpath = meta_util_cplat . get_resource_dir ( )
default = join ( resource_dpath , appname , 'lo... |
def _filter_orientdb_simple_optional_edge ( query_metadata_table , optional_edge_location , inner_location_name ) :
"""Return an Expression that is False for rows that don ' t follow the @ optional specification .
OrientDB does not filter correctly within optionals . Namely , a result where the optional edge
DO... | inner_local_field = LocalField ( inner_location_name )
inner_location_existence = BinaryComposition ( u'!=' , inner_local_field , NullLiteral )
# The optional _ edge _ location here is actually referring to the edge field itself .
# This is definitely non - standard , but required to get the proper semantics .
# To get... |
def logpdf ( self , mu ) :
"""Log PDF for Laplace prior
Parameters
mu : float
Latent variable for which the prior is being formed over
Returns
- log ( p ( mu ) )""" | if self . transform is not None :
mu = self . transform ( mu )
return ss . laplace . logpdf ( mu , loc = self . loc0 , scale = self . scale0 ) |
def import_from_json ( self , data ) :
"""Replace the current roster with the : meth : ` export _ as _ json ` - compatible
dictionary in ` data ` .
No events are fired during this activity . After this method completes ,
the whole roster contents are exchanged with the contents from ` data ` .
Also , no dat... | self . version = data . get ( "ver" , None )
self . items . clear ( )
self . groups . clear ( )
for jid , data in data . get ( "items" , { } ) . items ( ) :
jid = structs . JID . fromstr ( jid )
item = Item ( jid )
item . update_from_json ( data )
self . items [ jid ] = item
for group in item . grou... |
def _set_get_flexports ( self , v , load = False ) :
"""Setter method for get _ flexports , mapped from YANG variable / brocade _ hardware _ rpc / get _ flexports ( rpc )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ get _ flexports is considered as a private
method... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = get_flexports . get_flexports , is_leaf = True , yang_name = "get-flexports" , rest_name = "get-flexports" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = False , exten... |
def run ( cmd , env = None , return_object = False , block = True , cwd = None , verbose = False , nospin = False , spinner_name = None , combine_stderr = True , display_limit = 200 , write_to_stdout = True , ) :
"""Use ` subprocess . Popen ` to get the output of a command and decode it .
: param list cmd : A lis... | _env = os . environ . copy ( )
if env :
_env . update ( env )
if six . PY2 :
fs_encode = partial ( to_bytes , encoding = locale_encoding )
_env = { fs_encode ( k ) : fs_encode ( v ) for k , v in _env . items ( ) }
else :
_env = { k : fs_str ( v ) for k , v in _env . items ( ) }
if not spinner_name :
... |
def ParseOptions ( self , options ) :
"""Parses tool specific options .
Args :
options ( argparse . Namespace ) : command line arguments .
Raises :
BadConfigOption : if the options are invalid .""" | # The extraction options are dependent on the data location .
helpers_manager . ArgumentHelperManager . ParseOptions ( options , self , names = [ 'data_location' ] )
self . _ReadParserPresetsFromFile ( )
# The output modules options are dependent on the preferred language
# and preferred time zone options .
self . _Par... |
def _get_text ( self , text ) :
"""Returns the text content of ` text ` , with all multi - character tokens
replaced with a single character . Substitutions are recorded
in self . _ substitutes .
: param text : text to get content from
: type text : ` Text `
: rtype : ` str `""" | tokens = text . get_tokens ( )
for i , token in enumerate ( tokens ) :
if len ( token ) > 1 :
char = chr ( self . _char_code )
substitute = self . _substitutes . setdefault ( token , char )
if substitute == char :
self . _char_code += 1
tokens [ i ] = substitute
return se... |
def authenticate ( self , request ) :
"""Authenticate a client against all the backends configured in
: attr : ` authentication ` .""" | for backend in self . authentication :
client = backend ( ) . authenticate ( request )
if client is not None :
return client
return None |
def wait_for_stable_cluster ( hosts , jolokia_port , jolokia_prefix , check_interval , check_count , unhealthy_time_limit , ) :
"""Block the caller until the cluster can be considered stable .
: param hosts : list of brokers ip addresses
: type hosts : list of strings
: param jolokia _ port : HTTP port for Jo... | stable_counter = 0
max_checks = int ( math . ceil ( unhealthy_time_limit / check_interval ) )
for i in itertools . count ( ) :
partitions , brokers = read_cluster_status ( hosts , jolokia_port , jolokia_prefix , )
if partitions or brokers :
stable_counter = 0
else :
stable_counter += 1
p... |
def reduce ( self , values , inplace = True ) :
"""Reduces the distribution to the context of the given variable values .
Let C ( X , Y ; K , h , g ) be some canonical form over X , Y where ,
k = [ [ K _ XX , K _ XY ] , ; h = [ [ h _ X ] ,
[ K _ YX , K _ YY ] ] [ h _ Y ] ]
The formula for the obtained condi... | if not isinstance ( values , ( list , tuple , np . ndarray ) ) :
raise TypeError ( "variables: Expected type list or array-like, " "got type {var_type}" . format ( var_type = type ( values ) ) )
if not all ( [ var in self . variables for var , value in values ] ) :
raise ValueError ( "Variable not in scope." )
... |
def _generate_phrases ( self , sentences ) :
"""Method to generate contender phrases given the sentences of the text
document .
: param sentences : List of strings where each string represents a
sentence which forms the text .
: return : Set of string tuples where each tuple is a collection
of words formi... | phrase_list = set ( )
# Create contender phrases from sentences .
for sentence in sentences :
word_list = [ word . lower ( ) for word in wordpunct_tokenize ( sentence ) ]
phrase_list . update ( self . _get_phrase_list_from_words ( word_list ) )
return phrase_list |
def sim_givenAdj ( self , Adj : np . array , model = 'line' ) :
"""Simulate data given only an adjacancy matrix and a model .
The model is a bivariate funtional dependence . The adjacancy matrix
needs to be acyclic .
Parameters
Adj
adjacancy matrix of shape ( dim , dim ) .
Returns
Data array of shape ... | # nice examples
examples = [ { 'func' : 'sawtooth' , 'gdist' : 'uniform' , 'sigma_glob' : 1.8 , 'sigma_noise' : 0.1 } ]
# nr of samples
n_samples = 100
# noise
sigma_glob = 1.8
sigma_noise = 0.4
# coupling function / model
func = self . funcs [ model ]
# glob distribution
sourcedist = 'uniform'
# loop over source nodes... |
def onlasso ( self , verts ) :
"""Main function to control the action of the lasso , allows user to draw on data image and adjust thematic map
: param verts : the vertices selected by the lasso
: return : nothin , but update the selection array so lassoed region now has the selected theme , redraws canvas""" | p = path . Path ( verts )
ind = p . contains_points ( self . pix , radius = 1 )
self . history . append ( self . selection_array . copy ( ) )
self . selection_array = self . updateArray ( self . selection_array , ind , self . solar_class_var . get ( ) )
self . mask . set_data ( self . selection_array )
self . fig . can... |
def from_html_one ( html_code , ** kwargs ) :
"""Generates a PrettyTables from a string of HTML code which contains only a
single < table >""" | tables = from_html ( html_code , ** kwargs )
try :
assert len ( tables ) == 1
except AssertionError :
raise Exception ( "More than one <table> in provided HTML code! Use from_html instead." )
return tables [ 0 ] |
def list ( self , status = values . unset , iccid = values . unset , rate_plan = values . unset , e_id = values . unset , sim_registration_code = values . unset , limit = None , page_size = None ) :
"""Lists SimInstance records from the API as a list .
Unlike stream ( ) , this operation is eager and will load ` l... | return list ( self . stream ( status = status , iccid = iccid , rate_plan = rate_plan , e_id = e_id , sim_registration_code = sim_registration_code , limit = limit , page_size = page_size , ) ) |
def zip ( self , other ) :
"""zips two sequences unifying the corresponding points .""" | return self . __class__ ( p1 % p2 for p1 , p2 in zip ( self , other ) ) |
def check_dir ( directory , newly_created_files ) :
"""Returns list of files that fail the check .""" | header_parse_failures = [ ]
for root , dirs , files in os . walk ( directory ) :
for f in files :
if f . endswith ( '.py' ) and os . path . basename ( f ) != '__init__.py' :
filename = os . path . join ( root , f )
try :
check_header ( filename , filename in newly_cre... |
def get ( path , objectType , user = None ) :
'''Get the ACL of an object . Will filter by user if one is provided .
Args :
path : The path to the object
objectType : The type of object ( FILE , DIRECTORY , REGISTRY )
user : A user name to filter by
Returns ( dict ) : A dictionary containing the ACL
CLI... | ret = { 'Path' : path , 'ACLs' : [ ] }
sidRet = _getUserSid ( user )
if path and objectType :
dc = daclConstants ( )
objectTypeBit = dc . getObjectTypeBit ( objectType )
path = dc . processPath ( path , objectTypeBit )
tdacl = _get_dacl ( path , objectTypeBit )
if tdacl :
for counter in rang... |
def EnumType ( enum_class , nested_type = _Undefined , ** kwargs ) :
"""Create and return a : class : ` EnumCDataType ` or : class : ` EnumElementType ` ,
depending on the type of ` nested _ type ` .
If ` nested _ type ` is a : class : ` AbstractCDataType ` or omitted , a
: class : ` EnumCDataType ` is constr... | if nested_type is _Undefined :
return EnumCDataType ( enum_class , ** kwargs )
if isinstance ( nested_type , AbstractCDataType ) :
return EnumCDataType ( enum_class , nested_type , ** kwargs )
else :
return EnumElementType ( enum_class , nested_type , ** kwargs ) |
def luminance ( mycolour ) :
r"""Determine ( relative ) luminance of a colour .
Args :
mycolour ( colourettu . Colour ) : a colour
Luminance is a measure of how ' bright ' a colour is . Values are
normalized so that the Luminance of White is 1 and the Luminance of
Black is 0 . That is to say :
. . code ... | colour_for_type = Colour ( )
if type ( mycolour ) is type ( colour_for_type ) :
mycolour2 = mycolour
else :
try :
mycolour2 = Colour ( mycolour )
except :
raise TypeError ( "Must supply a colourettu.Colour" )
( r1 , g1 , b1 ) = mycolour2 . normalized_rgb ( )
return math . sqrt ( 0.299 * math... |
def verify_password ( self , user , password ) :
"""Returns ` ` True ` ` if the password is valid for the specified user .
Additionally , the hashed password in the database is updated if the
hashing algorithm happens to have changed .
: param user : The user to verify against
: param password : The plainte... | if self . use_double_hash ( user . password ) :
verified = self . security . pwd_context . verify ( self . get_hmac ( password ) , user . password )
else : # Try with original password .
verified = self . security . pwd_context . verify ( password , user . password )
if verified and self . security . pwd_contex... |
def _GetUrl ( self , url_id , cache , database ) :
"""Retrieves an URL from a reference to an entry in the from _ visit table .
Args :
url _ id ( str ) : identifier of the visited URL .
cache ( SQLiteCache ) : cache .
database ( SQLiteDatabase ) : database .
Returns :
str : URL and hostname .""" | url_cache_results = cache . GetResults ( 'url' )
if not url_cache_results :
result_set = database . Query ( self . URL_CACHE_QUERY )
cache . CacheQueryResults ( result_set , 'url' , 'id' , ( 'url' , 'rev_host' ) )
url_cache_results = cache . GetResults ( 'url' )
url , reverse_host = url_cache_results . get ... |
def lab_to_xyz ( l , a = None , b = None , wref = _DEFAULT_WREF ) :
"""Convert the color from CIE L * a * b * to CIE 1931 XYZ .
Parameters :
The L component [ 0 . . . 100]
The a component [ - 1 . . . 1]
The a component [ - 1 . . . 1]
: wref :
The whitepoint reference , default is 2 ° D65.
Returns :
... | if type ( l ) in [ list , tuple ] :
l , a , b = l
y = ( l + 16 ) / 116
x = ( a / 5.0 ) + y
z = y - ( b / 2.0 )
return tuple ( ( ( ( v > 0.206893 ) and [ v ** 3 ] or [ ( v - _sixteenHundredsixteenth ) / 7.787 ] ) [ 0 ] * w for v , w in zip ( ( x , y , z ) , wref ) ) ) |
def add_email_addresses ( self , addresses = [ ] ) :
"""Add the email addresses in ` ` addresses ` ` to the authenticated
user ' s account .
: param list addresses : ( optional ) , email addresses to be added
: returns : list of email addresses""" | json = [ ]
if addresses :
url = self . _build_url ( 'user' , 'emails' )
json = self . _json ( self . _post ( url , data = addresses ) , 201 )
return json |
def wage ( return_X_y = True ) :
"""wage dataset
Parameters
return _ X _ y : bool ,
if True , returns a model - ready tuple of data ( X , y )
otherwise , returns a Pandas DataFrame
Returns
model - ready tuple of data ( X , y )
OR
Pandas DataFrame
Notes
X contains the year , age and education of ... | # y is real
# recommend LinearGAM
wage = pd . read_csv ( PATH + '/wage.csv' , index_col = 0 )
if return_X_y :
X = wage [ [ 'year' , 'age' , 'education' ] ] . values
X [ : , - 1 ] = np . unique ( X [ : , - 1 ] , return_inverse = True ) [ 1 ]
y = wage [ 'wage' ] . values
return _clean_X_y ( X , y )
return... |
def rfcformat ( dt , localtime = False ) :
"""Return the RFC822 - formatted representation of a datetime object .
: param datetime dt : The datetime .
: param bool localtime : If ` ` True ` ` , return the date relative to the local
timezone instead of UTC , displaying the proper offset ,
e . g . " Sun , 10 ... | if not localtime :
return formatdate ( timegm ( dt . utctimetuple ( ) ) )
else :
return local_rfcformat ( dt ) |
def predict ( self , name , payload , params = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Perform an online prediction . The prediction result will be directly
returned in the response . Available for follow... | # Wrap the transport method to add retry and timeout logic .
if "predict" not in self . _inner_api_calls :
self . _inner_api_calls [ "predict" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . predict , default_retry = self . _method_configs [ "Predict" ] . retry , default_timeout = self ... |
def _get_file_creation_time ( file_path ) :
"""Returns the creation time of the file at the specified file path in Microsoft FILETIME
structure format ( https : / / msdn . microsoft . com / en - us / library / windows / desktop / ms724284 . aspx ) ,
formatted as a 8 - byte unsigned integer bytearray .""" | ctime = getctime ( file_path )
if ctime < - 11644473600 or ctime >= 253402300800 :
raise FileTimeOutOfRangeException ( ctime )
creation_time_datetime = datetime . utcfromtimestamp ( ctime )
creation_time_epoch_offset = creation_time_datetime - datetime ( 1601 , 1 , 1 )
creation_time_secs_from_epoch = _convert_timed... |
def _comparator_approximate ( filter_value , tested_value ) :
"""Tests if the filter value is nearly equal to the tested value .
If the tested value is a string or an array of string , it compares their
lower case forms""" | lower_filter_value = filter_value . lower ( )
if is_string ( tested_value ) : # Lower case comparison
return _comparator_eq ( lower_filter_value , tested_value . lower ( ) )
elif hasattr ( tested_value , "__iter__" ) : # Extract a list of strings
new_tested = [ value . lower ( ) for value in tested_value if is_... |
def _fix_up_fields ( cls ) :
"""Add names to all of the Endpoint ' s Arguments .
This method will get called on class declaration because of
Endpoint ' s metaclass . The functionality is based on Google ' s NDB
implementation .""" | cls . _arguments = dict ( )
if cls . __module__ == __name__ : # skip the classes in this file
return
for name in set ( dir ( cls ) ) :
attr = getattr ( cls , name , None )
if isinstance ( attr , BaseArgument ) :
if name . startswith ( '_' ) :
raise TypeError ( "Endpoint argument %s canno... |
def add_parameters ( self , template_file , in_file = None , pst_path = None ) :
"""add new parameters to a control file
Parameters
template _ file : str
template file
in _ file : str ( optional )
model input file . If None , template _ file . replace ( ' . tpl ' , ' ' ) is used
pst _ path : str ( optio... | assert os . path . exists ( template_file ) , "template file '{0}' not found" . format ( template_file )
assert template_file != in_file
# get the parameter names in the template file
parnme = pst_utils . parse_tpl_file ( template_file )
# find " new " parameters that are not already in the control file
new_parnme = [ ... |
def StartsWith ( self , value ) :
"""Sets the type of the WHERE clause as " starts with " .
Args :
value : The value to be used in the WHERE condition .
Returns :
The query builder that this WHERE builder links to .""" | self . _awql = self . _CreateSingleValueCondition ( value , 'STARTS_WITH' )
return self . _query_builder |
def _eap_check_config ( eap_config : Dict [ str , Any ] ) -> Dict [ str , Any ] :
"""Check the eap specific args , and replace values where needed .
Similar to _ check _ configure _ args but for only EAP .""" | eap_type = eap_config . get ( 'eapType' )
for method in EAP_CONFIG_SHAPE [ 'options' ] :
if method [ 'name' ] == eap_type :
options = method [ 'options' ]
break
else :
raise ConfigureArgsError ( 'EAP method {} is not valid' . format ( eap_type ) )
_eap_check_no_extra_args ( eap_config , options ... |
def _get_heading_level ( self , element ) :
"""Returns the level of heading .
: param element : The heading .
: type element : hatemile . util . html . htmldomelement . HTMLDOMElement
: return : The level of heading .
: rtype : int""" | # pylint : disable = no - self - use
tag = element . get_tag_name ( )
if tag == 'H1' :
return 1
elif tag == 'H2' :
return 2
elif tag == 'H3' :
return 3
elif tag == 'H4' :
return 4
elif tag == 'H5' :
return 5
elif tag == 'H6' :
return 6
return - 1 |
def validate_gps ( value ) :
"""Validate GPS value .""" | try :
latitude , longitude , altitude = value . split ( ',' )
vol . Coerce ( float ) ( latitude )
vol . Coerce ( float ) ( longitude )
vol . Coerce ( float ) ( altitude )
except ( TypeError , ValueError , vol . Invalid ) :
raise vol . Invalid ( 'GPS value should be of format "latitude,longitude,alti... |
def keep_resample ( nkeep , X_train , y_train , X_test , y_test , attr_test , model_generator , metric , trained_model , random_state ) :
"""The model is revaluated for each test sample with the non - important features set to resample background values .""" | # why broken ? overwriting ?
X_train , X_test = to_array ( X_train , X_test )
# how many features to mask
assert X_train . shape [ 1 ] == X_test . shape [ 1 ]
# how many samples to take
nsamples = 100
# keep nkeep top features for each test explanation
N , M = X_test . shape
X_test_tmp = np . tile ( X_test , [ 1 , nsam... |
def _get_linewise_report ( self ) :
"""Returns a report each line of which comprises a pair of an input line
and an error . Unlike in the standard report , errors will appear as many
times as they occur .
Helper for the get _ report method .""" | d = defaultdict ( list )
# line : [ ] of errors
for error , lines in self . errors . items ( ) :
for line_num in lines :
d [ line_num ] . append ( error )
return '\n' . join ( [ '{:>3} → {}' . format ( line , error . string ) for line in sorted ( d . keys ( ) ) for error in d [ line ] ] ) |
def topological_sort ( dag ) :
"""topological sort
: param dag : directed acyclic graph
: type dag : dict
. . seealso : : ` Topographical Sorting
< http : / / en . wikipedia . org / wiki / Topological _ sorting > ` _ ,
` Directed Acyclic Graph ( DAG )
< https : / / en . wikipedia . org / wiki / Directed... | # find all edges of dag
topsort = [ node for node , edge in dag . iteritems ( ) if not edge ]
# loop through nodes until topologically sorted
while len ( topsort ) < len ( dag ) :
num_nodes = len ( topsort )
# number of nodes
# unsorted nodes
for node in dag . viewkeys ( ) - set ( topsort ) : # nodes wi... |
def delete ( self ) :
"""Delete this key from mist . io
: returns : An updated list of added keys""" | req = self . request ( self . mist_client . uri + '/keys/' + self . id )
req . delete ( )
self . mist_client . update_keys ( ) |
def save ( self , filename ) :
"""Save host keys into a file , in the format used by openssh . The order of
keys in the file will be preserved when possible ( if these keys were
loaded from a file originally ) . The single exception is that combined
lines will be split into individual key lines , which is arg... | f = open ( filename , 'w' )
for e in self . _entries :
line = e . to_line ( )
if line :
f . write ( line )
f . close ( ) |
def clicked ( self , event ) :
"""Call if an element of this plottype is clicked .
Implement in sub class .""" | group = event . artist . _mt_group
indices = event . ind
# double click only supported on 1.2 or later
major , minor , _ = mpl_version . split ( '.' )
if ( int ( major ) , int ( minor ) ) < ( 1 , 2 ) or not event . mouseevent . dblclick :
for i in indices :
print ( self . groups [ group ] [ i ] . line_str )... |
def retry ( num_attempts = 3 , exception_class = Exception , log = None , sleeptime = 1 ) :
"""> > > def fail ( ) :
. . . runs [ 0 ] + = 1
. . . raise ValueError ( )
> > > runs = [ 0 ] ; retry ( sleeptime = 0 ) ( fail ) ( )
Traceback ( most recent call last ) :
ValueError
> > > runs
> > > runs = [ 0 ]... | def decorator ( func ) :
@ functools . wraps ( func )
def wrapper ( * args , ** kwargs ) :
for i in range ( num_attempts ) :
try :
return func ( * args , ** kwargs )
except exception_class as e :
if i == num_attempts - 1 :
raise... |
def basic_diff ( source1 , source2 , start = None , end = None ) :
"""Perform a basic diff between two equal - sized binary strings and
return a list of ( offset , size ) tuples denoting the differences .
source1
The first byte string source .
source2
The second byte string source .
start
Start offset... | start = start if start is not None else 0
end = end if end is not None else min ( len ( source1 ) , len ( source2 ) )
end_point = min ( end , len ( source1 ) , len ( source2 ) )
pointer = start
diff_start = None
results = [ ]
while pointer < end_point :
if source1 [ pointer ] != source2 [ pointer ] :
if dif... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.