text stringlengths 81 112k |
|---|
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 reponsible for calling close() on the returned object
def open_url(url, httpuser=Non... |
Makes a HEAD request to find the final destination of a URL after
following any redirects
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 |
Read the contents of a URL into memory, return
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() |
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, use 0 to disable
delete_fail: If True delete the file if the download was not successful,
defaul... |
Append a backup prefix to a file or directory, with an increasing numeric
suffix (.N) if a file already exists
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,... |
Return a string of the form [basename-TIMESTAMP.ext]
where TIMESTAMP is of the form YYYYMMDD-HHMMSS-MILSEC
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(... |
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 this subdirectory
Python docs are unclear about the securi... |
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 directory, default current directory
return: If match_dir is T... |
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
def zip(filename, paths, strip_prefix=''):
"""
Create a new zip archive containing files
filena... |
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 automatically
expanded by default.
overwrite: Whether to overwrite an existing file:
'error': Raise an except... |
Allocates and initializes an encoder state.
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(re... |
Encodes an Opus frame
Returns string output payload
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_siz... |
Encodes an Opus frame from floating point input
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, ma... |
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:
A function definition, tailored to parsi... |
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:
A function which returns a Generator, tailore... |
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 boundary_constraints: regular expression for... |
MAX_TERM_COUNT = 10000 # There are 39,000 terms in the GO!
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 = []
... |
create Tag Groups and Child Tags using data from terms dict
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
... |
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
- install --managedb: Automatically initialise or upgrade th... |
Either downloads and/or unzips the server if necessary
return: the directory of the unzipped server
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:
... |
Handle database initialisation and upgrade, taking into account
command line arguments
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... |
Runs a command as if from the command-line
without the need for using popen or subprocess
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 = c... |
Runs the omero command-line client with an array of arguments using the
old environment
def bin(self, command):
"""
Runs the omero command-line client with an array of arguments using the
old environment
"""
if isinstance(command, basestring):
command = comma... |
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.
def symlink_check_and_set(self):
"""
The default symlink was changed from OMERO-CURRENT to OMERO.server.
If `--sym` w... |
Query encoder/decoder with a request value
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 |
Get CTL value from a encoder/decoder
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_cod... |
Set new CTL value to a encoder/decoder
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 |
Sort a list of SQL schemas in order
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'... |
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.
def parse_schema_files(files):
"""
Parse a list of SQL files and return a dictionary of valid schema
file... |
Dump the database using the postgres custom format
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(
... |
Get a dictionary of database connection parameters, and create an
environment for running postgres commands.
Falls back to omego defaults.
def get_db_args_env(self):
"""
Get a dictionary of database connection parameters, and create an
environment for running postgres commands.
... |
Run a psql command
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'
... |
Run a pg_dump command
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_dum... |
Set the directory of the server to be controlled
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) |
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 possibility of version conflicts
def get_config(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()
must be explcitly called.
def setup_... |
Create a copy of the current environment for interacting with the
current OMERO server installation
def setup_previous_omero_env(self, olddir, savevarsfile):
"""
Create a copy of the current environment for interacting with the
current OMERO server installation
"""
env =... |
Runs a command as if from the OMERO command-line without the need
for using popen or subprocess.
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)
... |
Runs the omero command-line client with an array of arguments using the
old environment
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_... |
Runs an executable with an array of arguments, optionally in the
specified environment.
Returns stdout and stderr
def run(exe, args, capturestd=False, env=None):
"""
Runs an executable with an array of arguments, optionally in the
specified environment.
Returns stdout an... |
Create byte-to-string and string-to-byte conversion functions for
internal use.
:param py3enc: Encoding used by Python 3 environment.
:type py3enc: str
def string_support(py3enc):
'''Create byte-to-string and string-to-byte conversion functions for
internal use.
:param py3enc: Encoding used b... |
Create tokenizer for use in boundary constraint parsing.
:param py2enc: Encoding used by Python 2 environment.
:type py2enc: str
def splitter_support(py2enc):
'''Create tokenizer for use in boundary constraint parsing.
:param py2enc: Encoding used by Python 2 environment.
:type py2enc: str
''... |
Apply updates given in update_spec to the document whose id
matches that of doc.
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(n... |
Insert a document into Elasticsearch.
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"))
metada... |
Insert multiple documents into Elasticsearch.
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_t... |
Remove a document from Elasticsearch.
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,
... |
Send buffered operations to Elasticsearch.
This method is periodically called by the AutoCommitThread.
def send_buffered_operations(self):
"""Send buffered operations to Elasticsearch.
This method is periodically called by the AutoCommitThread.
"""
with self.lock:
... |
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.
def get_last_doc(self):
"""Get the most recently modified document from Elasticsearch.
This method is used t... |
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]']
def split_sig(params):
"""
Split a list of parameters/types by commas,
whilst resp... |
Parse a method signature of the form: modifier* type name (params)
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, r... |
Parse a property signature of the form:
modifier* type name { (get;)? (set;)? }
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('Propert... |
Parse a indexer signature of the form:
modifier* type this[params] { (get;)? (set;)? }
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 RuntimeE... |
Parse a parameter signature of the form: type name (= default)?
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 = ma... |
Parse a type signature
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:
... |
Parse an attribute signature
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() != ''... |
Try and create a reference to a type on MSDN
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:
... |
Shorten a type. E.g. drops 'System.'
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:] |
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 instance. May be in short- or long-form, or in a
... |
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 instantiating the
MeCab instance, in long-form.
... |
Allocates and initializes a decoder state
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 |
Gets the bandwidth of an Opus packet.
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 |
Gets the number of channels from an Opus packet
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 |
Gets the number of frames in an Opus packet
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 resul... |
Gets the number of samples per frame from an Opus packet
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 OpusErro... |
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
def decode(decoder, data, length, frame_size, decode_fec, channels=2):
"""Decode an Opus frame
Unlike the `opus_decode` function , this ... |
Extracts comma separate tag=value pairs from a string
Assumes all characters other than / and , are valid
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.finda... |
:param app: The Flask app
:param register_blueprint: Override to False to stop the blueprint from automatically being registered to the
app
:param url_prefix: The URL prefix for the blueprint, defaults to /fm
:param access_control_function: Pass in a function here to implement... |
:param path: relative path, or None to get from request
:param content: file content, output in data. Used for editfile
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 ... |
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 to utf-8 on Mac OS.
Defaults ... |
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, respectively).
Will defer to the... |
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 Windows.
Raises:
WindowsError: A problem wa... |
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 deleted.
def diff(old_html, new_html, cutoff=0.0, plaintext=False, pretty=False):
... |
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(adjusted_ops(sequence_opcodes('abc', 'b')))... |
Yield index tuples (old_index, new_index) for each place in the match.
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 |
Use difflib to get the opcodes for a set of matching blocks.
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() |
Use difflib to find matching blocks.
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 |
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.
def get_nonmatching_blocks(matching_blocks):
"""Given a list of matching blocks, output the gaps between them.... |
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.
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 ... |
Remove comments, as they can break the xml parser.
See html5lib issue #122 ( http://code.google.com/p/html5lib/issues/detail?id=122 ).
>>> remove_comments('<!-- -->')
''
>>> remove_comments('<!--\\n-->')
''
>>> remove_comments('<p>stuff<!-- \\n -->stuff</p>')
'<p>stuffstuff</p>'
def remov... |
r"""Remove newlines in the xml.
If the newline separates words in text, then replace with a space instead.
>>> remove_newlines('<p>para one</p>\n<p>para two</p>')
'<p>para one</p><p>para two</p>'
>>> remove_newlines('<p>line one\nline two</p>')
'<p>line one line two</p>'
>>> remove_newlines('o... |
For html elements that should not have text nodes inside them, remove all
whitespace. For elements that may have text, collapse multiple spaces to a
single space.
def remove_insignificant_text_nodes(dom):
"""
For html elements that should not have text nodes inside them, remove all
whitespace. For ... |
Get the child at the given index, or return None if it doesn't exist.
def get_child(parent, child_index):
"""
Get the child at the given index, or return None if it doesn't exist.
"""
if child_index < 0 or child_index >= len(parent.childNodes):
return None
return parent.childNodes[child_ind... |
Get the node at the specified location in the dom.
Location is a sequence of child indices, starting at the children of the
root element. If there is no node at this location, raise a ValueError.
def get_location(dom, location):
"""
Get the node at the specified location in the dom.
Location is a s... |
Check whether two dom trees have similar text or not.
def check_text_similarity(a_dom, b_dom, cutoff):
"""Check whether two dom trees have similar text or not."""
a_words = list(tree_words(a_dom))
b_words = list(tree_words(b_dom))
sm = WordMatcher(a=a_words, b=b_words)
if sm.text_ratio() >= cutoff... |
Return all the significant text below the given node as a list of words.
>>> list(tree_words(parse_minidom('<h1>one</h1> two <div>three<em>four</em></div>')))
['one', 'two', 'three', 'four']
def tree_words(node):
"""Return all the significant text below the given node as a list of words.
>>> list(tree_... |
>>> tree_text(parse_minidom('<h1>one</h1>two<div>three<em>four</em></div>'))
'one two three four'
def tree_text(node):
"""
>>> tree_text(parse_minidom('<h1>one</h1>two<div>three<em>four</em></div>'))
'one two three four'
"""
text = []
for descendant in walk_dom(node):
if is_text(des... |
Insert the node before next_sibling. If next_sibling is None, append the node last instead.
def insert_or_append(parent, node, next_sibling):
"""
Insert the node before next_sibling. If next_sibling is None, append the node last instead.
"""
# simple insert
if next_sibling:
parent.insertBef... |
Wrap the given tag around a node.
def wrap(node, tag):
"""Wrap the given tag around a node."""
wrap_node = node.ownerDocument.createElement(tag)
parent = node.parentNode
if parent:
parent.replaceChild(wrap_node, node)
wrap_node.appendChild(node)
return wrap_node |
Wrap the given tag around the contents of a node.
def wrap_inner(node, tag):
"""Wrap the given tag around the contents of a node."""
children = list(node.childNodes)
wrap_node = node.ownerDocument.createElement(tag)
for c in children:
wrap_node.appendChild(c)
node.appendChild(wrap_node) |
Remove a node, replacing it with its children.
def unwrap(node):
"""Remove a node, replacing it with its children."""
for child in list(node.childNodes):
node.parentNode.insertBefore(child, node)
remove_node(node) |
Split the text by the regex, keeping all parts.
The parts should re-join back into the original text.
>>> list(full_split('word', re.compile('&.*?')))
['word']
def full_split(text, regex):
"""
Split the text by the regex, keeping all parts.
The parts should re-join back into the original text.... |
Split the text by the given regexes, in priority order.
Make sure that the regex is parenthesized so that matches are returned in
re.split().
Splitting on a single regex works like normal split.
>>> '|'.join(multi_split('one two three', [r'\w+']))
'one| |two| |three'
Splitting on digits first... |
Return a measure of the sequences' word similarity (float in [0,1]).
Each word has weight equal to its length for this measure
>>> m = WordMatcher(a=['abcdef', '12'], b=['abcdef', '34']) # 3/4 of the text is the same
>>> '%.3f' % m.ratio() # normal ratio fails
'0.500'
>>> '%.3f... |
Find the total length of all words that match between the two sequences.
def match_length(self):
""" Find the total length of all words that match between the two sequences."""
length = 0
for match in self.get_matching_blocks():
a, b, size = match
length += self._text_le... |
Run an xml edit script, and return the new html produced.
def run_edit_script(self):
"""
Run an xml edit script, and return the new html produced.
"""
for action, location, properties in self.edit_script:
if action == 'delete':
node = get_location(self.dom, l... |
Add <ins> and <del> tags to the dom to show changes.
def add_changes_markup(dom, ins_nodes, del_nodes):
"""
Add <ins> and <del> tags to the dom to show changes.
"""
# add markup for inserted and deleted sections
for node in reversed(del_nodes):
# diff algorithm deletes nodes in reverse orde... |
Unwrap items in the node list that have ancestors with the same tag.
def remove_nesting(dom, tag_name):
"""
Unwrap items in the node list that have ancestors with the same tag.
"""
for node in dom.getElementsByTagName(tag_name):
for ancestor in ancestors(node):
if ancestor is node:
... |
Sort the nodes of the dom in-place, based on a comparison function.
def sort_nodes(dom, cmp_func):
"""
Sort the nodes of the dom in-place, based on a comparison function.
"""
dom.normalize()
for node in list(walk_dom(dom, elements_only=True)):
prev_sib = node.previousSibling
while p... |
Merge all adjacent tags with the specified tag name.
Return the number of merges performed.
def merge_adjacent(dom, tag_name):
"""
Merge all adjacent tags with the specified tag name.
Return the number of merges performed.
"""
for node in dom.getElementsByTagName(tag_name):
prev_sib = n... |
Wrap a copy of the given element around the contents of each of its
children, removing the node in the process.
def distribute(node):
"""
Wrap a copy of the given element around the contents of each of its
children, removing the node in the process.
"""
children = list(c for c in node.childNode... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.