code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
sent_id = 's{}'.format(sent_number)
self.add_node(sent_id, layers={self.ns, self.ns+':sentence'},
tokens=[])
self.add_edge(self.root, sent_id,
layers={self.ns, self.ns+':sentence'},
edge_type=EdgeTypes.dominance_relation)... | def __add_sentence_root_node(self, sent_number) | adds the root node of a sentence to the graph and the list of sentences
(``self.sentences``). the node has a ``tokens` attribute, which
contains a list of the tokens (token node IDs) of this sentence.
Parameters
----------
sent_number : int
the index of the sentence ... | 3.864255 | 4.094193 | 0.943838 |
token_id = '{0}_t{1}'.format(sent_id, word.word_id)
feats = word._asdict()
# dicts can't be generated and updated at once
feats.update({self.ns+':token': word.token, 'label': word.token,
'word_pos': int(word.word_id)})
self.__add_morph_features(feat... | def __add_token(self, word, sent_id, feat_format='unknown') | adds a token to the document graph (with all the features given
in the columns of the CoNLL file).
Parameters
----------
word : Conll2009Word or Conll2010Word
a namedtuple representing all the information stored in a CoNLL
file line (token, lemma, pos, dependenci... | 5.017986 | 5.151325 | 0.974116 |
# 'head_attr': (projected) head
head = word_instance.__getattribute__(self.head_attr)
deprel = word_instance.__getattribute__(self.deprel_attr)
if head == '0':
# word represents the sentence root
source_id = sent_id
else:
source_id = '... | def __add_dependency(self, word_instance, sent_id) | adds an ingoing dependency relation from the projected head of a token
to the token itself. | 4.168538 | 3.973017 | 1.049212 |
assert feature_format in ('attrib_val', 'val_only', 'unknown')
def add_val_only_features(token_dict, feature_string):
feature_values = feature_string.split('|')
for feat_val in feature_values:
for morph_cat in MORPHOLOGICAL_FEATURES:
... | def __add_morph_features(self, token_dict, feature_string,
feature_format='unknown') | Parameters
----------
token_dict : dict
the node attribute dict belonging to a token node
feature_string : str
a string representing the (grammatical) features of a token
feature_format : str
Format of the feature string (i.e. ``attrib_val``, ``val_onl... | 2.530876 | 2.455759 | 1.030588 |
tok2markables = defaultdict(set)
markable2toks = defaultdict(list)
markable2chains = defaultdict(list)
coreference_chains = get_pointing_chains(self.docgraph,
layer=coreference_layer)
for chain_id, chain in enumerate(core... | def __build_markable_token_mapper(self, coreference_layer=None,
markable_layer=None) | Creates mappings from tokens to the markable spans they belong to
and the coreference chains these markables are part of.
Returns
-------
tok2markables : dict (str -> set of str)
Maps from a token (node ID) to all the markables (node IDs)
it is part of.
m... | 2.816845 | 2.569344 | 1.096329 |
span = self.markable2toks[markable_id]
coref_str = str(target_id)
if span.index(token_id) == 0:
# token is the first element of a markable span
coref_str = '(' + coref_str
if span.index(token_id) == len(span)-1:
# token is the last element of ... | def __gen_coref_str(self, token_id, markable_id, target_id) | generates the string that represents the markables and coreference
chains that a token is part of.
Parameters
----------
token_id : str
the node ID of the token
markable_id : str
the node ID of the markable span
target_id : int
the ID ... | 2.730764 | 2.653693 | 1.029043 |
sents = []
tokens = []
for i, node in enumerate(nodes):
if i in token_node_indices:
if node.features['tiger.pos'] != '$.':
tokens.append(i)
else: # start a new sentence, if 'tiger.pos' is '$.'
tokens.append(i)
sents.append... | def extract_sentences(nodes, token_node_indices) | given a list of ``SaltNode``\s, returns a list of lists, where each list
contains the indices of the nodes belonging to that sentence. | 3.607369 | 3.568538 | 1.010881 |
ins = SaltElement.from_etree(etree_element)
# TODO: this looks dangerous, ask Stackoverflow about it!
ins.__class__ = SaltNode.mro()[0] # convert SaltElement into SaltNode
ins.layers = get_layer_ids(etree_element)
ins.features = get_annotations(etree_element)
re... | def from_etree(cls, etree_element) | creates a ``SaltNode`` instance from the etree representation of an
<nodes> element from a SaltXMI file. | 8.670064 | 7.51621 | 1.153515 |
layers_attrib_val = ' '.join('//@layers.{}'.format(layer_id)
for layer_id in self.layers)
attribs = {
'{{{pre}}}type'.format(pre=NAMESPACES['xsi']): self.xsi_type,
'layers': layers_attrib_val}
E = ElementMaker()
node... | def to_etree(self) | creates an etree element of a ``SaltNode`` that mimicks a SaltXMI
<nodes> element | 5.902492 | 5.268779 | 1.120277 |
ins = SaltNode.from_etree(etree_element)
# TODO: this looks dangerous, ask Stackoverflow about it!
# convert SaltNode into PrimaryTextNode
ins.__class__ = PrimaryTextNode.mro()[0]
ins.text = extract_primary_text(etree_element)
return ins | def from_etree(cls, etree_element) | creates a ``PrimaryTextNode`` instance from the etree representation of
a <nodes> element from a SaltXMI file. | 10.247524 | 7.260704 | 1.411368 |
dg_copy = deepcopy(docgraph)
remove_root_metadata(dg_copy)
layerset2str(dg_copy)
attriblist2str(dg_copy)
nx_write_gexf(dg_copy, output_file) | def write_gexf(docgraph, output_file) | takes a document graph, converts it into GEXF format and writes it to
a file. | 6.71276 | 6.437424 | 1.042771 |
"Create (DGParented)Tree from a root (str) and a list of (str, list) tuples."
if isinstance(root, Tree):
if children is None:
return root
return root.__class__(root, children, root_id)
elif isinstance(root, basestring):
root = debug_root_label(root, debug, root_id)
... | def t(root, children=None, debug=False, root_id=None) | Create (DGParented)Tree from a root (str) and a list of (str, list) tuples. | 3.417129 | 2.729183 | 1.25207 |
return select_neighbors_by_edge_attribute(
docgraph=docgraph,
source=parent_node_id,
attribute='edge_type',
value=[EdgeTypes.dominance_relation],
data=data) | def get_child_nodes(docgraph, parent_node_id, data=False) | Yield all nodes that the given node dominates or spans. | 5.793869 | 5.250142 | 1.103564 |
parents = []
for src, _, edge_attrs in docgraph.in_edges(child_node, data=True):
if edge_attrs['edge_type'] == EdgeTypes.dominance_relation:
parents.append(src)
if strict and len(parents) > 1:
raise ValueError(("In a syntax tree, a node can't be "
... | def get_parents(docgraph, child_node, strict=True) | Return a list of parent nodes that dominate this child.
In a 'syntax tree' a node never has more than one parent node
dominating it. To enforce this, set strict=True.
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph
strict : bool
If True, raise a ValueEr... | 3.703567 | 3.731152 | 0.992607 |
# calculate positions for the whole graph
root_cond = (sentence_root is None) or (sentence_root == docgraph.root)
if root_cond or ('tokens' not in docgraph.node[sentence_root]):
sentence_root = docgraph.root
token_nodes = docgraph.tokens
path = {}
else: # calculate position... | def horizontal_positions(docgraph, sentence_root=None) | return map: node ID -> first token index (int) it covers | 3.118418 | 3.040557 | 1.025607 |
if source is None:
source = G.root
xpos = horizontal_positions(G, source)
visited = set([source])
source_children = get_child_nodes(G, source)
queue = deque([(source, iter(sorted(source_children,
key=lambda x: xpos[x])))])
while queue:
... | def sorted_bfs_edges(G, source=None) | Produce edges in a breadth-first-search starting at source.
Neighbors appear in the order a linguist would expect in a syntax tree.
The result will only contain edges that express a dominance or spanning
relation, i.e. edges expressing pointing or precedence relations will
be ignored.
Parameters
... | 2.272483 | 2.607735 | 0.871439 |
if source is None:
source = G.root
successors = defaultdict(list)
for src, target in sorted_bfs_edges(G, source):
successors[src].append(target)
return dict(successors) | def sorted_bfs_successors(G, source=None) | Return dictionary of successors in breadth-first-search from source.
Parameters
----------
G : DiscourseDocumentGraph graph
source : node
Specify starting node for breadth-first search and return edges in
the component reachable from source.
Returns
-------
successors: dict
... | 2.847853 | 3.378815 | 0.842856 |
node_attrs = docgraph.node[node_id]
if istoken(docgraph, node_id):
pos_str = node_attrs.get(docgraph.ns+':pos', '')
token_str = node_attrs[docgraph.ns+':token']
return u"({pos}{space1}{token}{space2}{child})".format(
pos=pos_str, space1=bool(pos_str)*' ', token=token_str... | def node2bracket(docgraph, node_id, child_str='') | convert a docgraph node into a PTB-style string. | 2.834278 | 2.777464 | 1.020456 |
if root is None:
root = docgraph.root
if successors is None:
successors = sorted_bfs_successors(docgraph, root)
if root in successors:
embed_str = u" ".join(tree2bracket(docgraph, child, successors)
for child in successors[root])
return nod... | def tree2bracket(docgraph, root=None, successors=None) | convert a docgraph into a PTB-style string.
If root (a node ID) is given, only convert the subgraph that this
node domintes/spans into a PTB-style string. | 2.935686 | 3.054261 | 0.961177 |
if width != 0:
for i, leaf_text in enumerate(parented_tree.leaves()):
dedented_text = textwrap.dedent(leaf_text).strip()
parented_tree[parented_tree.leaf_treeposition(i)] = textwrap.fill(dedented_text, width=width)
return parented_tree | def word_wrap_tree(parented_tree, width=0) | line-wrap an NLTK ParentedTree for pretty-printing | 2.74426 | 2.610635 | 1.051185 |
if node_id is None:
node_id = self.root_id
if node_id in rst_tree.edu_set:
return rst_tree.edus.index(node_id)
return min(self.get_position(rst_tree, child_node_id)
for child_node_id in rst_tree.child_dict[node_id]) | def get_position(self, rst_tree, node_id=None) | Get the linear position of an element of this DGParentedTree in an RSTTree.
If ``node_id`` is given, this will return the position of the subtree
with that node ID. Otherwise, the position of the root of this
DGParentedTree in the given RSTTree is returned. | 2.633512 | 2.621478 | 1.004591 |
if self._use_cache:
r = requests.get(self.url, params=params)
else:
with requests_cache.disabled():
r = requests.get(self.url, params=params)
r.raise_for_status()
return r | def get(self, **params) | Performs get request to the biomart service.
Args:
**params (dict of str: any): Arbitrary keyword arguments, which
are added as parameters to the get request to biomart.
Returns:
requests.models.Response: Response from biomart for the request. | 2.476274 | 2.6762 | 0.925295 |
temp = tempfile.NamedTemporaryFile(delete=False)
temp.write(ptb_string)
temp.close()
ptb_docgraph = cls(ptb_filepath=temp.name, namespace=namespace,
precedence=precedence, ignore_traces=ignore_traces)
os.unlink(temp.name)
return ptb_doc... | def fromstring(cls, ptb_string, namespace='ptb', precedence=False,
ignore_traces=True) | create a PTBDocumentGraph from a string containing PTB parses. | 2.429108 | 2.049075 | 1.185466 |
self.sentences.append(self._node_id)
# add edge from document root to sentence root
self.add_edge(self.root, self._node_id, edge_type=dg.EdgeTypes.dominance_relation)
self._parse_sentencetree(sentence, ignore_traces=ignore_traces)
self._node_id += 1 | def _add_sentence(self, sentence, ignore_traces=True) | add a sentence from the input document to the document graph.
Parameters
----------
sentence : nltk.tree.Tree
a sentence represented by a Tree instance | 4.748869 | 4.642423 | 1.022929 |
def get_nodelabel(node):
if isinstance(node, nltk.tree.Tree):
return node.label()
elif isinstance(node, unicode):
return node.encode('utf-8')
else:
raise ValueError("Unexpected node type: {0}, {1}".format(type(node), no... | def _parse_sentencetree(self, tree, parent_node_id=None, ignore_traces=True) | parse a sentence Tree into this document graph | 3.706062 | 3.6615 | 1.01217 |
xsi_type = get_xsi_type(element)
element_class = XSI_TYPE_CLASSES[xsi_type]
return element_class.from_etree(element) | def create_class_instance(element, element_id, doc_id) | given an Salt XML element, returns a corresponding `SaltElement` class
instance, i.e. a SaltXML `SToken` node will be converted into a
`TokenNode`.
Parameters
----------
element : lxml.etree._Element
an `etree._Element` is the XML representation of a Salt element,
e.g. a single 'nod... | 3.938016 | 5.849136 | 0.673264 |
return [i for (i, element) in enumerate(elements)
if isinstance(element, subtype)] | def subtype_ids(elements, subtype) | returns the ids of all elements of a list that have a certain type,
e.g. show all the nodes that are ``TokenNode``\s. | 4.129331 | 4.068899 | 1.014852 |
all_elements = tree.findall('//')
tag_counter = defaultdict(int)
for element in all_elements:
tag_counter[element.tag] += 1
for (tag, counts) in tag_counter.items():
print "{0}: {1}".format(tag, counts) | def tree_statistics(tree) | prints the types and counts of elements present in a SaltDocument tree,
e.g.::
layers: 3
sDocument: 1
nodes: 252
labels: 2946
edges: 531 | 3.01442 | 3.425317 | 0.880041 |
abs_dir = os.path.abspath(directory)
filenames = os.listdir(abs_dir)
return [os.path.join(abs_dir, filename) for filename in filenames] | def abslistdir(directory) | returns a list of absolute filepaths for all files found in the given
directory. | 2.08977 | 2.138708 | 0.977118 |
# creates a new attribute, e.g. 'self.nodes' and assigns it an
# empty list
setattr(self, element_type, [])
etree_elements = get_elements(tree, element_type)
for i, etree_element in enumerate(etree_elements):
# create an instance of an element class (e.g. Tok... | def _extract_elements(self, tree, element_type) | extracts all element of type `element_type from the `_ElementTree`
representation of a SaltXML document and adds them to the corresponding
`SaltDocument` attributes, i.e. `self.nodes`, `self.edges` and
`self.layers`.
Parameters
----------
tree : lxml.etree._ElementTree
... | 4.445327 | 4.067224 | 1.092963 |
tokens = [self.print_token(tok_idx)
for tok_idx in self.sentences[sent_index]]
return ' '.join(tokens) | def print_sentence(self, sent_index) | returns the string representation of a sentence.
:param sent_index: the index of a sentence (from ``self.sentences``)
:type sent_index: int
:return: the sentence string
:rtype: str | 4.017502 | 4.326275 | 0.928628 |
err_msg = "The given node is not a token node."
assert isinstance(self.nodes[token_node_index], TokenNode), err_msg
onset = self.nodes[token_node_index].onset
offset = self.nodes[token_node_index].offset
return self.text[onset:offset] | def print_token(self, token_node_index) | returns the string representation of a token. | 2.812722 | 2.570117 | 1.094395 |
for edge_index in self._textual_relation_ids:
token_node_index = self.edges[edge_index].source
self.nodes[token_node_index].onset = self.edges[edge_index].onset
self.nodes[token_node_index].offset = self.edges[edge_index].offset | def _add_offsets_to_token_nodes(self) | Adds primary text string onsets/offsets to all nodes that represent
tokens. In SaltDocuments, this data was stored in TextualRelation
edges only. | 3.3646 | 2.354489 | 1.429015 |
span_dict = defaultdict(list)
for span_edge in self._spanning_relation_ids:
token_node_id = self.edges[span_edge].target
span_node_id = self.edges[span_edge].source
span_dict[span_node_id].append(token_node_id)
for span_node_id in span_dict:
... | def _add_token_node_ids_to_span_nodes(self) | Adds to every span node the list of tokens (token node IDs) that belong
to it.
SpanNode.tokens - a list of `int` ids of `TokenNode`s | 2.486592 | 2.428676 | 1.023847 |
span_dict = defaultdict(list)
for span_edge in self._spanning_relation_ids:
token_node_id = self.edges[span_edge].target
span_node_id = self.edges[span_edge].source
span_dict[token_node_id].append(span_node_id)
for token_node_id in span_dict:
... | def _add_span_node_ids_to_token_nodes(self) | Adds to every token node the list of spans (span node IDs) that it
belongs to.
TokenNode.spans - a list of `int` ids of `SpanNode`s | 2.52571 | 2.362742 | 1.068974 |
'''
detect_stream_mode - Detect the mode on a given stream
@param stream <object> - A stream object
If "mode" is present, that will be used.
@return <type> - "Bytes" type or "str" type
'''
# If "Mode" is present, pull from that
if hasattr(stream, 'mode'):
... | def detect_stream_mode(stream) | detect_stream_mode - Detect the mode on a given stream
@param stream <object> - A stream object
If "mode" is present, that will be used.
@return <type> - "Bytes" type or "str" type | 4.909322 | 2.845509 | 1.725288 |
fpaths = []
base = os.path.dirname(src_dir)
for root, dir, files in os.walk(src_dir):
if len(files) != 0:
for f in files:
fpaths.append(os.path.relpath(os.path.join(root, f), base))
return fpaths | def gen_data_files(src_dir) | generates a list of files contained in the given directory (and its
subdirectories) in the format required by the ``package_data`` parameter
of the ``setuptools.setup`` function.
Parameters
----------
src_dir : str
(relative) path to the directory structure containing the files to
b... | 2.262785 | 2.551337 | 0.886902 |
node_attrs = docgraph.node[node_id]
if istoken(docgraph, node_id):
token_str = escape_func(node_attrs[docgraph.ns+':token'])
if include_pos:
pos_str = escape_func(node_attrs.get(docgraph.ns+':pos', ''))
return u"({pos}({token}){child})".format(
pos=po... | def node2freqt(docgraph, node_id, child_str='', include_pos=False,
escape_func=FREQT_ESCAPE_FUNC) | convert a docgraph node into a FREQT string. | 2.315041 | 2.282006 | 1.014477 |
if successors is None:
successors = sorted_bfs_successors(docgraph, root)
if root in successors: # root node has children / subgraphs
embed_str = u"".join(sentence2freqt(docgraph, child, successors,
include_pos=include_pos,
... | def sentence2freqt(docgraph, root, successors=None, include_pos=False,
escape_func=FREQT_ESCAPE_FUNC) | convert a sentence subgraph into a FREQT string. | 2.408735 | 2.314637 | 1.040653 |
if root is None:
return u"\n".join(
sentence2freqt(docgraph, sentence, include_pos=include_pos,
escape_func=escape_func)
for sentence in docgraph.sentences)
else:
return sentence2freqt(docgraph, root, include_pos=include_pos,
... | def docgraph2freqt(docgraph, root=None, include_pos=False,
escape_func=FREQT_ESCAPE_FUNC) | convert a docgraph into a FREQT string. | 2.015236 | 2.030381 | 0.992541 |
path_to_file = os.path.dirname(output_filepath)
if not os.path.isdir(path_to_file):
create_dir(path_to_file)
with codecs.open(output_filepath, 'w', 'utf-8') as output_file:
for sentence in docgraph.sentences:
output_file.write(docgraph2freqt(docgraph, sentence,
... | def write_freqt(docgraph, output_filepath, include_pos=False) | convert a docgraph into a FREQT input file (one sentence per line). | 2.413552 | 2.289301 | 1.054275 |
Plugin.options(self, parser, env)
parser.add_option('--xcoverage-file', action='store',
default=env.get('NOSE_XCOVER_FILE', 'coverage.xml'),
dest='xcoverage_file',
metavar="FILE",
help='Path ... | def options(self, parser, env) | Add options to command line. | 2.762436 | 2.734024 | 1.010392 |
if not self.xcoverageToStdout:
# This will create a false stream where output will be ignored
stream = StringIO()
super(XCoverage, self).report(stream)
if not hasattr(self, 'coverInstance'):
# nose coverage plugin 1.0 and earlier
... | def report(self, stream) | Output code coverage report. | 6.819279 | 6.424837 | 1.061393 |
from labels import get_annotation
annotations = {}
for label in element.getchildren():
if get_xsi_type(label) == 'saltCore:SAnnotation':
annotations.update([get_annotation(label)])
return annotations | def get_annotations(element) | returns a dictionary of all the annotation features of an element,
e.g. tiger.pos = ART or coref.type = anaphoric. | 8.350334 | 8.642928 | 0.966146 |
layers = []
if element.xpath('@layers'):
layers_string = element.xpath('@layers')[0]
for layer_string in layers_string.split():
_prefix, layer = layer_string.split('.') # '//@layers.0' -> '0'
layers.append(int(layer))
return layers | def get_layer_ids(element) | returns the layer ids from a SaltElement (i.e. a node, edge or layer).
Parameters
----------
element : lxml.etree._Element
an etree element parsed from a SaltXML document
Returns
-------
layers: list of int
list of layer indices. list might be empty. | 4.430492 | 4.863437 | 0.91098 |
elements = get_elements(tree, element_type)
stats = defaultdict(int)
for i, element in enumerate(elements):
stats[get_xsi_type(element)] += 1
for (etype, count) in stats.items():
print "{0}: {1}".format(etype, count) | def element_statistics(tree, element_type) | Prints the names and counts of all elements present in an
`etree._ElementTree`, e.g. a SaltDocument::
SStructure: 65
SSpan: 32
SToken: 154
STextualDS: 1
Parameters
----------
tree : lxml.etree._ElementTree
an ElementTree that represents a complete SaltXML docume... | 3.056847 | 3.79437 | 0.805627 |
label_elements = get_subelements(etree_element, 'labels')
labels = [SaltLabel.from_etree(elem) for elem in label_elements]
return cls(name=get_element_name(etree_element),
element_id=get_graph_element_id(etree_element),
xsi_type=get_xsi_type(etree_e... | def from_etree(cls, etree_element) | creates a `SaltElement` from an `etree._Element` representing
an element in a SaltXMI file. | 3.714585 | 3.285319 | 1.130662 |
user = getattr(request, 'user', None)
# If there's not a user on the request, just noop
if user is None:
return
if not user.is_authenticated():
raise ValueError('User needs to be logged in to be elevated to sudo')
# Token doesn't need to be unique,
# just needs to be unpr... | def grant_sudo_privileges(request, max_age=COOKIE_AGE) | Assigns a random token to the user's session
that allows them to have elevated permissions | 4.916124 | 4.55549 | 1.079165 |
request._sudo = False
if COOKIE_NAME in request.session:
del request.session[COOKIE_NAME] | def revoke_sudo_privileges(request) | Revoke sudo privileges from a request explicitly | 6.744725 | 7.155499 | 0.942593 |
if getattr(request, '_sudo', None) is None:
try:
request._sudo = (
request.user.is_authenticated() and
constant_time_compare(
request.get_signed_cookie(COOKIE_NAME, salt=COOKIE_SALT, max_age=COOKIE_AGE),
request.session... | def has_sudo_privileges(request) | Check if a request is allowed to perform sudo actions | 3.008212 | 2.86535 | 1.049859 |
if url is not None:
url = url.strip()
if not url:
return False
if six.PY2: # pragma: nocover
try:
url = force_text(url)
except UnicodeDecodeError:
return False
# Chrome treats \ completely as / in paths but it could be part of some
# basi... | def is_safe_url(url, host=None) | Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
a different host and uses a safe scheme).
Always returns ``False`` on an empty url. | 5.275712 | 4.658195 | 1.132566 |
def transform(hilda_tree):
if isinstance(hilda_tree, basestring) or not hasattr(hilda_tree, 'label'):
return hilda_tree
assert len(hilda_tree) == 2, "We can only handle binary trees."
match = HILDA_REL_RE.match(hilda_tree.label())
... | def hildatree2dgparentedtree(self) | Convert the tree from HILDA's format into a conventional binary tree,
which can be easily converted into output formats like RS3. | 3.221189 | 3.16501 | 1.01775 |
if self._marts is None:
self._marts = self._fetch_marts()
return self._marts | def marts(self) | List of available marts. | 3.69704 | 3.144677 | 1.17565 |
def _row_gen(attributes):
for attr in attributes.values():
yield (attr.name, attr.display_name)
return pd.DataFrame.from_records(
_row_gen(self.marts), columns=['name', 'display_name']) | def list_marts(self) | Lists available marts in a readable DataFrame format.
Returns:
pd.DataFrame: Frame listing available marts. | 5.134321 | 4.449611 | 1.153881 |
'''
_do_bgread - Worker functon for the background read thread.
@param stream <object> - Stream to read until closed
@param results <BackgroundReadData>
'''
# Put the whole function in a try instead of just the read portion for performance reasons.
try:
while True:
... | def _do_bgread(stream, blockSizeLimit, pollTime, closeStream, results) | _do_bgread - Worker functon for the background read thread.
@param stream <object> - Stream to read until closed
@param results <BackgroundReadData> | 6.515333 | 3.833449 | 1.699601 |
rel_attr = rst_namespace+':rel_name'
for node_id, node_attrs in docgraph.nodes_iter(data=True):
if rel_attr in node_attrs and node_attrs[rel_attr] != 'span':
yield (node_id, node_attrs[rel_attr], get_span(docgraph, node_id)) \
if data else (node_id) | def get_rst_relation_root_nodes(docgraph, data=True, rst_namespace='rst') | yield all nodes that dominate one or more RST relations in the given
document graph (in no particular order).
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph which contains RST annotations
data : bool
If True (default), yields (node ID, relation name, list o... | 3.184403 | 3.582325 | 0.888921 |
rst_relations = defaultdict(lambda: defaultdict(str))
for dom_node, _, _ in get_rst_relation_root_nodes(docgraph):
neighbors = \
list(select_neighbors_by_layer(docgraph, dom_node,
layer={'rst:segment', 'rst:group'}))
multinuc_nuc_count... | def get_rst_relations(docgraph) | returns a dictionary with RST relation root node IDs (str, e.g. 'rst:23')
as keys and dictionaries describing these RST relations as values.
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph which contains RST annotations
Returns
-------
rst_relations : defau... | 3.369668 | 3.119239 | 1.080285 |
doc_root = rs3_xml_tree.getroot()
for segment in doc_root.iter('segment'):
self.__add_segment(segment)
for group in doc_root.iter('group'):
self.__add_group(group) | def __rst2graph(self, rs3_xml_tree) | Reads an RST tree (from an ElementTree representation of an RS3
XML file) and adds all segments (nodes representing text) and
groups (nonterminal nodes in an RST tree) as well as the
relationships that hold between them (typed edges) to this
RSTGraph.
Parameters
--------... | 2.769777 | 2.908382 | 0.952343 |
segment_id = self.ns+':'+segment.attrib['id']
self.segments.append(segment_id)
segment_type, parent_segment_type = self.__get_segment_types(segment)
segment_text = sanitize_string(segment.text)
segment_label = get_segment_label(
segment, segment_type, segment... | def __add_segment(self, segment) | add attributes to segment nodes, as well as edges to/from other
segments/groups. add segment to list of EDUs.
Parameters
----------
segment : ??? etree Element | 3.945063 | 3.654737 | 1.079438 |
group_id = self.ns+':'+group.attrib['id']
group_type = group.attrib['type'] # 'span' or 'multinuc'
group_layers = {self.ns, self.ns+':group'}
segment_type, parent_segment_type = self.__get_segment_types(group)
group_attrs = \
{self.ns+':group_type': group_t... | def __add_group(self, group) | add attributes to group nodes, as well as in-edges from other
groups. a group's ``type`` attribute tells us whether the group
node represents a span (of RST segments or other groups) OR
a multinuc(ular) relation (i.e. it dominates several RST nucleii).
a group's ``relname`` gives us the... | 3.911311 | 3.543137 | 1.103912 |
relname = element.attrib['relname'] # name of RST relation or 'span'
reltype = self.relations.get(relname, '') # 'span', 'multinuc' or ''
parent_id = self.ns+':'+element.attrib['parent']
if parent_segment_type:
parent_attrs = {self.ns+':rel_name': relname,
... | def __add_parent_relation(self, element, element_id, segment_type, parent_segment_type) | - add parent node (if not there, yet) w/ segment type
- add edge from parent node to current element | 3.443218 | 3.42967 | 1.00395 |
if not 'parent' in element.attrib:
if element.tag == 'segment':
segment_type = 'isolated'
parent_segment_type = None
else: # element.tag == 'group'
segment_type = 'span'
parent_segment_type = None
retur... | def __get_segment_types(self, element) | given a <segment> or <group> element, returns its segment type and the
segment type of its parent (i.e. its dominating node)
Parameters
----------
element : ??? etree Element
Returns
-------
segment_type : str
'nucleus', 'satellite' or 'isolated' (un... | 4.80113 | 3.701909 | 1.296934 |
for seg_node_id in self.segments:
segment_toks = self.node[seg_node_id][self.ns+':text'].split()
for i, tok in enumerate(segment_toks):
tok_node_id = '{0}:{1}_{2}'.format(self.ns, seg_node_id, i)
self.add_node(tok_node_id, layers={self.ns, self.ns... | def __tokenize_segments(self) | tokenizes every RS3 segment (i.e. an RST nucleus or satellite).
for each token, a node is added to the graph, as well as an edge from
the segment node to the token node. the token node IDs are also added
to ``self.tokens``. | 3.509374 | 3.172505 | 1.106184 |
next = request.POST.get('next', request.GET.get('next'))
if not is_safe_url(url=next, host=request.get_host()):
next = request.META.get('HTTP_REFERER')
if not is_safe_url(url=next, host=request.get_host()):
next = '/'
response = http.HttpResponseRedirect(next)
if req... | def set_theme(request) | Redirect to a given url while setting the chosen theme in the session or cookie. The url and the theme identifier
need to be specified in the request parameters.
Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If
called as a GET request, it wi... | 1.925988 | 1.938082 | 0.99376 |
#propagated from mercurial documentation
sections = [
'alias',
'auth',
'decode/encode',
'defaults',
'diff',
'email',
'extensions',
'format',
'merge-patterns',
... | def make_ui(self, path='hgwebdir.config') | A funcion that will read python rc files and make an ui from read options
:param path: path to mercurial config file | 5.373154 | 5.427004 | 0.990077 |
return self.repository._repo.status(self._ctx.p1().node(),
self._ctx.node()) | def status(self) | Returns modified, added, removed, deleted files for current changeset | 23.102184 | 10.031714 | 2.302915 |
return [self.repository.get_changeset(parent.rev())
for parent in self._ctx.parents() if parent.rev() >= 0] | def parents(self) | Returns list of parents changesets. | 8.710911 | 5.39897 | 1.613439 |
return [self.repository.get_changeset(child.rev())
for child in self._ctx.children() if child.rev() >= 0] | def children(self) | Returns list of children changesets. | 9.666917 | 5.490039 | 1.76081 |
if path.endswith('/'):
path = path.rstrip('/')
return safe_str(path) | def _fix_path(self, path) | Paths are stored without trailing slash so we need to get rid off it if
needed. Also mercurial keeps filenodes as str so we need to decode
from unicode to str | 7.749351 | 5.918421 | 1.309361 |
fctx = self._get_filectx(path)
hist = []
cnt = 0
for cs in reversed([x for x in fctx.filelog()]):
cnt += 1
hist.append(hex(fctx.filectx(cs).node()))
if limit and cnt == limit:
break
return [self.repository.get_changese... | def get_file_history(self, path, limit=None) | Returns history of file as reversed list of ``Changeset`` objects for
which file at given ``path`` has been modified. | 5.303568 | 4.452226 | 1.191217 |
fctx = self._get_filectx(path)
for i, annotate_data in enumerate(fctx.annotate()):
ln_no = i + 1
sha = hex(annotate_data[0].node())
yield (ln_no, sha, lambda: self.repository.get_changeset(sha), annotate_data[1],) | def get_file_annotate(self, path) | Returns a generator of four element tuples with
lineno, sha, changeset lazy loader and line | 7.736829 | 4.908248 | 1.576291 |
allowed_kinds = settings.ARCHIVE_SPECS.keys()
if kind not in allowed_kinds:
raise ImproperArchiveTypeError('Archive kind not supported use one'
'of %s', allowed_kinds)
if stream is None:
raise VCSError('You need to pass in a valid stream for fil... | def fill_archive(self, stream=None, kind='tgz', prefix=None,
subrepos=False) | Fills up given stream.
:param stream: file like object.
:param kind: one of following: ``zip``, ``tgz`` or ``tbz2``.
Default: ``tgz``.
:param prefix: name of root directory in archive.
Default is repository name and changeset's raw_id joined with dash
(``repo... | 3.719266 | 3.332212 | 1.116155 |
if self._get_kind(path) != NodeKind.DIR:
raise ChangesetError("Directory does not exist for revision %s at "
" '%s'" % (self.revision, path))
path = self._fix_path(path)
filenodes = [FileNode(f, changeset=self) for f in self._file_paths
if os.pa... | def get_nodes(self, path) | Returns combined ``DirNode`` and ``FileNode`` objects list representing
state of changeset at the given ``path``. If node at the given ``path``
is not instance of ``DirNode``, ChangesetError would be raised. | 5.076304 | 4.632687 | 1.095758 |
path = self._fix_path(path)
if not path in self.nodes:
if path in self._file_paths:
node = FileNode(path, changeset=self)
elif path in self._dir_paths or path in self._dir_paths:
if path == '':
node = RootNode(changes... | def get_node(self, path) | Returns ``Node`` object from the given ``path``. If there is no node at
the given ``path``, ``ChangesetError`` would be raised. | 3.255966 | 3.193602 | 1.019528 |
if self.changeset:
mode = self.changeset.get_file_mode(self.path)
else:
mode = self._mode
return mode | def mode(self) | Returns lazily mode of the FileNode. If ``changeset`` is not set, would
use value given at initialization or 0100644 (default). | 5.469069 | 3.118565 | 1.753713 |
content = self._get_content()
if bool(content and '\0' in content):
return content
return safe_unicode(content) | def content(self) | Returns lazily content of the FileNode. If possible, would try to
decode content from UTF-8. | 10.29857 | 8.477082 | 1.214872 |
if hasattr(self, '_mimetype'):
if (isinstance(self._mimetype, (tuple, list,)) and
len(self._mimetype) == 2):
return self._mimetype
else:
raise NodeError('given _mimetype attribute must be an 2 '
'elem... | def get_mimetype(self) | Mimetype is calculated based on the file's content. If ``_mimetype``
attribute is available, it will be returned (backends which store
mimetypes or can easily recognize them, should set this private
attribute to indicate that type should *NOT* be calculated). | 2.949157 | 2.826071 | 1.043554 |
try:
lexer = lexers.guess_lexer_for_filename(self.name, self.content, stripnl=False)
except lexers.ClassNotFound:
lexer = lexers.TextLexer(stripnl=False)
# returns first alias
return lexer | def lexer(self) | Returns pygment's lexer class. Would try to guess lexer taking file's
content, name and mimetype. | 5.220696 | 3.752564 | 1.391235 |
if self.changeset is None:
raise NodeError('Unable to get changeset for this FileNode')
return self.changeset.get_file_history(self.path) | def history(self) | Returns a list of changeset for this file in which the file was changed | 8.195159 | 5.147735 | 1.591993 |
if self.changeset is None:
raise NodeError('Unable to get changeset for this FileNode')
return self.changeset.get_file_annotate(self.path) | def annotate(self) | Returns a list of three element tuples with lineno,changeset and line | 8.805676 | 6.054499 | 1.454402 |
try:
path = path.rstrip('/')
if path == '':
raise NodeError("Cannot retrieve node without path")
self.nodes # access nodes first in order to set _nodes_dict
paths = path.split('/')
if len(paths) == 1:
if not se... | def get_node(self, path) | Returns node from within this particular ``DirNode``, so it is now
allowed to fetch, i.e. node located at 'docs/api/index.rst' from node
'docs'. In order to access deeper nodes one must fetch nodes between
them first - this would work::
docs = root.get_node('docs')
docs.ge... | 3.237808 | 3.076096 | 1.052571 |
org = safe_unicode(self.path.rstrip('/').split('/')[-1])
return u'%s @ %s' % (org, self.changeset.short_id) | def name(self) | Returns name of the node so if its path
then only last part is returned. | 8.265244 | 7.85244 | 1.05257 |
r
X, y = check_X_y(X, y)
# Batch magnification factor
N, _ = X.shape
self.B_ = X.shape[0] / self.batch_size
self.D_ = self.basis.get_dim(X)
# Pack data
likelihood_args = _reshape_likelihood_args(likelihood_args, N)
data = (X, y) + likelihood_args... | def fit(self, X, y, likelihood_args=()) | r"""
Learn the parameters of a Bayesian generalized linear model (GLM).
Parameters
----------
X : ndarray
(N, d) array input dataset (N samples, d dimensions).
y : ndarray
(N,) array targets (N samples)
likelihood : Object
A likelihood... | 5.196116 | 5.397484 | 0.962692 |
Ey, _ = self.predict_moments(X, nsamples, likelihood_args)
return Ey | def predict(self, X, nsamples=200, likelihood_args=()) | Predict target values from Bayesian generalized linear regression.
Parameters
----------
X : ndarray
(N*,d) array query input dataset (N* samples, d dimensions).
nsamples : int, optional
Number of samples for sampling the expected target values from the
... | 6.975127 | 6.166753 | 1.131086 |
r
# Get latent function samples
N = X.shape[0]
ys = np.empty((N, nsamples))
fsamples = self._sample_func(X, nsamples)
# Push samples though likelihood expected value
Eyargs = tuple(chain(atleast_list(self.like_hypers_), likelihood_args))
for i, f in enume... | def predict_moments(self, X, nsamples=200, likelihood_args=()) | r"""
Predictive moments, in particular mean and variance, of a Bayesian GLM.
This function uses Monte-Carlo sampling to evaluate the predictive mean
and variance of a Bayesian GLM. The exact expressions evaluated are,
.. math ::
\mathbb{E}[y^* | \mathbf{x^*}, \mathbf{X}, y... | 7.042787 | 6.890951 | 1.022034 |
r
X, y = check_X_y(X, y)
# Get latent function samples
N = X.shape[0]
ps = np.empty((N, nsamples))
fsamples = self._sample_func(X, nsamples)
# Push samples though likelihood pdf
llargs = tuple(chain(atleast_list(self.like_hypers_), likelihood_args))
... | def predict_logpdf(self, X, y, nsamples=200, likelihood_args=()) | r"""
Predictive log-probability density function of a Bayesian GLM.
Parameters
----------
X : ndarray
(N*,d) array query input dataset (N* samples, D dimensions).
y : float or ndarray
The test observations of shape (N*,) to evaluate under,
:ma... | 4.709229 | 4.740431 | 0.993418 |
r
# Get latent function samples
N = X.shape[0]
ps = np.empty((N, nsamples))
fsamples = self._sample_func(X, nsamples)
# Push samples though likelihood cdf
cdfarg = tuple(chain(atleast_list(self.like_hypers_), likelihood_args))
for i, f in enumerate(fsampl... | def predict_cdf(self, X, quantile, nsamples=200, likelihood_args=()) | r"""
Predictive cumulative density function of a Bayesian GLM.
Parameters
----------
X : ndarray
(N*,d) array query input dataset (N* samples, D dimensions).
quantile : float
The predictive probability, :math:`p(y^* \leq \text{quantile} |
\mat... | 5.406703 | 5.218719 | 1.036021 |
N = X.shape[0]
# Generate latent function samples per observation (n in N)
fsamples = self._sample_func(X, nsamples, genaxis=0)
# Make sure likelihood_args is consistent with work
if len(likelihood_args) > 0:
likelihood_args = _reshape_likelihood_args(likel... | def predict_interval(self, X, percentile, nsamples=200, likelihood_args=(),
multiproc=True) | Predictive percentile interval (upper and lower quantiles).
Parameters
----------
X : ndarray
(N*,d) array query input dataset (N* samples, D dimensions).
percentile : float
The percentile confidence interval (e.g. 95%) to return.
nsamples : int, optional... | 5.311388 | 5.328504 | 0.996788 |
check_is_fitted(self, ['weights_', 'covariance_', 'basis_hypers_',
'like_hypers_', 'regularizer_'])
X = check_array(X)
D, K = self.weights_.shape
# Generate weight samples from all mixture components
k = self.random_.randint(0, K, size=(ns... | def _sample_func(self, X, nsamples, genaxis=1) | Generate samples from the posterior latent function mixtures of the GLM
for query inputs, X*.
Parameters
----------
X : ndarray
(N*, d) array query input dataset (N* samples, D dimensions).
nsamples : int
Number of samples for sampling the latent function... | 5.306388 | 5.635557 | 0.941591 |
arg1 = parent.add_subparsers(dest='command')
arg2 = arg1.add_parser('create')
arg2.add_argument('-P', '--progress',
action='store_true',
help='show progress bar')
arg2.add_argument('-s', '--settings',
type=FileType('r'), default=No... | def create_arg_parser(parent) | Create command subparsers.
Parameters
----------
parent : `argparse.ArgumentParser`
Command parser. | 1.721666 | 1.731084 | 0.994559 |
pbar = None
channels = markov.imgtype.channels
tr = markov.scanner.traversal
if progress and not isinstance(tr[0], TraversalProgressWrapper):
tr[0] = TraversalProgressWrapper(tr[0], channels)
tr = tr[0]
try:
with infiles(fnames, progress, leave) as fnames:
for ... | def read(fnames, markov, progress, leave=True) | Read data files and update a generator.
Parameters
----------
fnames : `list` of `str`
File paths.
markov : `markovchain.base.MarkovBase`
Generator to update.
progress : `bool`
Show progress bar.
leave : `bool`, optional
Leave progress bars (default: `True`). | 4.942713 | 5.403829 | 0.914669 |
pbar = None
channels = markov.imgtype.channels
tr = markov.scanner.traversal
if progress and not isinstance(tr[0], TraversalProgressWrapper):
tr[0] = TraversalProgressWrapper(tr[0], channels)
tr = tr[0]
try:
with _outfiles(fmt, nfiles, progress) as fnames:
for ... | def outfiles(markov, fmt, nfiles, progress, start=0) | Get output file paths.
Parameters
----------
markov : `markovchain.base.MarkovBase`
Markov chain generator.
fmt : `str`
File path format string.
nfiles : `int`
Number of files.
progress : `bool`
Show progress bars.
start : `int`, optional
Initial imag... | 4.487814 | 4.860367 | 0.923349 |
check_output_format(args.output, args.count)
markov = load(MarkovImage, args.state, args)
if args.size is None:
if markov.scanner.resize is None:
print('Unknown output image size', file=stderr)
exit(1)
width, height = markov.scanner.resize
else:
wid... | def cmd_generate(args) | Generate images.
Parameters
----------
args : `argparse.Namespace`
Command arguments. | 4.558103 | 4.691252 | 0.971617 |
check_output_format(args.output, args.count)
img = Image.open(args.input)
width, height = img.size
if args.state is not None:
markov = load(MarkovImage, args.state, args)
else:
args.state = ()
if args.type == JSON:
storage = JsonStorage(settings=args.settin... | def cmd_filter(args) | Filter an image.
Parameters
----------
args : `argparse.Namespace`
Command arguments. | 4.523462 | 4.641403 | 0.974589 |
res = string.lstrip().lstrip(chars)
while len(res) != len(string):
string = res
res = string.lstrip().lstrip(chars)
return res | def lstrip_ws_and_chars(string, chars) | Remove leading whitespace and characters from a string.
Parameters
----------
string : `str`
String to strip.
chars : `str`
Characters to remove.
Returns
-------
`str`
Stripped string.
Examples
--------
>>> lstrip_ws_and_chars(' \\t.\\n , .x. ', '.,?!')... | 2.704697 | 4.517396 | 0.598729 |
if not string:
return string
if len(string) == 1:
return string.upper()
return string[0].upper() + string[1:].lower() | def capitalize(string) | Capitalize a sentence.
Parameters
----------
string : `str`
String to capitalize.
Returns
-------
`str`
Capitalized string.
Examples
--------
>>> capitalize('worD WORD WoRd')
'Word word word' | 2.007349 | 3.165178 | 0.634198 |
re_, custom_ = 0, 0
for flag in flags.upper():
try:
re_ |= getattr(re, flag)
except AttributeError:
if custom is not None:
try:
custom_ |= getattr(custom, flag)
except AttributeError:
raise Value... | def re_flags(flags, custom=ReFlags) | Parse regexp flag string.
Parameters
----------
flags: `str`
Flag string.
custom: `IntEnum`, optional
Custom flag enum (default: None).
Returns
-------
(`int`, `int`)
(flags for `re.compile`, custom flags)
Raises
------
ValueError | 2.941245 | 3.462457 | 0.849468 |
res = ''
for flag in RE_FLAGS:
if flags & getattr(re, flag):
res += flag
for flag in RE_CUSTOM_FLAGS:
if custom_flags & getattr(ReFlags, flag):
res += flag
return res | def re_flags_str(flags, custom_flags) | Convert regexp flags to string.
Parameters
----------
flags : `int`
Flags.
custom_flags : `int`
Custom flags.
Returns
-------
`str`
Flag string. | 2.873 | 3.709467 | 0.774505 |
if custom_flags & ReFlags.OVERLAP:
prev_string = None
while string != prev_string:
prev_string = string
string = re.sub(pattern, repl, string, count, flags)
return string
return re.sub(pattern, repl, string, count, flags) | def re_sub(pattern, repl, string, count=0, flags=0, custom_flags=0) | Replace regular expression.
Parameters
----------
pattern : `str` or `_sre.SRE_Pattern`
Compiled regular expression.
repl : `str` or `function`
Replacement.
string : `str`
Input string.
count: `int`
Maximum number of pattern occurrences.
flags : `int`
... | 2.580003 | 3.068724 | 0.840741 |
if self == self.__class__.TITLE:
return capitalize(string)
if self == self.__class__.UPPER:
return string.upper()
if self == self.__class__.LOWER:
return string.lower()
return string | def convert(self, string) | Return a copy of string converted to case.
Parameters
----------
string : `str`
Returns
-------
`str`
Examples
--------
>>> CharCase.LOWER.convert('sTr InG')
'str ing'
>>> CharCase.UPPER.convert('sTr InG')
'STR ING'
... | 3.285036 | 3.199882 | 1.026612 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.