_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q7600 | Slot._set_value | train | def _set_value(self, slot_record):
"""Sets the value of this slot based on its corresponding _SlotRecord.
Does nothing if the slot has not yet been filled.
Args:
slot_record: The _SlotRecord containing this Slot's value.
"""
if slot_record.status == _SlotRecord.FILLED:
self.filled = Tr... | python | {
"resource": ""
} |
q7601 | PipelineFuture._inherit_outputs | train | def _inherit_outputs(self,
pipeline_name,
already_defined,
resolve_outputs=False):
"""Inherits outputs from a calling Pipeline.
Args:
pipeline_name: The Pipeline class name (used for debugging).
already_defined: Maps output name t... | python | {
"resource": ""
} |
q7602 | Pipeline.from_id | train | def from_id(cls, pipeline_id, resolve_outputs=True, _pipeline_record=None):
"""Returns an instance corresponding to an existing Pipeline.
The returned object will have the same properties a Pipeline does while
it's running synchronously (e.g., like what it's first allocated), allowing
callers to inspec... | python | {
"resource": ""
} |
q7603 | Pipeline.start | train | def start(self,
idempotence_key='',
queue_name='default',
base_path='/_ah/pipeline',
return_task=False,
countdown=None,
eta=None):
"""Starts a new instance of this pipeline.
Args:
idempotence_key: The ID to use for this Pipeline and ... | python | {
"resource": ""
} |
q7604 | Pipeline.retry | train | def retry(self, retry_message=''):
"""Forces a currently running asynchronous pipeline to retry.
Note this may not be called by synchronous or generator pipelines. Those
must instead raise the 'Retry' exception during execution.
Args:
retry_message: Optional message explaining why the retry happ... | python | {
"resource": ""
} |
q7605 | Pipeline.abort | train | def abort(self, abort_message=''):
"""Mark the entire pipeline up to the root as aborted.
Note this should only be called from *outside* the context of a running
pipeline. Synchronous and generator pipelines should raise the 'Abort'
exception to cause this behavior during execution.
Args:
ab... | python | {
"resource": ""
} |
q7606 | Pipeline.fill | train | def fill(self, name_or_slot, value):
"""Fills an output slot required by this Pipeline.
Args:
name_or_slot: The name of the slot (a string) or Slot record to fill.
value: The serializable value to assign to this slot.
Raises:
UnexpectedPipelineError if the Slot no longer exists. SlotNotD... | python | {
"resource": ""
} |
q7607 | Pipeline.set_status | train | def set_status(self, message=None, console_url=None, status_links=None):
"""Sets the current status of this pipeline.
This method is purposefully non-transactional. Updates are written to the
datastore immediately and overwrite all existing statuses.
Args:
message: (optional) Overall status mess... | python | {
"resource": ""
} |
q7608 | Pipeline.complete | train | def complete(self, default_output=None):
"""Marks this asynchronous Pipeline as complete.
Args:
default_output: What value the 'default' output slot should be assigned.
Raises:
UnexpectedPipelineError if the slot no longer exists or this method was
called for a pipeline that is not async... | python | {
"resource": ""
} |
q7609 | Pipeline.get_callback_url | train | def get_callback_url(self, **kwargs):
"""Returns a relative URL for invoking this Pipeline's callback method.
Args:
kwargs: Dictionary mapping keyword argument names to single values that
should be passed to the callback when it is invoked.
Raises:
UnexpectedPipelineError if this is in... | python | {
"resource": ""
} |
q7610 | Pipeline.get_callback_task | train | def get_callback_task(self, *args, **kwargs):
"""Returns a task for calling back this Pipeline.
Args:
params: Keyword argument containing a dictionary of key/value pairs
that will be passed to the callback when it is executed.
args, kwargs: Passed to the taskqueue.Task constructor. Use thes... | python | {
"resource": ""
} |
q7611 | Pipeline.cleanup | train | def cleanup(self):
"""Clean up this Pipeline and all Datastore records used for coordination.
Only works when called on a root pipeline. Child pipelines will ignore
calls to this method.
After this method is called, Pipeline.from_id() and related status
methods will return inconsistent or missing ... | python | {
"resource": ""
} |
q7612 | Pipeline.with_params | train | def with_params(self, **kwargs):
"""Modify various execution parameters of a Pipeline before it runs.
This method has no effect in test mode.
Args:
kwargs: Attributes to modify on this Pipeline instance before it has
been executed.
Returns:
This Pipeline instance, for easy chainin... | python | {
"resource": ""
} |
q7613 | Pipeline._set_class_path | train | def _set_class_path(cls, module_dict=sys.modules):
"""Sets the absolute path to this class as a string.
Used by the Pipeline API to reconstruct the Pipeline sub-class object
at execution time instead of passing around a serialized function.
Args:
module_dict: Used for testing.
"""
# Do n... | python | {
"resource": ""
} |
q7614 | Pipeline._set_values_internal | train | def _set_values_internal(self,
context,
pipeline_key,
root_pipeline_key,
outputs,
result_status):
"""Sets the user-visible values provided as an API by this class.
Args:
... | python | {
"resource": ""
} |
q7615 | Pipeline._callback_internal | train | def _callback_internal(self, kwargs):
"""Used to execute callbacks on asynchronous pipelines."""
logging.debug('Callback %s(*%s, **%s)#%s with params: %r',
self._class_path, _short_repr(self.args),
_short_repr(self.kwargs), self._pipeline_key.name(), kwargs)
return self.c... | python | {
"resource": ""
} |
q7616 | Pipeline._run_internal | train | def _run_internal(self,
context,
pipeline_key,
root_pipeline_key,
caller_output):
"""Used by the Pipeline evaluator to execute this Pipeline."""
self._set_values_internal(
context, pipeline_key, root_pipeline_key, caller_out... | python | {
"resource": ""
} |
q7617 | Pipeline._finalized_internal | train | def _finalized_internal(self,
context,
pipeline_key,
root_pipeline_key,
caller_output,
aborted):
"""Used by the Pipeline evaluator to finalize this Pipeline."""
result_status = _Pipe... | python | {
"resource": ""
} |
q7618 | InOrder._add_future | train | def _add_future(cls, future):
"""Adds a future to the list of in-order futures thus far.
Args:
future: The future to add to the list.
"""
if cls._local._activated:
cls._local._in_order_futures.add(future) | python | {
"resource": ""
} |
q7619 | InOrder._thread_init | train | def _thread_init(cls):
"""Ensure thread local is initialized."""
if not hasattr(cls._local, '_in_order_futures'):
cls._local._in_order_futures = set()
cls._local._activated = False | python | {
"resource": ""
} |
q7620 | _PipelineContext.from_environ | train | def from_environ(cls, environ=os.environ):
"""Constructs a _PipelineContext from the task queue environment."""
base_path, unused = (environ['PATH_INFO'].rsplit('/', 1) + [''])[:2]
return cls(
environ['HTTP_X_APPENGINE_TASKNAME'],
environ['HTTP_X_APPENGINE_QUEUENAME'],
base_path) | python | {
"resource": ""
} |
q7621 | _PipelineContext.fill_slot | train | def fill_slot(self, filler_pipeline_key, slot, value):
"""Fills a slot, enqueueing a task to trigger pending barriers.
Args:
filler_pipeline_key: db.Key or stringified key of the _PipelineRecord
that filled this slot.
slot: The Slot instance to fill.
value: The serializable value to a... | python | {
"resource": ""
} |
q7622 | _PipelineContext.begin_abort | train | def begin_abort(self, root_pipeline_key, abort_message):
"""Kicks off the abort process for a root pipeline and all its children.
Args:
root_pipeline_key: db.Key of the root pipeline to abort.
abort_message: Message explaining why the abort happened, only saved
into the root pipeline.
... | python | {
"resource": ""
} |
q7623 | _PipelineContext.continue_abort | train | def continue_abort(self,
root_pipeline_key,
cursor=None,
max_to_notify=_MAX_ABORTS_TO_BEGIN):
"""Sends the abort signal to all children for a root pipeline.
Args:
root_pipeline_key: db.Key of the root pipeline to abort.
cursor: The quer... | python | {
"resource": ""
} |
q7624 | _PipelineContext.start | train | def start(self, pipeline, return_task=True, countdown=None, eta=None):
"""Starts a pipeline.
Args:
pipeline: Pipeline instance to run.
return_task: When True, do not submit the task to start the pipeline
but instead return it for someone else to enqueue.
countdown: Time in seconds int... | python | {
"resource": ""
} |
q7625 | _PipelineContext._create_barrier_entities | train | def _create_barrier_entities(root_pipeline_key,
child_pipeline_key,
purpose,
blocking_slot_keys):
"""Creates all of the entities required for a _BarrierRecord.
Args:
root_pipeline_key: The root pipeline this is p... | python | {
"resource": ""
} |
q7626 | _PipelineContext.handle_run_exception | train | def handle_run_exception(self, pipeline_key, pipeline_func, e):
"""Handles an exception raised by a Pipeline's user code.
Args:
pipeline_key: The pipeline that raised the error.
pipeline_func: The class path name of the Pipeline that was running.
e: The exception that was raised.
Returns... | python | {
"resource": ""
} |
q7627 | _PipelineContext.transition_run | train | def transition_run(self,
pipeline_key,
blocking_slot_keys=None,
fanned_out_pipelines=None,
pipelines_to_run=None):
"""Marks an asynchronous or generator pipeline as running.
Does nothing if the pipeline is no longer in a runnab... | python | {
"resource": ""
} |
q7628 | _PipelineContext.transition_complete | train | def transition_complete(self, pipeline_key):
"""Marks the given pipeline as complete.
Does nothing if the pipeline is no longer in a state that can be completed.
Args:
pipeline_key: db.Key of the _PipelineRecord that has completed.
"""
def txn():
pipeline_record = db.get(pipeline_key)
... | python | {
"resource": ""
} |
q7629 | _PipelineContext.transition_retry | train | def transition_retry(self, pipeline_key, retry_message):
"""Marks the given pipeline as requiring another retry.
Does nothing if all attempts have been exceeded.
Args:
pipeline_key: db.Key of the _PipelineRecord that needs to be retried.
retry_message: User-supplied message indicating the reas... | python | {
"resource": ""
} |
q7630 | _CallbackHandler.run_callback | train | def run_callback(self):
"""Runs the callback for the pipeline specified in the request.
Raises:
_CallbackTaskError if something was wrong with the request parameters.
"""
pipeline_id = self.request.get('pipeline_id')
if not pipeline_id:
raise _CallbackTaskError('"pipeline_id" parameter ... | python | {
"resource": ""
} |
q7631 | _fix_path | train | def _fix_path():
"""Finds the google_appengine directory and fixes Python imports to use it."""
import os
import sys
all_paths = os.environ.get('PYTHONPATH').split(os.pathsep)
for path_dir in all_paths:
dev_appserver_path = os.path.join(path_dir, 'dev_appserver.py')
if os.path.exists(dev_appserver_pat... | python | {
"resource": ""
} |
q7632 | _PipelineRecord.params | train | def params(self):
"""Returns the dictionary of parameters for this Pipeline."""
if hasattr(self, '_params_decoded'):
return self._params_decoded
if self.params_blob is not None:
value_encoded = self.params_blob.open().read()
else:
value_encoded = self.params_text
value = json.loa... | python | {
"resource": ""
} |
q7633 | _SlotRecord.value | train | def value(self):
"""Returns the value of this Slot."""
if hasattr(self, '_value_decoded'):
return self._value_decoded
if self.value_blob is not None:
encoded_value = self.value_blob.open().read()
else:
encoded_value = self.value_text
self._value_decoded = json.loads(encoded_value... | python | {
"resource": ""
} |
q7634 | _BarrierIndex.to_barrier_key | train | def to_barrier_key(cls, barrier_index_key):
"""Converts a _BarrierIndex key to a _BarrierRecord key.
Args:
barrier_index_key: db.Key for a _BarrierIndex entity.
Returns:
db.Key for the corresponding _BarrierRecord entity.
"""
barrier_index_path = barrier_index_key.to_path()
# Pick... | python | {
"resource": ""
} |
q7635 | Sheet.partial_page | train | def partial_page(self, page, used_labels):
"""Allows a page to be marked as already partially used so you can
generate a PDF to print on the remaining labels.
Parameters
----------
page: positive integer
The page number to mark as partially used. The page must not ha... | python | {
"resource": ""
} |
q7636 | Sheet._new_page | train | def _new_page(self):
"""Helper function to start a new page. Not intended for external use.
"""
self._current_page = Drawing(*self._pagesize)
if self._bgimage:
self._current_page.add(self._bgimage)
self._pages.append(self._current_page)
self.page_count += 1
... | python | {
"resource": ""
} |
q7637 | Sheet._next_label | train | def _next_label(self):
"""Helper method to move to the next label. Not intended for external use.
This does not increment the label_count attribute as the next label may
not be usable (it may have been marked as missing through
partial_pages). See _next_unused_label for generally more u... | python | {
"resource": ""
} |
q7638 | Sheet._next_unused_label | train | def _next_unused_label(self):
"""Helper method to move to the next unused label. Not intended for external use.
This method will shade in any missing labels if desired, and will
increment the label_count attribute once a suitable label position has
been found.
"""
self.... | python | {
"resource": ""
} |
q7639 | Sheet._calculate_edges | train | def _calculate_edges(self):
"""Calculate edges of the current label. Not intended for external use.
"""
# Calculate the left edge of the label.
left = self.specs.left_margin
left += (self.specs.label_width * (self._position[1] - 1))
if self.specs.column_gap:
... | python | {
"resource": ""
} |
q7640 | Sheet._shade_missing_label | train | def _shade_missing_label(self):
"""Helper method to shade a missing label. Not intended for external use.
"""
# Start a drawing for the whole label.
label = Drawing(float(self._lw), float(self._lh))
label.add(self._clip_label)
# Fill with a rectangle; the clipping path ... | python | {
"resource": ""
} |
q7641 | Sheet._shade_remaining_missing | train | def _shade_remaining_missing(self):
"""Helper method to shade any missing labels remaining on the current
page. Not intended for external use.
Note that this will modify the internal _position attribute and should
therefore only be used once all the 'real' labels have been drawn.
... | python | {
"resource": ""
} |
q7642 | Sheet._draw_label | train | def _draw_label(self, obj, count):
"""Helper method to draw on the current label. Not intended for external use.
"""
# Start a drawing for the whole label.
label = Drawing(float(self._lw), float(self._lh))
label.add(self._clip_label)
# And one for the available area (i.... | python | {
"resource": ""
} |
q7643 | Sheet.add_labels | train | def add_labels(self, objects, count=1):
"""Add multiple labels to the sheet.
Parameters
----------
objects: iterable
An iterable of the objects to add. Each of these will be passed to
the add_label method. Note that if this is a generator it will be
c... | python | {
"resource": ""
} |
q7644 | Sheet.save | train | def save(self, filelike):
"""Save the file as a PDF.
Parameters
----------
filelike: path or file-like object
The filename or file-like object to save the labels under. Any
existing contents will be overwritten.
"""
# Shade any remaining missing ... | python | {
"resource": ""
} |
q7645 | Sheet.preview | train | def preview(self, page, filelike, format='png', dpi=72, background_colour=0xFFFFFF):
"""Render a preview image of a page.
Parameters
----------
page: positive integer
Which page to render. Must be in the range [1, page_count]
filelike: path or file-like object
... | python | {
"resource": ""
} |
q7646 | Sheet.preview_string | train | def preview_string(self, page, format='png', dpi=72, background_colour=0xFFFFFF):
"""Render a preview image of a page as a string.
Parameters
----------
page: positive integer
Which page to render. Must be in the range [1, page_count]
format: string
The i... | python | {
"resource": ""
} |
q7647 | Specification.bounding_boxes | train | def bounding_boxes(self, mode='fraction', output='dict'):
"""Get the bounding boxes of the labels on a page.
Parameters
----------
mode: 'fraction', 'actual'
If 'fraction', the bounding boxes are expressed as a fraction of the
height and width of the sheet. If 'a... | python | {
"resource": ""
} |
q7648 | templatesCollector | train | def templatesCollector(text, open, close):
"""leaves related articles and wikitables in place"""
others = []
spans = [i for i in findBalanced(text, open, close)]
spanscopy = copy(spans)
for i in range(len(spans)):
start, end = spans[i]
o = text[start:end]
ol = o.lower()
... | python | {
"resource": ""
} |
q7649 | assert_legal_arguments | train | def assert_legal_arguments(kwargs):
"""Assert that PrettyPrinter arguments are correct.
Raises
------
ValueError
In case there are unknown arguments or a single layer is mapped to more than one aesthetic.
"""
seen_layers = set()
for k, v in kwargs.items():
if k not in LEGAL_... | python | {
"resource": ""
} |
q7650 | parse_arguments | train | def parse_arguments(kwargs):
"""Function that parses PrettyPrinter arguments.
Detects which aesthetics are mapped to which layers
and collects user-provided values.
Parameters
----------
kwargs: dict
The keyword arguments to PrettyPrinter.
Returns
-------
dict, dict
... | python | {
"resource": ""
} |
q7651 | PrettyPrinter.render | train | def render(self, text, add_header=False):
"""Render the HTML.
Parameters
----------
add_header: boolean (default: False)
If True, add HTML5 header and footer.
Returns
-------
str
The rendered HTML.
"""
html = mark_text(te... | python | {
"resource": ""
} |
q7652 | Trainer.train | train | def train(self, nerdocs, mode_filename):
"""Train a CRF model using given documents.
Parameters
----------
nerdocs: list of estnltk.estner.ner.Document.
The documents for model training.
mode_filename: str
The fielname where to save the model.
"""... | python | {
"resource": ""
} |
q7653 | json_2_text | train | def json_2_text(inp, out, verbose = False):
"""Convert a Wikipedia article to Text object.
Concatenates the sections in wikipedia file and rearranges other information so it
can be interpreted as a Text object.
Links and other elements with start and end positions are annotated
as layers.
Para... | python | {
"resource": ""
} |
q7654 | concatenate_matches | train | def concatenate_matches(a, b, text, name):
"""Concatenate matches a and b.
All submatches will be copied to result."""
match = Match(a.start, b.end, text[a.start:b.end], name)
for k, v in a.matches.items():
match.matches[k] = v
for k, v in b.matches.items():
match.matches[k] = v
... | python | {
"resource": ""
} |
q7655 | Match.dict | train | def dict(self):
"""Dictionary representing this match and all child symbol matches."""
res = copy(self)
if MATCHES in res:
del res[MATCHES]
if NAME in res:
del res[NAME]
res = {self.name: res}
for k, v in self.matches.items():
res[k] = ... | python | {
"resource": ""
} |
q7656 | regex_from_markers | train | def regex_from_markers(markers):
"""Given a string of characters, construct a regex that matches them.
Parameters
----------
markers: str
The list of string containing the markers
Returns
-------
regex
The regular expression matching the given markers.
"""
return re... | python | {
"resource": ""
} |
q7657 | convert | train | def convert(word):
"""This method converts given `word` to UTF-8 encoding and `bytes` type for the
SWIG wrapper."""
if six.PY2:
if isinstance(word, unicode):
return word.encode('utf-8')
else:
return word.decode('utf-8').encode('utf-8') # make sure it is real utf8, ... | python | {
"resource": ""
} |
q7658 | postprocess_result | train | def postprocess_result(morphresult, trim_phonetic, trim_compound):
"""Postprocess vabamorf wrapper output."""
word, analysis = morphresult
return {
'text': deconvert(word),
'analysis': [postprocess_analysis(a, trim_phonetic, trim_compound) for a in analysis]
} | python | {
"resource": ""
} |
q7659 | trim_phonetics | train | def trim_phonetics(root):
"""Function that trims phonetic markup from the root.
Parameters
----------
root: str
The string to remove the phonetic markup.
Returns
-------
str
The string with phonetic markup removed.
"""
global phonetic_markers
global phonetic_reg... | python | {
"resource": ""
} |
q7660 | get_root | train | def get_root(root, phonetic, compound):
"""Get the root form without markers.
Parameters
----------
root: str
The word root form.
phonetic: boolean
If True, add phonetic information to the root forms.
compound: boolean
if True, add compound word markers to root forms.
... | python | {
"resource": ""
} |
q7661 | Vabamorf.instance | train | def instance():
"""Return an PyVabamorf instance.
It returns the previously initialized instance or creates a new
one if nothing exists. Also creates new instance in case the
process has been forked.
"""
if not hasattr(Vabamorf, 'pid') or Vabamorf.pid != os.getpid():
... | python | {
"resource": ""
} |
q7662 | Vabamorf.analyze | train | def analyze(self, words, **kwargs):
"""Perform morphological analysis and disambiguation of given text.
Parameters
----------
words: list of str or str
Either a list of pretokenized words or a string. In case of a string, it will be splitted using
default behavio... | python | {
"resource": ""
} |
q7663 | Vabamorf.disambiguate | train | def disambiguate(self, words):
"""Disambiguate previously analyzed words.
Parameters
----------
words: list of dict
A sentence of words.
Returns
-------
list of dict
Sentence of disambiguated words.
"""
words = vm.Sentence... | python | {
"resource": ""
} |
q7664 | Vabamorf.spellcheck | train | def spellcheck(self, words, suggestions=True):
"""Spellcheck given sentence.
Note that spellchecker does not respect pre-tokenized words and concatenates
token sequences such as "New York".
Parameters
----------
words: list of str or str
Either a list of pre... | python | {
"resource": ""
} |
q7665 | ClauseSegmenter.annotate_indices | train | def annotate_indices(self, sentence):
"""Add clause indexes to already annotated sentence."""
max_index = 0
max_depth = 1
stack_of_indexes = [ max_index ]
for token in sentence:
if CLAUSE_ANNOT not in token:
token[CLAUSE_IDX] = stack_of_indexes[-1]
... | python | {
"resource": ""
} |
q7666 | ClauseSegmenter.rename_annotations | train | def rename_annotations(self, sentence):
"""Function that renames and restructures clause information."""
annotations = []
for token in sentence:
data = {CLAUSE_IDX: token[CLAUSE_IDX]}
if CLAUSE_ANNOT in token:
if 'KINDEL_PIIR' in token[CLAUSE_ANNOT]:
... | python | {
"resource": ""
} |
q7667 | train_default_model | train | def train_default_model():
"""Function for training the default NER model.
NB! It overwrites the default model, so do not use it unless
you know what are you doing.
The training data is in file estnltk/corpora/estner.json.bz2 .
The resulting model will be saved to estnltk/estner/models/default.bin... | python | {
"resource": ""
} |
q7668 | _get_synset_offsets | train | def _get_synset_offsets(synset_idxes):
"""Returs pointer offset in the WordNet file for every synset index.
Notes
-----
Internal function. Do not call directly.
Preserves order -- for [x,y,z] returns [offset(x),offset(y),offset(z)].
Parameters
----------
synset_idxes : list of ints
... | python | {
"resource": ""
} |
q7669 | _get_synsets | train | def _get_synsets(synset_offsets):
"""Given synset offsets in the WordNet file, parses synset object for every offset.
Notes
-----
Internal function. Do not call directly.
Stores every parsed synset into global synset dictionary under two keys:
synset's name lemma.pos.sense_no and synset's id ... | python | {
"resource": ""
} |
q7670 | _get_key_from_raw_synset | train | def _get_key_from_raw_synset(raw_synset):
"""Derives synset key in the form of `lemma.pos.sense_no` from the provided eurown.py Synset class,
Notes
-----
Internal function. Do not call directly.
Parameters
----------
raw_synset : eurown.Synset
Synset representation from which lemma,... | python | {
"resource": ""
} |
q7671 | synset | train | def synset(synset_key):
"""Returns synset object with the provided key.
Notes
-----
Uses lazy initialization - synsets will be fetched from a dictionary after the first request.
Parameters
----------
synset_key : string
Unique synset identifier in the form of `lemma.pos.sense_no`.
... | python | {
"resource": ""
} |
q7672 | synsets | train | def synsets(lemma,pos=None):
"""Returns all synset objects which have lemma as one of the variant literals and fixed pos, if provided.
Notes
-----
Uses lazy initialization - parses only those synsets which are not yet initialized, others are fetched from a dictionary.
Parameters
----------
... | python | {
"resource": ""
} |
q7673 | all_synsets | train | def all_synsets(pos=None):
"""Return all the synsets which have the provided pos.
Notes
-----
Returns thousands or tens of thousands of synsets - first time will take significant time.
Useful for initializing synsets as each returned synset is also stored in a global dictionary for fast retrieval t... | python | {
"resource": ""
} |
q7674 | lemma | train | def lemma(lemma_key):
"""Returns the Lemma object with the given key.
Parameters
----------
lemma_key : str
Key of the returned lemma.
Returns
-------
Lemma
Lemma matching the `lemma_key`.
"""
if lemma_key in LEMMAS_DICT:
return LEMMAS_DICT[lemma_key]
split... | python | {
"resource": ""
} |
q7675 | lemmas | train | def lemmas(lemma,pos=None):
"""Returns all the Lemma objects of which name is `lemma` and which have `pos` as part
of speech.
Parameters
----------
lemma : str
Literal of the sought Lemma objects.
pos : str, optional
Part of speech of the sought Lemma objects. If None, matches any p... | python | {
"resource": ""
} |
q7676 | Synset._recursive_hypernyms | train | def _recursive_hypernyms(self, hypernyms):
"""Finds all the hypernyms of the synset transitively.
Notes
-----
Internal method. Do not call directly.
Parameters
----------
hypernyms : set of Synsets
An set of hypernyms met so far.
Returns
... | python | {
"resource": ""
} |
q7677 | Synset._min_depth | train | def _min_depth(self):
"""Finds minimum path length from the root.
Notes
-----
Internal method. Do not call directly.
Returns
-------
int
Minimum path length from the root.
"""
if "min_depth" in self.__dict__:
return self.... | python | {
"resource": ""
} |
q7678 | Synset.get_related_synsets | train | def get_related_synsets(self,relation):
"""Retrieves all the synsets which are related by given relation.
Parameters
----------
relation : str
Name of the relation via which the sought synsets are linked.
Returns
-------
list of Synsets
Synse... | python | {
"resource": ""
} |
q7679 | Synset.closure | train | def closure(self, relation, depth=float('inf')):
"""Finds all the ancestors of the synset using provided relation.
Parameters
----------
relation : str
Name of the relation which is recursively used to fetch the ancestors.
Returns
-------
list of ... | python | {
"resource": ""
} |
q7680 | Synset.lch_similarity | train | def lch_similarity(self, synset):
"""Calculates Leacock and Chodorow's similarity between the two synsets.
Notes
-----
Similarity is calculated using the formula -log( (dist(synset1,synset2)+1) / (2*maximum taxonomy depth) ).
Parameters
----------
synset : S... | python | {
"resource": ""
} |
q7681 | SyntaxPreprocessing.process_vm_json | train | def process_vm_json( self, json_dict, **kwargs ):
''' Executes the preprocessing pipeline on vabamorf's JSON, given as a dict;
Returns a list: lines of analyses in the VISL CG3 input format;
'''
mrf_lines = convert_vm_json_to_mrf( json_dict )
return self.process_mrf_lines( ... | python | {
"resource": ""
} |
q7682 | SyntaxPreprocessing.process_Text | train | def process_Text( self, text, **kwargs ):
''' Executes the preprocessing pipeline on estnltk's Text object.
Returns a list: lines of analyses in the VISL CG3 input format;
'''
mrf_lines = convert_Text_to_mrf( text )
return self.process_mrf_lines( mrf_lines, **kwargs ) | python | {
"resource": ""
} |
q7683 | SyntaxPreprocessing.process_mrf_lines | train | def process_mrf_lines( self, mrf_lines, **kwargs ):
''' Executes the preprocessing pipeline on mrf_lines.
The input should be an analysis of the text in Filosoft's old mrf format;
Returns the input list, where elements (tokens/analyses) have been converted
into the new form... | python | {
"resource": ""
} |
q7684 | get_sources | train | def get_sources(src_dir='src', ending='.cpp'):
"""Function to get a list of files ending with `ending` in `src_dir`."""
return [os.path.join(src_dir, fnm) for fnm in os.listdir(src_dir) if fnm.endswith(ending)] | python | {
"resource": ""
} |
q7685 | TextCleaner.clean | train | def clean(self, text):
"""Remove all unwanted characters from text."""
return ''.join([c for c in text if c in self.alphabet]) | python | {
"resource": ""
} |
q7686 | TextCleaner.invalid_characters | train | def invalid_characters(self, text):
"""Give simple list of invalid characters present in text."""
return ''.join(sorted(set([c for c in text if c not in self.alphabet]))) | python | {
"resource": ""
} |
q7687 | TextCleaner.find_invalid_chars | train | def find_invalid_chars(self, text, context_size=20):
"""Find invalid characters in text and store information about
the findings.
Parameters
----------
context_size: int
How many characters to return as the context.
"""
result = defaultdict(list)
... | python | {
"resource": ""
} |
q7688 | TextCleaner.compute_report | train | def compute_report(self, texts, context_size=10):
"""Compute statistics of invalid characters on given texts.
Parameters
----------
texts: list of str
The texts to search for invalid characters.
context_size: int
How many characters to return as the conte... | python | {
"resource": ""
} |
q7689 | TextCleaner.report | train | def report(self, texts, n_examples=10, context_size=10, f=sys.stdout):
"""Compute statistics of invalid characters and print them.
Parameters
----------
texts: list of str
The texts to search for invalid characters.
n_examples: int
How many examples to di... | python | {
"resource": ""
} |
q7690 | __sort_analyses | train | def __sort_analyses(sentence):
''' Sorts analysis of all the words in the sentence.
This is required for consistency, because by default, analyses are
listed in arbitrary order; '''
for word in sentence:
if ANALYSIS not in word:
raise Exception( '(!) Error: no analysis foun... | python | {
"resource": ""
} |
q7691 | augmentTextWithCONLLstr | train | def augmentTextWithCONLLstr( conll_str_array, text ):
''' Augments given Text object with the information from Maltparser's output.
More specifically, adds information about SYNTAX_LABEL, SYNTAX_HEAD and
DEPREL to each token in the Text object;
'''
j = 0
for sentence in text.divide( laye... | python | {
"resource": ""
} |
q7692 | create_rules | train | def create_rules(aes, value):
"""Create a Rules instance for a single aesthetic value.
Parameter
---------
aes: str
The name of the aesthetic
value: str or list
The value associated with any aesthetic
"""
if isinstance(value, six.string_types):
return Rules(aes)
... | python | {
"resource": ""
} |
q7693 | Rules.add_rule | train | def add_rule(self, pattern, css_class):
"""Add a new rule.
Parameters
----------
pattern: str
Pattern that is compiled to a regular expression.
css_class: str
The class that will corresponds to given pattern.
"""
#print('adding rule <{0}> ... | python | {
"resource": ""
} |
q7694 | json_document_to_estner_document | train | def json_document_to_estner_document(jsondoc):
"""Convert an estnltk document to an estner document.
Parameters
----------
jsondoc: dict
Estnltk JSON-style document.
Returns
-------
estnltk.estner.ner.Document
A ner document.
"""
sentences = []
for json_sent in ... | python | {
"resource": ""
} |
q7695 | json_token_to_estner_token | train | def json_token_to_estner_token(json_token):
"""Convert a JSON-style word token to an estner token.
Parameters
----------
vabamorf_token: dict
Vabamorf token representing a single word.
label: str
The label string.
Returns
-------
estnltk.estner.ner.Token
"""
tok... | python | {
"resource": ""
} |
q7696 | ModelStorageUtil.makedir | train | def makedir(self):
""" Create model_dir directory """
try:
os.makedirs(self.model_dir)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise | python | {
"resource": ""
} |
q7697 | ModelStorageUtil.copy_settings | train | def copy_settings(self, settings_module):
""" Copy settings module to the model_dir directory """
source = inspect.getsourcefile(settings_module)
dest = os.path.join(self.model_dir, 'settings.py')
shutil.copyfile(source, dest) | python | {
"resource": ""
} |
q7698 | ModelStorageUtil.load_settings | train | def load_settings(self):
"""Load settings module from the model_dir directory."""
mname = 'loaded_module'
if six.PY2:
import imp
return imp.load_source(mname, self.settings_filename)
else:
import importlib.machinery
loader = importlib.machi... | python | {
"resource": ""
} |
q7699 | VISLCG3Pipeline.check_if_vislcg_is_in_path | train | def check_if_vislcg_is_in_path( self, vislcg_cmd1 ):
''' Checks whether given vislcg_cmd1 is in system's PATH. Returns True, there is
a file named vislcg_cmd1 in the path, otherwise returns False;
The idea borrows from: http://stackoverflow.com/a/377028
'''
for path ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.