Search is not available for this dataset
text stringlengths 75 104k |
|---|
def overlaps(self, other):
"""
check for overlap with the other interval
"""
if self.chrom != other.chrom: return False
if self.start >= other.end: return False
if other.start >= self.end: return False
return True |
def is_upstream_of(self, other):
"""
check if this is upstream of the `other` interval taking the strand of
the other interval into account
"""
if self.chrom != other.chrom: return None
if getattr(other, "strand", None) == "+":
return self.end <= other.start
... |
def distance(self, other_or_start=None, end=None, features=False):
"""
check the distance between this an another interval
Parameters
----------
other_or_start : Interval or int
either an integer or an Interval with a start attribute indicating
the start ... |
def exons(self):
"""
return a list of exons [(start, stop)] for this object if appropriate
"""
# drop the trailing comma
if not self.is_gene_pred: return []
if hasattr(self, "exonStarts"):
try:
starts = (long(s) for s in self.exonStarts[:-1].sp... |
def gene_features(self):
"""
return a list of features for the gene features of this object.
This would include exons, introns, utrs, etc.
"""
nm, strand = self.gene_name, self.strand
feats = [(self.chrom, self.start, self.end, nm, strand, 'gene')]
for feat in ('i... |
def tss(self, up=0, down=0):
"""
Return a start, end tuple of positions around the transcription-start
site
Parameters
----------
up : int
if greature than 0, the strand is used to add this many upstream
bases in the appropriate direction
... |
def promoter(self, up=2000, down=0):
"""
Return a start, end tuple of positions for the promoter region of this
gene
Parameters
----------
up : int
this distance upstream that is considered the promoter
down : int
the strand is used to add... |
def coding_exons(self):
"""
includes the entire exon as long as any of it is > cdsStart and <
cdsEnd
"""
# drop the trailing comma
starts = (long(s) for s in self.exonStarts[:-1].split(","))
ends = (long(s) for s in self.exonEnds[:-1].split(","))
return [(... |
def cds(self):
"""just the parts of the exons that are translated"""
ces = self.coding_exons
if len(ces) < 1: return ces
ces[0] = (self.cdsStart, ces[0][1])
ces[-1] = (ces[-1][0], self.cdsEnd)
assert all((s < e for s, e in ces))
return ces |
def is_downstream_of(self, other):
"""
return a boolean indicating whether this feature is downstream of
`other` taking the strand of other into account
"""
if self.chrom != other.chrom: return None
if getattr(other, "strand", None) == "-":
# other feature is ... |
def features(self, other_start, other_end):
"""
return e.g. "intron;exon" if the other_start, end overlap introns and
exons
"""
# completely encases gene.
if other_start <= self.start and other_end >= self.end:
return ['gene' if self.cdsStart != self.cdsEnd el... |
def upstream(self, distance):
"""
return the (start, end) of the region before the geneStart
"""
if getattr(self, "strand", None) == "+":
e = self.start
s = e - distance
else:
s = self.end
e = s + distance
return self._xstre... |
def utr5(self):
"""
return the 5' UTR if appropriate
"""
if not self.is_coding or len(self.exons) < 2: return (None, None)
if self.strand == "+":
s, e = (self.txStart, self.cdsStart)
else:
s, e = (self.cdsEnd, self.txEnd)
if s == e: return ... |
def sequence(self, per_exon=False):
"""
Return the sequence for this feature.
if per-exon is True, return an array of exon sequences
This sequence is never reverse complemented
"""
db = self.db
if not per_exon:
start = self.txStart + 1
retu... |
def ncbi_blast(self, db="nr", megablast=True, sequence=None):
"""
perform an NCBI blast against the sequence of this feature
"""
import requests
requests.defaults.max_retries = 4
assert sequence in (None, "cds", "mrna")
seq = self.sequence() if sequence is None el... |
def blat(self, db=None, sequence=None, seq_type="DNA"):
"""
make a request to the genome-browsers BLAT interface
sequence is one of None, "mrna", "cds"
returns a list of features that are hits to this sequence.
"""
from . blat_blast import blat, blat_all
assert se... |
def bed(self, *attrs, **kwargs):
"""
return a bed formatted string of this feature
"""
exclude = ("chrom", "start", "end", "txStart", "txEnd", "chromStart",
"chromEnd")
if self.is_gene_pred:
return self.bed12(**kwargs)
return "\t".join(map(str,... |
def bed12(self, score="0", rgb="."):
"""
return a bed12 (http://genome.ucsc.edu/FAQ/FAQformat.html#format1)
representation of this interval
"""
if not self.is_gene_pred:
raise CruzException("can't create bed12 from non genepred feature")
exons = list(self.exon... |
def localize(self, *positions, **kwargs):
"""
convert global coordinate(s) to local taking
introns into account and cds/tx-Start depending on cdna=True kwarg
"""
cdna = kwargs.get('cdna', False)
# TODO: account for strand ?? add kwarg ??
# if it's to the CDNA, the... |
def distance(self, other_or_start=None, end=None, features="unused",
shore_dist=3000):
"""
check the distance between this an another interval
Parameters
----------
other_or_start : Interval or int
either an integer or an Interval with a start attribute i... |
def annotate(g, fname, tables, feature_strand=False, in_memory=False,
header=None, out=sys.stdout, _chrom=None, parallel=False):
"""
annotate bed file in fname with tables.
distances are integers for distance. and intron/exon/utr5 etc for gene-pred
tables. if the annotation features have a stran... |
def entry_point():
"""
External entry point which calls main() and
if Stop is raised, calls sys.exit()
"""
try:
main("omego", items=[
(InstallCommand.NAME, InstallCommand),
(UpgradeCommand.NAME, UpgradeCommand),
(ConvertCommand.NAME, ConvertCommand),
... |
def open_url(url, httpuser=None, httppassword=None, method=None):
"""
Open a URL using an opener that will simulate a browser user-agent
url: The URL
httpuser, httppassword: HTTP authentication credentials (either both or
neither must be provided)
method: The HTTP method
Caller is reponsi... |
def dereference_url(url):
"""
Makes a HEAD request to find the final destination of a URL after
following any redirects
"""
res = open_url(url, method='HEAD')
res.close()
return res.url |
def read(url, **kwargs):
"""
Read the contents of a URL into memory, return
"""
response = open_url(url, **kwargs)
try:
return response.read()
finally:
response.close() |
def download(url, filename=None, print_progress=0, delete_fail=True,
**kwargs):
"""
Download a file, optionally printing a simple progress bar
url: The URL to download
filename: The filename to save to, default is to use the URL basename
print_progress: The length of the progress bar, u... |
def rename_backup(name, suffix='.bak'):
"""
Append a backup prefix to a file or directory, with an increasing numeric
suffix (.N) if a file already exists
"""
newname = '%s%s' % (name, suffix)
n = 0
while os.path.exists(newname):
n += 1
newname = '%s%s.%d' % (name, suffix, n)... |
def timestamp_filename(basename, ext=None):
"""
Return a string of the form [basename-TIMESTAMP.ext]
where TIMESTAMP is of the form YYYYMMDD-HHMMSS-MILSEC
"""
dt = datetime.now().strftime('%Y%m%d-%H%M%S-%f')
if ext:
return '%s-%s.%s' % (basename, dt, ext)
return '%s-%s' % (basename, ... |
def check_extracted_paths(namelist, subdir=None):
"""
Check whether zip file paths are all relative, and optionally in a
specified subdirectory, raises an exception if not
namelist: A list of paths from the zip file
subdir: If specified then check whether all paths in the zip file are
under t... |
def unzip(filename, match_dir=False, destdir=None):
"""
Extract all files from a zip archive
filename: The path to the zip file
match_dir: If True all files in the zip must be contained in a subdirectory
named after the archive file with extension removed
destdir: Extract the zip into this dir... |
def zip(filename, paths, strip_prefix=''):
"""
Create a new zip archive containing files
filename: The name of the zip file to be created
paths: A list of files or directories
strip_dir: Remove this prefix from all file-paths before adding to zip
"""
if isinstance(paths, basestring):
... |
def get_as_local_path(path, overwrite, progress=0,
httpuser=None, httppassword=None):
"""
Automatically handle local and remote URLs, files and directories
path: Either a local directory, file or remote URL. If a URL is given
it will be fetched. If this is a zip it will be autom... |
def create(fs, channels, application):
"""Allocates and initializes an encoder state."""
result_code = ctypes.c_int()
result = _create(fs, channels, application, ctypes.byref(result_code))
if result_code.value is not constants.OK:
raise OpusError(result_code.value)
return result |
def encode(encoder, pcm, frame_size, max_data_bytes):
"""Encodes an Opus frame
Returns string output payload
"""
pcm = ctypes.cast(pcm, c_int16_pointer)
data = (ctypes.c_char * max_data_bytes)()
result = _encode(encoder, pcm, frame_size, data, max_data_bytes)
if result < 0:
raise ... |
def encode_float(encoder, pcm, frame_size, max_data_bytes):
"""Encodes an Opus frame from floating point input"""
pcm = ctypes.cast(pcm, c_float_pointer)
data = (ctypes.c_char * max_data_bytes)()
result = _encode_float(encoder, pcm, frame_size, data, max_data_bytes)
if result < 0:
raise Op... |
def __parse_tostr(self, text, **kwargs):
'''Builds and returns the MeCab function for parsing Unicode text.
Args:
fn_name: MeCab function name that determines the function
behavior, either 'mecab_sparse_tostr' or
'mecab_nbest_sparse_tostr'.
Returns:
... |
def __parse_tonodes(self, text, **kwargs):
'''Builds and returns the MeCab function for parsing to nodes using
morpheme boundary constraints.
Args:
format_feature: flag indicating whether or not to format the feature
value for each node yielded.
Returns:
... |
def parse(self, text, **kwargs):
'''Parse the given text and return result from MeCab.
:param text: the text to parse.
:type text: str
:param as_nodes: return generator of MeCabNodes if True;
or string if False.
:type as_nodes: bool, defaults to False
:param ... |
def parse(filename, MAX_TERM_COUNT=1000):
"""
MAX_TERM_COUNT = 10000 # There are 39,000 terms in the GO!
"""
with open(filename, "r") as f:
termId = None
name = None
desc = None
parents = []
termCount = 0
for l in f.readlines():
if l.st... |
def generate(tagGroups, terms):
"""
create Tag Groups and Child Tags using data from terms dict
"""
rv = []
for pid in tagGroups:
# In testing we may not have complete set
if pid not in terms.keys():
continue
groupData = terms[pid]
groupName = "[%s] %s" ... |
def _handle_args(self, cmd, args):
"""
We need to support deprecated behaviour for now which makes this
quite complicated
Current behaviour:
- install: Installs a new server, existing server causes an error
- install --upgrade: Installs or upgrades a server
- ins... |
def get_server_dir(self):
"""
Either downloads and/or unzips the server if necessary
return: the directory of the unzipped server
"""
if not self.args.server:
if self.args.skipunzip:
raise Stop(0, 'Unzip disabled, exiting')
log.info('Downl... |
def handle_database(self):
"""
Handle database initialisation and upgrade, taking into account
command line arguments
"""
# TODO: When initdb and upgradedb are dropped we can just test
# managedb, but for backwards compatibility we need to support
# initdb without... |
def run(self, command):
"""
Runs a command as if from the command-line
without the need for using popen or subprocess
"""
if isinstance(command, basestring):
command = command.split()
else:
command = list(command)
self.external.omero_cli(co... |
def bin(self, command):
"""
Runs the omero command-line client with an array of arguments using the
old environment
"""
if isinstance(command, basestring):
command = command.split()
self.external.omero_bin(command) |
def symlink_check_and_set(self):
"""
The default symlink was changed from OMERO-CURRENT to OMERO.server.
If `--sym` was not specified and OMERO-CURRENT exists in the current
directory stop and warn.
"""
if self.args.sym == '':
if os.path.exists('OMERO-CURRENT'... |
def query(request):
"""Query encoder/decoder with a request value"""
def inner(func, obj):
result_code = func(obj, request)
if result_code is not constants.OK:
raise OpusError(result_code)
return result_code
return inner |
def get(request, result_type):
"""Get CTL value from a encoder/decoder"""
def inner(func, obj):
result = result_type()
result_code = func(obj, request, ctypes.byref(result))
if result_code is not constants.OK:
raise OpusError(result_code)
return result.value
r... |
def set(request):
"""Set new CTL value to a encoder/decoder"""
def inner(func, obj, value):
result_code = func(obj, request, value)
if result_code is not constants.OK:
raise OpusError(result_code)
return inner |
def sort_schemas(schemas):
"""Sort a list of SQL schemas in order"""
def keyfun(v):
x = SQL_SCHEMA_REGEXP.match(v).groups()
# x3: 'DEV' should come before ''
return (int(x[0]), x[1], int(x[2]) if x[2] else None,
x[3] if x[3] else 'zzz', int(x[4]))
return sorted(schem... |
def parse_schema_files(files):
"""
Parse a list of SQL files and return a dictionary of valid schema
files where each key is a valid schema file and the corresponding value is
a tuple containing the source and the target schema.
"""
f_dict = {}
for f in files:
root, ext = os.path.spl... |
def dump(self):
"""
Dump the database using the postgres custom format
"""
dumpfile = self.args.dumpfile
if not dumpfile:
db, env = self.get_db_args_env()
dumpfile = fileutils.timestamp_filename(
'omero-database-%s' % db['name'], 'pgdump')
... |
def get_db_args_env(self):
"""
Get a dictionary of database connection parameters, and create an
environment for running postgres commands.
Falls back to omego defaults.
"""
db = {
'name': self.args.dbname,
'host': self.args.dbhost,
'us... |
def psql(self, *psqlargs):
"""
Run a psql command
"""
db, env = self.get_db_args_env()
args = [
'-v', 'ON_ERROR_STOP=on',
'-d', db['name'],
'-h', db['host'],
'-U', db['user'],
'-w', '-A', '-t'
] + list(psqla... |
def pgdump(self, *pgdumpargs):
"""
Run a pg_dump command
"""
db, env = self.get_db_args_env()
args = ['-d', db['name'], '-h', db['host'], '-U', db['user'], '-w'
] + list(pgdumpargs)
stdout, stderr = External.run(
'pg_dump', args, capturestd=Tr... |
def set_server_dir(self, dir):
"""
Set the directory of the server to be controlled
"""
self.dir = os.path.abspath(dir)
config = os.path.join(self.dir, 'etc', 'grid', 'config.xml')
self.configured = os.path.exists(config) |
def get_config(self, force=False):
"""
Returns a dictionary of all config.xml properties
If `force = True` then ignore any cached state and read config.xml
if possible
setup_omero_cli() must be called before this method to import the
correct omero module to minimise the... |
def setup_omero_cli(self):
"""
Imports the omero CLI module so that commands can be run directly.
Note Python does not allow a module to be imported multiple times,
so this will only work with a single omero instance.
This can have several surprising effects, so setup_omero_cli(... |
def setup_previous_omero_env(self, olddir, savevarsfile):
"""
Create a copy of the current environment for interacting with the
current OMERO server installation
"""
env = self.get_environment(savevarsfile)
def addpath(varname, p):
if not os.path.exists(p):
... |
def omero_cli(self, command):
"""
Runs a command as if from the OMERO command-line without the need
for using popen or subprocess.
"""
assert isinstance(command, list)
if not self.cli:
raise Exception('omero.cli not initialised')
log.info("Invoking CLI... |
def omero_bin(self, command):
"""
Runs the omero command-line client with an array of arguments using the
old environment
"""
assert isinstance(command, list)
if not self.old_env:
raise Exception('Old environment not initialised')
log.info("Running [ol... |
def run(exe, args, capturestd=False, env=None):
"""
Runs an executable with an array of arguments, optionally in the
specified environment.
Returns stdout and stderr
"""
command = [exe] + args
if env:
log.info("Executing [custom environment]: %s", " ".... |
def string_support(py3enc):
'''Create byte-to-string and string-to-byte conversion functions for
internal use.
:param py3enc: Encoding used by Python 3 environment.
:type py3enc: str
'''
if sys.version < '3':
def bytes2str(b):
'''Identity, returns the argument string (bytes)... |
def splitter_support(py2enc):
'''Create tokenizer for use in boundary constraint parsing.
:param py2enc: Encoding used by Python 2 environment.
:type py2enc: str
'''
if sys.version < '3':
def _fn_sentence(pattern, sentence):
if REGEXTYPE == type(pattern):
if patt... |
def update(self, document_id, update_spec, namespace, timestamp):
"""Apply updates given in update_spec to the document whose id
matches that of doc.
"""
index, doc_type = self._index_and_mapping(namespace)
with self.lock:
# Check if document source is stored in loca... |
def upsert(self, doc, namespace, timestamp, update_spec=None):
"""Insert a document into Elasticsearch."""
index, doc_type = self._index_and_mapping(namespace)
# No need to duplicate '_id' in source document
doc_id = u(doc.pop("_id"))
metadata = {
'ns': namespace,
... |
def bulk_upsert(self, docs, namespace, timestamp):
"""Insert multiple documents into Elasticsearch."""
def docs_to_upsert():
doc = None
for doc in docs:
# Remove metadata and redundant _id
index, doc_type = self._index_and_mapping(namespace)
... |
def remove(self, document_id, namespace, timestamp):
"""Remove a document from Elasticsearch."""
index, doc_type = self._index_and_mapping(namespace)
action = {
'_op_type': 'delete',
'_index': index,
'_type': doc_type,
'_id': u(document_id)
... |
def send_buffered_operations(self):
"""Send buffered operations to Elasticsearch.
This method is periodically called by the AutoCommitThread.
"""
with self.lock:
try:
action_buffer = self.BulkBuffer.get_buffer()
if action_buffer:
... |
def get_last_doc(self):
"""Get the most recently modified document from Elasticsearch.
This method is used to help define a time window within which documents
may be in conflict after a MongoDB rollback.
"""
try:
result = self.elastic.search(
index=se... |
def split_sig(params):
"""
Split a list of parameters/types by commas,
whilst respecting brackets.
For example:
String arg0, int arg2 = 1, List<int> arg3 = [1, 2, 3]
=> ['String arg0', 'int arg2 = 1', 'List<int> arg3 = [1, 2, 3]']
"""
result = []
current = ''
level = 0
f... |
def parse_method_signature(sig):
""" Parse a method signature of the form: modifier* type name (params) """
match = METH_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Method signature invalid: ' + sig)
modifiers, return_type, name, generic_types, params = match.groups()
if para... |
def parse_property_signature(sig):
""" Parse a property signature of the form:
modifier* type name { (get;)? (set;)? } """
match = PROP_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Property signature invalid: ' + sig)
groups = match.groups()
if groups[0] is not None:
... |
def parse_indexer_signature(sig):
""" Parse a indexer signature of the form:
modifier* type this[params] { (get;)? (set;)? } """
match = IDXR_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Indexer signature invalid: ' + sig)
modifiers, return_type, params, getter, setter = m... |
def parse_param_signature(sig):
""" Parse a parameter signature of the form: type name (= default)? """
match = PARAM_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Parameter signature invalid, got ' + sig)
groups = match.groups()
modifiers = groups[0].split()
typ, name, _, ... |
def parse_type_signature(sig):
""" Parse a type signature """
match = TYPE_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Type signature invalid, got ' + sig)
groups = match.groups()
typ = groups[0]
generic_types = groups[1]
if not generic_types:
generic_types = ... |
def parse_attr_signature(sig):
""" Parse an attribute signature """
match = ATTR_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Attribute signature invalid, got ' + sig)
name, _, params = match.groups()
if params is not None and params.strip() != '':
params = split_sig(p... |
def get_msdn_ref(name):
""" Try and create a reference to a type on MSDN """
in_msdn = False
if name in MSDN_VALUE_TYPES:
name = MSDN_VALUE_TYPES[name]
in_msdn = True
if name.startswith('System.'):
in_msdn = True
if in_msdn:
link = name.split('<')[0]
if link i... |
def shorten_type(typ):
""" Shorten a type. E.g. drops 'System.' """
offset = 0
for prefix in SHORTEN_TYPE_PREFIXES:
if typ.startswith(prefix):
if len(prefix) > offset:
offset = len(prefix)
return typ[offset:] |
def parse_mecab_options(self, options):
'''Parses the MeCab options, returning them in a dictionary.
Lattice-level option has been deprecated; please use marginal or nbest
instead.
:options string or dictionary of options to use when instantiating
the MeCab insta... |
def build_options_str(self, options):
'''Returns a string concatenation of the MeCab options.
Args:
options: dictionary of options to use when instantiating the MeCab
instance.
Returns:
A string concatenation of the options used when instantiatin... |
def create(fs, channels):
"""Allocates and initializes a decoder state"""
result_code = ctypes.c_int()
result = _create(fs, channels, ctypes.byref(result_code))
if result_code.value is not 0:
raise OpusError(result_code.value)
return result |
def packet_get_bandwidth(data):
"""Gets the bandwidth of an Opus packet."""
data_pointer = ctypes.c_char_p(data)
result = _packet_get_bandwidth(data_pointer)
if result < 0:
raise OpusError(result)
return result |
def packet_get_nb_channels(data):
"""Gets the number of channels from an Opus packet"""
data_pointer = ctypes.c_char_p(data)
result = _packet_get_nb_channels(data_pointer)
if result < 0:
raise OpusError(result)
return result |
def packet_get_nb_frames(data, length=None):
"""Gets the number of frames in an Opus packet"""
data_pointer = ctypes.c_char_p(data)
if length is None:
length = len(data)
result = _packet_get_nb_frames(data_pointer, ctypes.c_int(length))
if result < 0:
raise OpusError(result)
r... |
def packet_get_samples_per_frame(data, fs):
"""Gets the number of samples per frame from an Opus packet"""
data_pointer = ctypes.c_char_p(data)
result = _packet_get_nb_frames(data_pointer, ctypes.c_int(fs))
if result < 0:
raise OpusError(result)
return result |
def decode(decoder, data, length, frame_size, decode_fec, channels=2):
"""Decode an Opus frame
Unlike the `opus_decode` function , this function takes an additional parameter `channels`,
which indicates the number of channels in the frame
"""
pcm_size = frame_size * channels * ctypes.sizeof(ctypes... |
def label_list_parser(self, url):
"""
Extracts comma separate tag=value pairs from a string
Assumes all characters other than / and , are valid
"""
labels = re.findall('([^/,]+=[^/,]+)', url)
slabels = set(labels)
if '' in slabels:
slabels.remove('')
... |
def init(app, register_blueprint=True, url_prefix='/fm', access_control_function=None,
custom_config_json_path=None, custom_init_js_path=None):
"""
:param app: The Flask app
:param register_blueprint: Override to False to stop the blueprint from automatically being registered to the
... |
def get_file(path=None, content=None):
"""
:param path: relative path, or None to get from request
:param content: file content, output in data. Used for editfile
"""
if path is None:
path = request.args.get('path')
if path is None:
return error('No path in request')
fi... |
def __get_charset(self):
'''Return the character encoding (charset) used internally by MeCab.
Charset is that of the system dictionary used by MeCab. Will defer to
the user-specified MECAB_CHARSET environment variable, if set.
Defaults to shift-jis on Windows.
Defaults t... |
def __get_libpath(self):
'''Return the absolute path to the MeCab library.
On Windows, the path to the system dictionary is used to deduce the
path to libmecab.dll.
Otherwise, mecab-config is used find the libmecab shared object or
dynamic library (*NIX or Mac OS, respec... |
def __regkey_value(self, path, name='', start_key=None):
r'''Return the data of value mecabrc at MeCab HKEY node.
On Windows, the path to the mecabrc as set in the Windows Registry is
used to deduce the path to libmecab.dll.
Returns:
The full path to the mecabrc on W... |
def diff(old_html, new_html, cutoff=0.0, plaintext=False, pretty=False):
"""Show the differences between the old and new html document, as html.
Return the document html with extra tags added to show changes. Add <ins>
tags around newly added sections, and <del> tags to show sections that have
been del... |
def adjusted_ops(opcodes):
"""
Iterate through opcodes, turning them into a series of insert and delete
operations, adjusting indices to account for the size of insertions and
deletions.
>>> def sequence_opcodes(old, new): return difflib.SequenceMatcher(a=old, b=new).get_opcodes()
>>> list(adju... |
def match_indices(match):
"""Yield index tuples (old_index, new_index) for each place in the match."""
a, b, size = match
for i in range(size):
yield a + i, b + i |
def get_opcodes(matching_blocks):
"""Use difflib to get the opcodes for a set of matching blocks."""
sm = difflib.SequenceMatcher(a=[], b=[])
sm.matching_blocks = matching_blocks
return sm.get_opcodes() |
def match_blocks(hash_func, old_children, new_children):
"""Use difflib to find matching blocks."""
sm = difflib.SequenceMatcher(
_is_junk,
a=[hash_func(c) for c in old_children],
b=[hash_func(c) for c in new_children],
)
return sm |
def get_nonmatching_blocks(matching_blocks):
"""Given a list of matching blocks, output the gaps between them.
Non-matches have the format (alo, ahi, blo, bhi). This specifies two index
ranges, one in the A sequence, and one in the B sequence.
"""
i = j = 0
for match in matching_blocks:
... |
def merge_blocks(a_blocks, b_blocks):
"""Given two lists of blocks, combine them, in the proper order.
Ensure that there are no overlaps, and that they are for sequences of the
same length.
"""
# Check sentinels for sequence length.
assert a_blocks[-1][2] == b_blocks[-1][2] == 0 # sentinel size... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.