code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if not patterns:
return {}
data = {'ignore': list(patterns)}
return self.post('ignores', params={'folder': folder}, data=data) | def set_ignores(self, folder, *patterns) | Applies ``patterns`` to ``folder``'s ``.stignore`` file.
Args:
folder (str):
patterns (str):
Returns:
dict | 5.944129 | 6.956362 | 0.854488 |
assert isinstance(page, int) or page is None
assert isinstance(perpage, int) or perpage is None
return self.get('need', params={'folder': folder,
'page': page,
'perpage': perpage}) | def need(self, folder, page=None, perpage=None) | Returns lists of files which are needed by this device in order
for it to become in sync.
Args:
folder (str):
page (int): If defined applies pagination accross the
collection of results.
perpage (int): If defined applies pagination... | 2.59302 | 2.984163 | 0.868927 |
if not sub:
sub = ''
assert isinstance(sub, string_types)
assert isinstance(next_, int) or next_ is None
return self.post('scan', params={'folder': folder,
'sub': sub,
'next': next_}) | def scan(self, folder, sub=None, next_=None) | Request immediate rescan of a folder, or a specific path within a
folder.
Args:
folder (str): Folder ID.
sub (str): Path relative to the folder root. If sub is omitted
the entire folder is scanned for changes, otherwise only
th... | 3.055073 | 3.528142 | 0.865915 |
# coerce
if not isinstance(limit, (int, NoneType)):
limit = None
# coerce
if filters is None:
filters = []
# format our list into the correct expectation of string with commas
if isinstance(filters, string_types):
filters = ... | def _events(self, using_url, filters=None, limit=None) | A long-polling method that queries Syncthing for events..
Args:
using_url (str): REST HTTP endpoint
filters (List[str]): Creates an "event group" in Syncthing to
only receive events that have been subscribed to.
limit (int): The number of ... | 5.358997 | 5.336283 | 1.004256 |
for node_id, properties in discoursegraph.nodes_iter(data=True):
if 'label' not in properties and isinstance(node_id, (str, unicode)):
discoursegraph.node[node_id]['label'] = ensure_utf8(node_id) | def add_node_ids_as_labels(discoursegraph) | Adds the ID of each node of a discourse graph as a label (an attribute
named ``label`` with the value of the node ID) to itself. This will
ignore nodes whose ID isn't a string or which already have a label
attribute.
Parameters
----------
discoursegraph : DiscourseDocumentGraph | 2.821627 | 3.172588 | 0.889377 |
dg_copy = deepcopy(discoursegraph)
layerset2list(dg_copy)
add_node_ids_as_labels(dg_copy)
return graph2geoff(dg_copy, 'LINKS_TO') | def convert_to_geoff(discoursegraph) | Parameters
----------
discoursegraph : DiscourseDocumentGraph
the discourse document graph to be converted into GEOFF format
Returns
-------
geoff : string
a geoff string representation of the discourse graph. | 8.864335 | 10.490339 | 0.845 |
if isinstance(output_file, str):
with open(output_file, 'w') as outfile:
outfile.write(convert_to_geoff(discoursegraph))
else: # output_file is a file object
output_file.write(convert_to_geoff(discoursegraph)) | def write_geoff(discoursegraph, output_file) | converts a DiscourseDocumentGraph into a Geoff file and
writes it to the given file (or file path). | 2.026898 | 1.970288 | 1.028732 |
if sudo_url is None:
sudo_url = URL
sudo_url_parts = list(urlparse(resolve_url(sudo_url)))
querystring = QueryDict(sudo_url_parts[4], mutable=True)
querystring[REDIRECT_FIELD_NAME] = next_url
sudo_url_parts[4] = querystring.urlencode(safe='/')
return HttpResponseRedirect(urlunpar... | def redirect_to_sudo(next_url, sudo_url=None) | Redirects the user to the login page, passing the given 'next' page | 2.404877 | 2.36711 | 1.015955 |
relative_leaf_positions = subtree.treepositions('leaves')
subtree_root_pos = subtree.treeposition()
absolute_leaf_positions = []
for rel_leaf_pos in relative_leaf_positions:
absolute_leaf_positions.append( subtree_root_pos + rel_leaf_pos)
return absolute_leaf_positions | def subtree_leaf_positions(subtree) | Return tree positions of all leaves of a subtree. | 2.736606 | 2.579568 | 1.060878 |
all_leaves = all_leaf_positions(parented_tree)
if is_root(parented_tree):
return t('span', ['1', str(len(all_leaves))])
subtree_leaves = subtree_leaf_positions(parented_tree)
if len(subtree_leaves) == 1:
edu_id = all_leaves.index(subtree_leaves[0]) + 1
return t('leaf', ... | def make_span(parented_tree) | create a 'span' or 'leaf' subtree for dis/lisp/RST-DT-formatted trees.
Examples:
span (a subtree that covers the leaves 1 to 7)
___|____
1 7
leaf (a subtree that only covers leaf 7)
|
7 | 2.370503 | 2.335776 | 1.014867 |
if is_leaf(parented_tree):
return [parented_tree]
nucsat_children = []
for child in parented_tree:
if is_leaf(child) or child.label() in ('N', 'S'):
nucsat_children.append(child)
else:
nucsat_children.extend( get_nucsat_subtrees(child) )
return ... | def get_nucsat_subtrees(parented_tree) | Return all direct children of the given tree, that are either
a nucleus, satellite or a leaf node (i.e. all children except
for relation nodes.) | 2.119748 | 2.121245 | 0.999294 |
dis_raw_str = self.disfiletree.pformat()
return re.sub('_!(.*?)_!', join_lines, dis_raw_str, flags=re.DOTALL) | def to_dis_format(self) | Return a string representation of the tree in .dis format. | 13.617978 | 11.503851 | 1.183776 |
dg_copy = deepcopy(docgraph)
layerset2str(dg_copy)
attriblist2str(dg_copy)
remove_root_metadata(dg_copy)
nx_write_graphml(dg_copy, output_file) | def write_graphml(docgraph, output_file) | takes a document graph, converts it into GraphML format and writes it to
a file. | 7.19592 | 7.049019 | 1.02084 |
self.__context = etree.iterparse(self.exportxml_file, events=('end',),
tag='text', recover=True) | def _reset_corpus_iterator(self) | create an iterator over all documents in the file (i.e. all
<text> elements). The recover parameter is used, as the Tüba-D/Z 8.0
corpus used for testing isn't completely valid XML (i.e. there are two
element IDs used twice).
Once you have iterated over all documents, call this method ag... | 12.359896 | 8.158465 | 1.514978 |
for _event, elem in context:
if not self.debug:
yield ExportXMLDocumentGraph(elem, name=elem.attrib[add_ns('id')])
else:
yield elem
# removes element (and references to it) from memory after processing it
elem.clear()
... | def text_iter(self, context) | Iterates over all the elements in an iterparse context
(here: <text> elements) and yields an ExportXMLDocumentGraph instance
for each of them. For efficiency, the elements are removed from the
DOM / main memory after processing them.
If ``self.debug`` is set to ``True`` (in the ``__init... | 8.864984 | 5.094744 | 1.740025 |
'''parses all children of an etree element'''
for child in element.iterchildren():
self.parsers[child.tag](child) | def parse_child_elements(self, element) | parses all children of an etree element | 6.527429 | 4.637927 | 1.407402 |
'''parses all descendants of an etree element'''
for descendant in element.iterdescendants():
self.parsers[descendant.tag](descendant) | def parse_descedant_elements(self, element) | parses all descendants of an etree element | 5.426412 | 4.032403 | 1.345702 |
word_node_id = self.get_element_id(connective)
# add a key 'connective' to the token with add rel1/rel2 attributes as a dict and
# add the token to the namespace:connective layer
connective_attribs = {key: val for (key, val) in connective.attrib.items() if key != 'konn'}
... | def add_connective(self, connective) | Parameters
----------
connective : etree.Element
etree representation of a <connective> element
(annotates connective tokens)
Example
-------
<word xml:id="s29_1" form="Als" pos="KOUS" lemma="als" func="-"
parent="s29_500" dephead="s29_1... | 7.662979 | 6.276666 | 1.220868 |
if self.ignore_relations is False:
arg1_id = self.get_element_id(discrel)
arg2_id = discrel.attrib['arg2']
reltype = discrel.attrib['relation']
discrel_attribs = self.element_attribs_to_dict(discrel)
self.node[arg1_id].update(discrel_attribs)
... | def add_discrel(self, discrel) | Add a discourse relation to the document graph.
Parameters
----------
add_discrel : etree.Element
etree representation of a <discRel> element which describes the
relation between two EDUs.
The ID of the other EDU is given in the arg2 attribute.
No... | 3.742505 | 3.616247 | 1.034914 |
edu_id = self.get_element_id(edu)
edu_attribs = self.element_attribs_to_dict(edu) # contains 'span' or nothing
self.add_node(edu_id, layers={self.ns, self.ns+':edu'}, attr_dict=edu_attribs)
edu_token_ids = []
for word in edu.iterdescendants('word'):
word_id ... | def add_edu(self, edu) | Parameters
----------
edu : etree.Element
etree representation of a <edu> element
(annotates an EDU)
Note: the arg1 EDU has a discRel child, the arg2 doesn't
Example
-------
<edu xml:id="edu_55_21_1">
<discRel relation="Explanation-Ca... | 4.149907 | 4.065763 | 1.020696 |
edurange_id = self.get_element_id(edurange)
edurange_attribs = self.element_attribs_to_dict(edurange) # contains 'span' or nothing
self.add_node(edurange_id, layers={self.ns, self.ns+':edu:range'}, attr_dict=edurange_attribs)
for edu in edurange.iterdescendants('edu'):
... | def add_edurange(self, edurange) | Parameters
----------
edurange : etree.Element
etree representation of a <edurange> element
(annotation that groups a number of EDUs)
<edu-range> seems to glue together a number of `<edu> elements,
which may be scattered over a number of sentences
... | 4.388561 | 4.308905 | 1.018486 |
ne_id = self.get_element_id(ne)
ne_label = 'ne:'+ne.attrib['type']
self.add_node(ne_id, layers={self.ns, self.ns+':ne'},
attr_dict=self.element_attribs_to_dict(ne),
label=ne_label)
# possible children: [('word', 78703), ('node', 11152)... | def add_ne(self, ne) | Parameters
----------
ne : etree.Element
etree representation of a <ne> element
(marks a text span -- (one or more <node> or <word> elements) as a named entity)
Example
-------
<ne xml:id="ne_23" type="PER">
<word xml:id="s3_2" form="Ute"... | 4.740602 | 4.480463 | 1.058061 |
node_id = self.get_element_id(node)
if 'parent' in node.attrib:
parent_id = self.get_parent_id(node)
else:
# <node> is the root of the syntax tree of a sentence,
# but it might be embedded in a <edu> or <edu-range>.
# we want to attach it ... | def add_node_element(self, node) | Add a (syntax category) <node> to the document graph.
Parameters
----------
node : etree.Element
etree representation of a <node> element
A <node> describes an element of a syntax tree.
The root <node> element does not have a parent attribute,
whi... | 5.569281 | 4.711931 | 1.181953 |
if self.ignore_relations is False:
parent_node_id = self.get_parent_id(relation)
reltype = relation.attrib['type']
# add relation type information to parent node
self.node[parent_node_id].update({'relation': reltype})
self.add_layer(parent_nod... | def add_relation(self, relation) | Parameters
----------
relation : etree.Element
etree representation of a <relation> element
A <relation> always has a type attribute and inherits
its ID from its parent element. In the case of a non-expletive
relation, it also has a target attribute.
... | 4.273867 | 3.943635 | 1.083738 |
if self.ignore_secedges is False:
edge_source = self.get_parent_id(secedge)
edge_target = self.get_element_id(secedge)
self.add_edge(edge_source, edge_target,
layers={self.ns, self.ns+':secedge'},
label='secedge:'+s... | def add_secedge(self, secedge) | Parameters
----------
secedge : etree.Element
etree representation of a <secedge> element
A <secEdge> element has a cat and a parent attribute,
but inherits its ID from its parent element.
It describes a secondary edge in a tree-like syntax representation.
Ex... | 5.52685 | 4.978133 | 1.110225 |
sent_root_id = sentence.attrib[add_ns('id')]
# add edge from document root to sentence root
self.add_edge(self.root, sent_root_id, edge_type=dg.EdgeTypes.dominance_relation)
self.sentences.append(sent_root_id)
sentence_token_ids = []
if 'span' in sentence.attri... | def add_sentence(self, sentence) | Parameters
----------
sentence : etree.Element
etree representation of a sentence
(syntax tree with coreference annotation) | 4.725361 | 4.652574 | 1.015645 |
if self.ignore_relations is False and self.ignore_splitrelations is False:
source_id = self.get_element_id(splitrelation)
# the target attribute looks like this: target="s2527_504 s2527_521"
target_node_ids = splitrelation.attrib['target'].split()
# we'll... | def add_splitrelation(self, splitrelation) | Parameters
----------
splitrelation : etree.Element
etree representation of a <splitRelation> element
A <splitRelation> annotates its parent element (e.g. as an anaphora).
Its parent can be either a <word> or a <node>.
A <splitRelation> has a target attrib... | 3.386594 | 2.883824 | 1.174342 |
topic_id = self.get_element_id(topic)
self.add_node(topic_id, layers={self.ns, self.ns+':topic'},
description=topic.attrib['description'])
topic_tokens = []
for word in topic.iterdescendants('word'):
word_id = self.get_element_id(word)
... | def add_topic(self, topic) | Parameters
----------
topic : etree.Element
etree representation of a <topic> element
(topic annotation of a text span, e.g. a sentence, edu or edu-range)
Example
-------
<topic xml:id="topic_9_0" description="Kuli">
<sentence xml:id="... | 3.716463 | 3.541571 | 1.049383 |
word_id = self.get_element_id(word)
if word.getparent().tag in ('node', 'sentence'):
parent_id = self.get_parent_id(word)
else:
# ExportXML is an inline XML format. Therefore, a <word>
# might be embedded in weird elements. If this is the case,
... | def add_word(self, word) | Parameters
----------
word : etree.Element
etree representation of a <word> element
(i.e. a token, which might contain child elements) | 6.141122 | 5.745462 | 1.068865 |
return {self.ns+':'+key: val for (key, val) in element.attrib.items()
if key != add_ns('id')} | def element_attribs_to_dict(self, element) | Convert the ``.attrib`` attributes of an etree element into a dict,
leaving out the xml:id attribute. Each key will be prepended by graph's
namespace. | 6.885843 | 6.124958 | 1.124227 |
id_attrib_key = add_ns('id')
if id_attrib_key in element.attrib:
return element.attrib[id_attrib_key]
try:
return element.getparent().attrib[id_attrib_key]
except KeyError as e:
raise KeyError(
'Neither the element "{0}" nor it... | def get_element_id(element) | Returns the ID of an element (or, if the element doesn't have one:
the ID of its parent). Returns an error, if both elements have no ID. | 3.209862 | 2.902121 | 1.10604 |
if 'parent' in element.attrib:
return element.attrib['parent']
else:
return element.getparent().attrib[add_ns('id')] | def get_parent_id(element) | returns the ID of the parent of the given element | 4.242075 | 4.086592 | 1.038047 |
try:
sentence_elem = element.iterancestors('sentence').next()
except StopIteration as e:
warnings.warn("<{}> element is not a descendant of a <sentence> "
"We'll try to extract the sentence ID from the "
"prefix of the ... | def get_sentence_id(self, element) | returns the ID of the sentence the given element belongs to. | 4.596253 | 4.323781 | 1.063017 |
if is_leaf(dgtree):
return TreeNodeTypes.leaf_node
root_label = dgtree.label()
if root_label == '':
assert dgtree == DGParentedTree('', []), \
"The tree has no root label, but isn't empty: {}".format(dgtree)
return TreeNodeTypes.empty_tree
elif root_label in NUC... | def get_node_type(dgtree) | Returns the type of the root node of a DGParentedTree. | 5.194014 | 4.403788 | 1.179442 |
children_treepos = []
for i, child in enumerate(self.dgtree[treepos]):
if isinstance(child, nltk.Tree):
children_treepos.append(child.treeposition())
elif is_leaf(child):
# we can't call .treeposition() on a leaf node
treep... | def get_children_treepos(self, treepos) | Given a treeposition, return the treepositions of its children. | 2.446683 | 2.413701 | 1.013665 |
parent_pos = self.get_parent_treepos(treepos)
siblings_treepos = []
if parent_pos is not None:
for child_treepos in self.get_children_treepos(parent_pos):
if child_treepos != treepos:
siblings_treepos.append(child_treepos)
return ... | def get_siblings_treepos(self, treepos) | Given a treeposition, return the treepositions of its siblings. | 1.694901 | 1.651153 | 1.026496 |
cousins_pos = []
mother_pos = self.get_parent_treepos(treepos)
if mother_pos is not None:
aunts_pos = self.get_siblings_treepos(mother_pos)
for aunt_pos in aunts_pos:
cousins_pos.extend( self.get_children_treepos(aunt_pos) )
return cousin... | def get_cousins_treepos(self, treepos) | Given a treeposition, return the treeposition of its siblings. | 2.318116 | 2.244409 | 1.03284 |
parent_pos = self.get_parent_treepos(treepos)
if parent_pos is not None:
parent = self.dgtree[parent_pos]
return parent.label()
else:
return None | def get_parent_label(self, treepos) | Given the treeposition of a node, return the label of its parent.
Returns None, if the tree has no parent. | 3.101254 | 2.88541 | 1.074805 |
children_labels = []
node = self.dgtree[treepos]
for child in node:
if is_leaf(child):
# we can't call .label() on a leaf node
children_labels.append(child)
else:
children_labels.append(child.label())
return... | def get_children_labels(self, treepos) | Given the treeposition of a node, return the labels of its children. | 3.499551 | 3.340461 | 1.047625 |
relations_elem = self.gen_relations()
header = E('header')
header.append(relations_elem)
self.gen_body()
tree = E('rst')
tree.append(header)
# The <body> contains both <segment>, as well as <group> elements.
# While the order of the elements sh... | def gen_etree(self) | convert an RST tree (DGParentedTree -> lxml etree) | 5.128521 | 4.8702 | 1.053041 |
relations_elem = E('relations')
for relname in sorted(self.relations):
relations_elem.append(
E('rel', OrderedDict([('name', relname), ('type', self.relations[relname])])))
return relations_elem | def gen_relations(self) | Create the <relations> etree element of an RS3 file.
This represents all relation types (both 'rst' and 'multinuc').
Example relation:
<rel name="circumstance" type="rst" /> | 4.209149 | 3.18947 | 1.319702 |
# We need to sort the treepositions, as RSTTool relies on <segment>
# elements to be in linear order of the EDUs in the text.
for treepos in sorted(self.treepositions):
node = self.dgtree[treepos]
node_id = self.get_node_id(treepos)
node_type = get_no... | def gen_body(self) | Create the <body> etree element of an RS3 file (contains segments
and groups) given a DGParentedTree. | 4.16436 | 3.771955 | 1.104032 |
node = self.dgtree[treepos]
node_type = get_node_type(node)
assert node_type in (TreeNodeTypes.relation_node, TreeNodeTypes.leaf_node)
parent_pos = self.get_parent_treepos(treepos)
if parent_pos is None: # a root node has no upward relation
return None, Non... | def get_relname_and_parent(self, treepos) | Return the (relation name, parent ID) tuple that a node is in.
Return None if this node is not in a relation. | 3.061698 | 3.023421 | 1.01266 |
token_indices = [token_map[token_id] for token_id in segment_token_list]
# we need to foolproof this for nasty RS3 files or other input formats
# with unordered or wrongly orderd IDs
return min(token_indices), max(token_indices) | def get_segment_token_offsets(segment_token_list, token_map) | given a list of token node IDs, returns the index of its first and last
elements. this actually calculates the int indices, as there are weird
formats like RS3, which use unordered / wrongly ordered IDs.
Parameters
----------
segment_token_list : list of str
sorted list of token IDs (i.e. t... | 11.169339 | 7.572001 | 1.475084 |
return [int(text) if text.isdigit() else text
for text in re.split(INTEGER_RE, str(s))] | def natural_sort_key(s) | returns a key that can be used in sort functions.
Example:
>>> items = ['A99', 'a1', 'a2', 'a10', 'a24', 'a12', 'a100']
The normal sort function will ignore the natural order of the
integers in the string:
>>> print sorted(items)
['A99', 'a1', 'a10', 'a100', 'a12', 'a2', 'a24']
When we ... | 4.209713 | 8.516035 | 0.494328 |
if isinstance(str_or_unicode, str):
return str_or_unicode.decode('utf-8')
elif isinstance(str_or_unicode, unicode):
return str_or_unicode
else:
raise ValueError("Input '{0}' should be a string or unicode, "
"but its of type {1}".format(str_or_unicode,
... | def ensure_unicode(str_or_unicode) | tests, if the input is ``str`` or ``unicode``. if it is ``str``, it
will be decoded from ``UTF-8`` to unicode. | 2.004869 | 2.2155 | 0.904928 |
if isinstance(str_or_unicode, str):
return str_or_unicode
elif isinstance(str_or_unicode, unicode):
return str_or_unicode.encode('utf-8')
else:
raise ValueError(
"Input '{0}' should be a string or unicode, but it is of "
"type {1}".format(str_or_unicode, ... | def ensure_utf8(str_or_unicode) | tests, if the input is ``str`` or ``unicode``. if it is ``unicode``,
it will be encoded from ``unicode`` to ``utf-8``. otherwise, the
input string is returned. | 1.841166 | 2.039674 | 0.902677 |
if isinstance(str_or_unicode, str):
return str_or_unicode.decode('utf-8').encode('ascii',
'xmlcharrefreplace')
elif isinstance(str_or_unicode, unicode):
return str_or_unicode.encode('ascii', 'xmlcharrefreplace')
else:
raise Va... | def ensure_ascii(str_or_unicode) | tests, if the input is ``str`` or ``unicode``. if it is ``unicode``,
it will be encoded from ``unicode`` to 7-bit ``latin-1``.
otherwise, the input string is converted from ``utf-8`` to 7-bit
``latin-1``. 7-bit latin-1 doesn't even contain umlauts, but
XML/HTML-style escape sequences (e.g. ``ä`` becomes... | 1.917785 | 2.056129 | 0.932716 |
assert isinstance(node_id, (int, str, unicode)),\
"node ID must be an int, str or unicode, not".format(type(node_id))
if isinstance(node_id, (str, unicode)):
return FORBIDDEN_XPOINTER_RE.sub('_', node_id)
else:
return node_id | def ensure_xpointer_compatibility(node_id) | makes a given node ID xpointer compatible.
xpointer identifiers must not contain ':', so we'll
replace it by '_'.
Parameters
----------
node_id : str or unicode or int
a node or edge ID
Returns
-------
xpointer_id : str or unicode or int
int IDs are returned verbatim, s... | 3.292768 | 3.266606 | 1.008009 |
if not isinstance(dict_like, dict):
try:
dict_like = dict(dict_like)
except Exception as e:
raise ValueError("{0}\nCan't convert container to dict: "
"{1}".format(e, dict_like))
return {prefix + k: v for (k, v) in dict_like.items()} | def add_prefix(dict_like, prefix) | takes a dict (or dict-like object, e.g. etree._Attrib) and adds the
given prefix to each key. Always returns a dict (via a typecast).
Parameters
----------
dict_like : dict (or similar)
a dictionary or a container that implements .items()
prefix : str
the prefix string to be prepend... | 2.780526 | 3.254411 | 0.854387 |
import sys
import errno
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST:
if os.path.isdir(path):
pass
else: # if something exists at the path, but it's not a dir
raise
elif exc... | def create_dir(path) | Creates a directory. Warns, if the directory can't be accessed. Passes,
if the directory already exists.
modified from http://stackoverflow.com/a/600612
Parameters
----------
path : str
path to the directory to be created | 2.976106 | 3.01696 | 0.986459 |
import os
import fnmatch
if isinstance(dir_or_filelist, str):
directory = dir_or_filelist
abspath = os.path.abspath(os.path.expanduser(directory))
for root, dirs, files in os.walk(abspath):
for basename in files:
if fnmatch.fnmatch(basename, pattern... | def find_files(dir_or_filelist, pattern='*') | If given a path to a directory, finds files recursively,
e.g. all *.txt files in a given directory (or its subdirectories).
If given a list of files, yields all of the files that match the given
pattern.
adapted from: http://stackoverflow.com/a/2186673 | 1.894996 | 1.847058 | 1.025954 |
if isinstance(string_or_unicode, unicode):
return string_or_unicode.strip()
elif isinstance(string_or_unicode, str):
return string_or_unicode.decode('utf-8').strip()
else: # e.g. if input is None
return u'' | def sanitize_string(string_or_unicode) | remove leading/trailing whitespace and always return unicode. | 2.568725 | 2.28382 | 1.124749 |
if isinstance(element, (etree._Element, etree._ElementTree)):
print etree.tostring(element, pretty_print=True)
else:
if hasattr(element, 'xml'):
print etree.tostring(element.xml, pretty_print=True) | def xmlprint(element) | pretty prints an ElementTree (or an Element of it), or the XML
representation of a SaltDocument (or an element
thereof, e.g. a node, edge, layer etc.) | 2.143759 | 2.014766 | 1.064024 |
def make_nodelabels_explicit(docgraph):
for node_id, node_attribs in docgraph.nodes(data=True):
if 'label' in docgraph.node[node_id]:
docgraph.node[node_id]['label'] = \
u"{0}_{1}".format(node_attribs['label'], node_id)
return docgraph
def m... | def make_labels_explicit(docgraph) | Appends the node ID to each node label and appends the edge type to each
edge label in the given document graph. This can be used to debug a
graph visually with ``write_dot``.
Parameters
----------
docgraph : DiscourseDocumentGraph
document graph from which the nodes will be extracted
... | 1.82346 | 1.776708 | 1.026314 |
'''
creates and prints a barplot (using matplotlib) for all values that an
attribute can have, e.g. counts of POS tags for all token nodes in a
document graph.
docgraph : DiscourseDocumentGraph
the document graph from which we'll extract node/edge attributes
elements : collections.Itera... | def plot_attribute_distribution(docgraph, elements, attribute,
ignore_missing=True) | creates and prints a barplot (using matplotlib) for all values that an
attribute can have, e.g. counts of POS tags for all token nodes in a
document graph.
docgraph : DiscourseDocumentGraph
the document graph from which we'll extract node/edge attributes
elements : collections.Iterable
... | 3.310454 | 2.05838 | 1.608281 |
adict = dict(*args, **kwds)
rx = re.compile('|'.join(map(re.escape, adict)))
def one_xlat(match):
return adict[match.group(0)]
def xlat(text):
return rx.sub(one_xlat, text)
return xlat | def create_multiple_replace_func(*args, **kwds) | You can call this function and pass it a dictionary, or any other
combination of arguments you could pass to built-in dict in order to
construct a dictionary. The function will return a xlat closure that
takes as its only argument text the string on which the substitutions
are desired and returns a copy... | 2.69927 | 2.442443 | 1.105152 |
for unit_id in sorted(select_nodes_by_layer(docgraph, conano_namespace+':unit'),
key=natural_sort_key):
yield (unit_id, get_span(docgraph, unit_id)) if data else (unit_id) | def get_conano_units(docgraph, data=True, conano_namespace='conano') | yield all Conano units that occur in the given document graph,
sorted by their unit ID. int(ernal) and ext(ernal) count as distinct units.
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph which contains Conano annotations
data : bool
If True (default), yields... | 4.568932 | 4.597655 | 0.993753 |
unit_index, _unit_type = unit_id.split(':')
connective_id = unit_index+':connective'
return ' '.join(docgraph.get_token(tok_id).lower()
for tok_id in get_span(docgraph, connective_id)) | def get_connective(docgraph, unit_id) | returns the lowercased string of the connective used in the given Conano unit. | 4.363168 | 3.871338 | 1.127044 |
if element.tag == 'unit':
element_node_id = element.attrib['id']+':'+element.attrib['type']
node_layers = {self.ns, self.ns+':unit', self.ns+':'+element.attrib['type']}
elif element.tag == 'connective':
element_node_id = element.attrib['id']+':connective'
... | def _add_element(self, element, parent_node) | add an element (i.e. a unit/connective/discourse or modifier)
to the docgraph. | 2.441718 | 2.242151 | 1.089007 |
if parent_node == 'root':
parent_node = self.root
token_node_id = 'token:{}'.format(self.token_count)
self.add_node(token_node_id, layers={self.ns, self.ns+':token'},
attr_dict={self.ns+':token': token})
self.add_edge(parent_node, token_node_id... | def _add_token(self, token, parent_node='root') | add a token to this docgraph | 3.386978 | 3.12535 | 1.083712 |
conano_plaintext = etree.tostring(tree, encoding='utf8', method='text')
token_str_list = conano_plaintext.split()
for i, plain_token in enumerate(token_str_list):
graph_token = self.node[self.tokens[i]][self.ns+':token']
if ensure_unicode(plain_token) != graph_to... | def is_valid(self, tree) | returns true, iff the order of the tokens in the graph are the
same as in the Conano file (converted to plain text). | 5.568471 | 4.15328 | 1.34074 |
regex_match = ANNOTATED_ANAPHORA_REGEX.search(token)
if regex_match: # token is annotated
unannotated_token = regex_match.group('token')
unicode_token = ensure_unicode(unannotated_token)
annotation = regex_match.group('annotation')
anno_type = AN... | def __add_token_to_document(self, token, token_id, connected) | adds a token to the document graph as a node with the given ID.
Parameters
----------
token : str
the token to be added to the document graph
token_id : int
the node ID of the token to be added, which must not yet
exist in the document graph
c... | 2.794698 | 2.835058 | 0.985764 |
if isinstance(string, int):
string = str(string)
escaped_str = QUOTE_RE.sub(r'\\"', string)
return u'"{}"'.format(escaped_str) | def quote_for_pydot(string) | takes a string (or int) and encloses it with "-chars. if the string
contains "-chars itself, they will be escaped. | 3.644334 | 3.588466 | 1.015569 |
for (node_id, attrs) in nodes_with_data:
if 'label' in attrs:
yield (quote_for_pydot(node_id),
{'label': quote_for_pydot(attrs['label'])})
else:
yield (quote_for_pydot(node_id), {}) | def _preprocess_nodes_for_pydot(nodes_with_data) | throw away all node attributes, except for 'label | 2.68816 | 2.639306 | 1.01851 |
for (source, target, attrs) in edges_with_data:
if 'label' in attrs:
yield (quote_for_pydot(source), quote_for_pydot(target),
{'label': quote_for_pydot(attrs['label'])})
else:
yield (quote_for_pydot(source), quote_for_pydot(target), {}) | def _preprocess_edges_for_pydot(edges_with_data) | throw away all edge attributes, except for 'label | 2.190115 | 2.1248 | 1.030739 |
stripped_graph = nx.MultiDiGraph()
stripped_graph.name = docgraph.name
nodes = _preprocess_nodes_for_pydot(docgraph.nodes_iter(data=True))
edges = _preprocess_edges_for_pydot(docgraph.edges_iter(data=True))
stripped_graph.add_nodes_from(nodes)
stripped_graph.add_edges_from(edges)
retu... | def preprocess_for_pydot(docgraph) | takes a document graph and strips all the information that aren't
necessary for visualizing it with graphviz. ensures that all
node/edge names and labels are properly quoted.
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph
Returns
-------
stripped_graph ... | 2.108298 | 2.123728 | 0.992735 |
stripped_graph = preprocess_for_pydot(docgraph)
return nx.drawing.nx_pydot.to_pydot(stripped_graph).to_string() | def print_dot(docgraph) | converts a document graph into a dot file and returns it as a string.
If this function call is prepended by %dotstr,
it will display the given document graph as a dot/graphviz graph
in the currently running IPython notebook session.
To use this function, the gvmagic IPython notebook extension
need... | 3.932134 | 5.383496 | 0.730405 |
# you can pass a function f(old_label)->new_label
# but we'll just make a dictionary here regardless
if not hasattr(mapping, "__getitem__"):
m = dict((n, mapping(n)) for n in G)
else:
m = mapping
if copy:
return _relabel_copy(G, m)
else:
return _relabel_inpla... | def relabel_nodes(G, mapping, copy=True) | Relabel the nodes of the graph G.
Parameters
----------
G : graph
A NetworkX graph
mapping : dictionary
A dictionary with the old labels as keys and new labels as values.
A partial mapping is allowed.
copy : bool (optional, default=True)
If True return a copy, or if Fa... | 3.706129 | 4.695041 | 0.789371 |
N = G.number_of_nodes() + first_label
if ordering == "default":
mapping = dict(zip(G.nodes(), range(first_label, N)))
elif ordering == "sorted":
nlist = G.nodes()
nlist.sort()
mapping = dict(zip(nlist, range(first_label, N)))
elif ordering == "increasing degree":
... | def convert_node_labels_to_integers(G, first_label=0, ordering="default",
label_attribute=None) | Return a copy of the graph G with the nodes relabeled with integers.
Parameters
----------
G : graph
A NetworkX graph
first_label : int, optional (default=0)
An integer specifying the offset in numbering nodes.
The n new integer labels are numbered first_label, ..., n-1+first_labe... | 2.072031 | 2.078831 | 0.996729 |
exmaralda_file = ExmaraldaFile(docgraph)
assert isinstance(output_file, (str, file))
if isinstance(output_file, str):
path_to_file = os.path.dirname(output_file)
if not os.path.isdir(path_to_file):
create_dir(path_to_file)
exmaralda_file.write(output_file)
else: ... | def write_exb(docgraph, output_file) | converts a DiscourseDocumentGraph into an Exmaralda ``*.exb`` file and
writes it to the given file (or file path). | 2.394722 | 2.42605 | 0.987087 |
with open(output_filepath, 'w') as out_file:
out_file.write(self.__str__()) | def write(self, output_filepath) | serialize the ExmaraldaFile instance and write it to a file.
Parameters
----------
output_filepath : str
relative or absolute path to the Exmaralda file to be created | 2.806593 | 3.171238 | 0.885015 |
E = self.E
root = E('basic-transcription')
head = E('head')
meta = E('meta-information')
project = E('project-name')
tname = E('transcription-name')
ref_file = E('referenced-file', url="")
ud = E('ud-meta-information')
comment = E('commen... | def __create_document_header(self) | Look, mum! XML generation without string concatenation!1!!
This creates an empty, but functional header for an Exmaralda *.exb
file. | 3.848088 | 3.477739 | 1.106492 |
E = self.E
root = self.__create_document_header()
body = E('basic-body')
timeline = E('common-timeline')
# for n tokens we need to create n+1 timeline indices
for i in xrange(len(docgraph.tokens)+1):
idx = str(i)
# example: <tli id="T0" ... | def __add_document_structure(self, docgraph,
remove_redundant_layers=True) | return an Exmaralda XML etree representation a docgraph | 4.469504 | 4.117937 | 1.085375 |
layer_cat = annotation_layer.split(':')[-1]
temp_tier = self.E('tier',
{'id': "TIE{}".format(self.tier_count),
'category': layer_cat, 'type': "t",
'display-name': "[{}]".format(annotation_layer)})
self.ti... | def __add_annotation_tier(self, docgraph, body, annotation_layer) | adds a span-based annotation layer as a <tier> to the Exmaralda <body>.
Parameter
---------
docgraph : DiscourseDocumentGraph
the document graph from which the chains will be extracted
body : etree._Element
an etree representation of the <basic_body> element (and... | 3.659988 | 3.663523 | 0.999035 |
E = self.E
for i, chain in enumerate(get_pointing_chains(docgraph)):
chain_tier = E('tier',
{'id': "TIE{}".format(self.tier_count),
'category': "chain", 'type': "t",
'display-name': "[coref-chain-{}]... | def __add_coreference_chain_tiers(self, docgraph, body,
min_chain_length=3) | Parameters
----------
docgraph : DiscourseDocumentGraph
the document graph from which the chains will be extracted
body : etree._Element
an etree representation of the <basic_body> element (and all its
descendants) of the Exmaralda file
min_chain_lengt... | 3.806071 | 3.88387 | 0.979969 |
E = self.E
token_tier = E('tier',
{'id': "TIE{}".format(self.tier_count),
'category': "tok", 'type': "t",
'display-name': "[tok]"})
self.tier_count += 1
token_attribs = defaultdict(lambda: defaultdict(str))
... | def __add_token_tiers(self, docgraph, body) | adds all tiers that annotate single tokens (e.g. token string, lemma,
POS tag) to the etree representation of the Exmaralda XML file.
Parameters
----------
docgraph : DiscourseDocumentGraph
the document graph to be converted
body : etree._Element
an etree... | 2.962558 | 2.937461 | 1.008544 |
for token_id in self.get_token_ids(tree):
self.add_node(token_id, layers={self.ns})
self.tokens.append(token_id) | def __add_tokenization(self, tree) | adds a node for each token ID in the document | 5.93905 | 4.532268 | 1.310392 |
if tier.attrib['category'] == token_tier_name:
self.__add_tokens(tier)
else:
if self.is_token_annotation_tier(tier):
self.__add_token_annotation_tier(tier)
else:
self.__add_span_tier(tier) | def __add_tier(self, tier, token_tier_name) | adds a tier to the document graph (either as additional attributes
to the token nodes or as a span node with outgoing edges to the token
nodes it represents) | 3.675349 | 3.271431 | 1.123468 |
for event in token_tier.iter('event'):
assert len(self.gen_token_range(event.attrib['start'],
event.attrib['end'])) == 1, \
"Events in the token tier must not span more than one token."
token_id = event.attrib['start']
self.node... | def __add_tokens(self, token_tier) | adds all tokens to the document graph. Exmaralda considers them to
be annotations as well, that's why we could only extract the token
node IDs from the timeline (using ``__add_tokenization()``), but not
the tokens themselves.
Parameters
----------
token_tier : etree._Ele... | 5.820255 | 5.873892 | 0.990869 |
for i, event in enumerate(tier.iter('event')):
if self.indexdelta(event.attrib['end'], event.attrib['start']) != 1:
return False
return True | def is_token_annotation_tier(self, tier) | returns True, iff all events in the given tier annotate exactly one
token. | 6.225352 | 4.697144 | 1.325348 |
for i, event in enumerate(tier.iter('event')):
anno_key = '{0}:{1}'.format(self.ns, tier.attrib['category'])
anno_val = event.text if event.text else ''
self.node[event.attrib['start']][anno_key] = anno_val | def __add_token_annotation_tier(self, tier) | adds a tier to the document graph, in which each event annotates
exactly one token. | 4.886722 | 4.893261 | 0.998664 |
tier_id = tier.attrib['id']
# add the tier's root node with an inbound edge from the document root
self.add_node(
tier_id, layers={self.ns, self.ns+':tier'},
attr_dict={self.ns+':category': tier.attrib['category'],
self.ns+':type': tier.att... | def __add_span_tier(self, tier) | adds a tier to the document graph in which each event annotates a span
of one or more tokens. | 3.119525 | 2.939451 | 1.061261 |
def tok2time(token_element):
'''
extracts the time (float) of a <tli> element
(i.e. the absolute position of a token in the document)
'''
return float(token_element.attrib['time'])
timeline = tree.find('//common-timeline')
ret... | def get_token_ids(tree) | returns a list of all token IDs occuring the the given exmaralda file,
sorted by their time stamp in ascending order. | 7.969499 | 6.626981 | 1.202584 |
return self.tokenid2index(stop_id) - self.tokenid2index(start_id) | def indexdelta(self, stop_id, start_id) | returns the distance (int) between to idices.
Two consecutive tokens must have a delta of 1. | 4.94671 | 3.87445 | 1.276751 |
index_range = range(self.tokenid2index(start_id), self.tokenid2index(stop_id))
return ["T{}".format(index) for index in index_range] | def gen_token_range(self, start_id, stop_id) | returns a list of all token IDs in the given, left-closed,
right-open interval (i.e. includes start_id, but excludes stop_id)
>>> gen_token_range('T0', 'T1')
['T0']
>>> gen_token_range('T1', 'T5')
['T1', 'T2', 'T3', 'T4'] | 4.144125 | 5.282781 | 0.784459 |
old2new = create_token_mapping(docgraph_with_old_names,
docgraph_with_new_names, verbose=verbose)
# save the mappings from old to new token node IDs in the `renamed_nodes`
# attribute of the merged graph
if hasattr(docgraph_with_new_names, 'renamed_nodes'):
... | def rename_tokens(docgraph_with_old_names, docgraph_with_new_names, verbose=False) | Renames the tokens of a graph (``docgraph_with_old_names``) in-place,
using the token names of another document graph
(``docgraph_with_new_names``). Also updates the ``.tokens`` list of the old
graph.
This will only work, iff both graphs have the same tokenization. | 2.667073 | 2.777803 | 0.960138 |
def kwic_string(docgraph, keyword_index):
tokens = [tok for (tokid, tok) in list(docgraph.get_tokens())]
before, keyword, after = get_kwic(tokens, keyword_index)
return "{0} (Index: {1}): {2} [[{3}]] {4}\n".format(
docgraph.name, keyword_index, ' '.join(before), keyword,
... | def create_token_mapping(docgraph_with_old_names, docgraph_with_new_names,
verbose=False) | given two document graphs which annotate the same text and which use the
same tokenization, creates a dictionary with a mapping from the token
IDs used in the first graph to the token IDs used in the second graph.
Parameters
----------
docgraph_with_old_names : DiscourseDocumentGraph
a docu... | 2.373979 | 2.382499 | 0.996424 |
text_length = len(tokens)
start_before = max(0, index-context_window)
end_before = max(0, index)
before = tokens[start_before:end_before]
start_after = min(text_length, index+1)
end_after = min(text_length, index+context_window+1)
after = tokens[start_after:end_after]
return before,... | def get_kwic(tokens, index, context_window=5) | keyword in context
Parameters
----------
tokens : list of str
a text represented as a list of tokens
index : int
the index of the keyword in the token list
context_window : int
the number of preceding/succeding words of the keyword to be
retrieved
Returns
--... | 2.096131 | 2.435299 | 0.860728 |
all_layers = set()
for node_id, node_attribs in docgraph.nodes_iter(data=True):
for layer in node_attribs['layers']:
all_layers.add(layer)
return all_layers | def get_node_annotation_layers(docgraph) | WARNING: this is higly inefficient!
Fix this via Issue #36.
Returns
-------
all_layers : set or dict
the set of all annotation layers used for annotating nodes in the given
graph | 2.437154 | 2.975023 | 0.819205 |
all_layers = set()
for source_id, target_id, edge_attribs in docgraph.edges_iter(data=True):
for layer in edge_attribs['layers']:
all_layers.add(layer)
return all_layers | def get_edge_annotation_layers(docgraph) | WARNING: this is higly inefficient!
Fix this via Issue #36.
Returns
-------
all_layers : set or dict
the set of all annotation layers used for annotating edges in the given
graph | 2.843247 | 3.292768 | 0.863483 |
try:
span = get_span(docgraph, node_id)
# workaround for issue #138
# TODO: when #138 is fixed, just take the first onset / last offset
onsets, offsets = zip(*[docgraph.get_offsets(tok_node)
for tok_node in span])
return (min(onsets), max(... | def get_span_offsets(docgraph, node_id) | returns the character start and end position of the span of text that
the given node spans or dominates.
Returns
-------
offsets : tuple(int, int)
character onset and offset of the span | 5.735046 | 5.500049 | 1.042726 |
if debug is True and is_directed_acyclic_graph(docgraph) is False:
warnings.warn(
("Can't reliably extract span '{0}' from cyclical graph'{1}'."
"Maximum recursion depth may be exceeded.").format(node_id,
docgrap... | def get_span(docgraph, node_id, debug=False) | returns all the tokens that are dominated or in a span relation with
the given node. If debug is set to True, you'll get a warning if the
graph is cyclic.
Returns
-------
span : list of str
sorted list of token nodes (token node IDs) | 4.265594 | 4.578093 | 0.93174 |
if node_id:
tokens = (docgraph.node[node_id][docgraph.ns+':token']
for node_id in get_span(docgraph, node_id))
else:
tokens = (docgraph.node[token_id][docgraph.ns+':token']
for token_id in docgraph.tokens)
return ' '.join(tokens) | def get_text(docgraph, node_id=None) | returns the text (joined token strings) that the given node dominates
or spans. If no node ID is given, returns the complete text of the
document | 3.026158 | 3.171037 | 0.954312 |
return ' '.join(docgraph.node[token_id][docgraph.ns+':token']
for token_id in token_ids) | def tokens2text(docgraph, token_ids) | given a list of token node IDs, returns a their string representation
(concatenated token strings). | 5.63351 | 5.592497 | 1.007334 |
if namespace is None:
namespace = docgraph.ns
return namespace+':token' in docgraph.node[node_id] | def istoken(docgraph, node_id, namespace=None) | returns true, iff the given node ID belongs to a token node.
Parameters
----------
node_id : str
the node to be checked
namespace : str or None
If a namespace is given, only look for tokens in the given namespace.
Otherwise, look for tokens in the default namespace of the given
... | 4.323555 | 4.826814 | 0.895737 |
first_onset, last_offset = get_span_offsets(docgraph, dominating_node)
span_range = xrange(first_onset, last_offset+1)
token_offsets = (docgraph.get_offsets(tok)
for tok in get_span(docgraph, dominating_node))
char_positions = set(itertools.chain.from_iterable(xrange(on, off+1... | def is_continuous(docgraph, dominating_node) | return True, if the tokens dominated by the given node are all adjacent | 3.512709 | 3.362517 | 1.044667 |
for node_id in docgraph.neighbors_iter(node):
node_layers = docgraph.node[node_id]['layers']
if isinstance(layer, (str, unicode)):
condition = layer in node_layers
else: # ``layer`` is a list/set/dict of layers
condition = any(l in node_layers for l in layer)
... | def select_neighbors_by_layer(docgraph, node, layer, data=False) | Get all neighboring nodes belonging to (any of) the given layer(s),
A neighboring node is a node that the given node connects to with an
outgoing edge.
Parameters
----------
docgraph : DiscourseDocumentGraph
document graph from which the nodes will be extracted
layer : str or collection... | 2.878548 | 2.852246 | 1.009222 |
assert isinstance(docgraph, MultiGraph)
for neighbor_id in docgraph.neighbors_iter(source):
edges = docgraph[source][neighbor_id].values()
if attribute is None:
has_attrib = True # don't filter neighbors
else:
has_attrib = any(attribute in edge for edge in e... | def select_neighbors_by_edge_attribute(docgraph, source,
attribute=None, value=None, data=False) | Get all neighbors with the given edge attribute value(s). | 2.563436 | 2.561549 | 1.000737 |
for node_id, node_attribs in docgraph.nodes_iter(data=True):
if layer is None:
condition = True # don't filter nodes
elif isinstance(layer, (str, unicode)):
condition = layer in node_attribs['layers']
else: # ``layer`` is a list/set/dict of layers
co... | def select_nodes_by_layer(docgraph, layer=None, data=False) | Get all nodes belonging to (any of) the given layer(s).
Parameters
----------
docgraph : DiscourseDocumentGraph
document graph from which the nodes will be extracted
layer : str or collection of str or None
name(s) of the layer(s) to select nodes from. If None, returns all
nodes... | 2.603893 | 2.628013 | 0.990822 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.