id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
170,510 | import random
import warnings
from abc import ABCMeta, abstractmethod
from bisect import bisect
from itertools import accumulate
from nltk.lm.counter import NgramCounter
from nltk.lm.util import log_base2
from nltk.lm.vocabulary import Vocabulary
def _random_generator(seed_or_generator):
if isinstance(seed_or_gene... | null |
170,511 | import random
import warnings
from abc import ABCMeta, abstractmethod
from bisect import bisect
from itertools import accumulate
from nltk.lm.counter import NgramCounter
from nltk.lm.util import log_base2
from nltk.lm.vocabulary import Vocabulary
bisect = bisect_right
The provided code snippet includes necessary depe... | Like random.choice, but with weights. Heavily inspired by python 3.6 `random.choices`. |
170,512 | from math import log
NEG_INF = float("-inf")
def log(x: SupportsFloat, base: SupportsFloat = ...) -> float: ...
The provided code snippet includes necessary dependencies for implementing the `log_base2` function. Write a Python function `def log_base2(score)` to solve the following problem:
Convenience function for c... | Convenience function for computing logarithms with base 2. |
170,513 | from operator import methodcaller
from nltk.lm.api import Smoothing
from nltk.probability import ConditionalFreqDist
def methodcaller(__name: str, *args: Any, **kwargs: Any) -> Callable[..., Any]: ...
class ConditionalFreqDist(defaultdict):
"""
A collection of frequency distributions for a single experiment
... | Count values that are greater than zero in a distribution. Assumes distribution is either a mapping with counts as values or an instance of `nltk.ConditionalFreqDist`. |
170,514 | from functools import partial
from itertools import chain
from nltk.util import everygrams, pad_sequence
pad_both_ends = partial(
pad_sequence,
pad_left=True,
left_pad_symbol="<s>",
pad_right=True,
right_pad_symbol="</s>",
)
pad_both_ends.__doc__ = """Pads both ends of a sentence to length specified... | Helper with some useful defaults. Applies pad_both_ends to sentence and follows it up with everygrams. |
170,515 | from functools import partial
from itertools import chain
from nltk.util import everygrams, pad_sequence
flatten = chain.from_iterable
pad_both_ends = partial(
pad_sequence,
pad_left=True,
left_pad_symbol="<s>",
pad_right=True,
right_pad_symbol="</s>",
)
pad_both_ends.__doc__ = """Pads both ends of ... | Default preprocessing for a sequence of sentences. Creates two iterators: - sentences padded and turned into sequences of `nltk.util.everygrams` - sentences padded as above and chained together for a flat stream of words :param order: Largest ngram length produced by `everygrams`. :param text: Text to iterate over. Exp... |
170,516 | import sys
from collections import Counter
from collections.abc import Iterable
from functools import singledispatch
from itertools import chain
def _dispatched_lookup(words, vocab):
raise TypeError(f"Unsupported type for looking up in vocabulary: {type(words)}")
The provided code snippet includes necessary depend... | Look up a sequence of words in the vocabulary. Returns an iterator over looked up words. |
170,517 | import sys
from collections import Counter
from collections.abc import Iterable
from functools import singledispatch
from itertools import chain
The provided code snippet includes necessary dependencies for implementing the `_string_lookup` function. Write a Python function `def _string_lookup(word, vocab)` to solve t... | Looks up one word in the vocabulary. |
170,518 | import click
from tqdm import tqdm
from nltk import word_tokenize
from nltk.util import parallelize_preprocess
def cli():
pass | null |
170,519 | import click
from tqdm import tqdm
from nltk import word_tokenize
from nltk.util import parallelize_preprocess
def parallelize_preprocess(func, iterator, processes, progress_bar=False):
from joblib import Parallel, delayed
from tqdm import tqdm
iterator = tqdm(iterator) if progress_bar else iterator
i... | This command tokenizes text stream using nltk.word_tokenize |
170,520 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | null |
170,521 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Return True if this function is run within idle. Tkinter programs that are run in idle should never call ``Tk.mainloop``; so this function should be used to gate all calls to ``Tk.mainloop``. :warning: This function works by checking ``sys.stdin``. If the user has modified ``sys.stdin``, then it may return incorrect re... |
170,522 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Pretty print a sequence of data items :param data: the data stream to print :type data: sequence or iter :param start: the start position :type start: int :param end: the end position :type end: int |
170,523 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Pretty print a string, breaking lines on whitespace :param s: the string to print, consisting of words and spaces :type s: str :param width: the display width :type width: int |
170,524 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Pretty print a list of text tokens, breaking lines on whitespace :param tokens: the tokens to print :type tokens: list :param separator: the string to use to separate tokens :type separator: str :param width: the display width (default=70) :type width: int |
170,525 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Return a string with markers surrounding the matched substrings. Search str for substrings matching ``regexp`` and wrap the matches with braces. This is convenient for learning about regular expressions. :param regexp: The regular expression. :type regexp: str :param string: The string being matched. :type string: str ... |
170,526 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | null |
170,527 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Traverse the nodes of a tree in breadth-first order. (No check for cycles.) The first argument should be the tree root; children should be a function taking as argument a tree node and returning an iterator of the node's children. |
170,528 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Build a Minimum Spanning Tree (MST) of an unweighted graph, by traversing the nodes of a tree in breadth-first order, discarding eventual cycles. Return a representation of this MST as a string in the DOT graph language, which can be converted to an image by the 'dot' program from the Graphviz package, or nltk.parse.de... |
170,529 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Traverse the nodes of a tree in breadth-first order, discarding eventual cycles. The first argument should be the tree root; children should be a function taking as argument a tree node and returning an iterator of the node's children. |
170,530 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Traverse the nodes of a tree in depth-first order, discarding eventual cycles within any branch, adding cut_mark (when specified) if cycles were truncated. The first argument should be the tree root; children should be a function taking as argument a tree node and returning an iterator of the node's children. Catches a... |
170,531 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Traverse the nodes of a tree in depth-first order, discarding eventual cycles within the same branch, but keep duplicate paths in different branches. Add cut_mark (when defined) if cycles were truncated. The first argument should be the tree root; children should be a function taking as argument a tree node and returni... |
170,532 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Output a Minimum Spanning Tree (MST) of an unweighted graph, by traversing the nodes of a tree in breadth-first order, discarding eventual cycles. The first argument should be the tree root; children should be a function taking as argument a tree node and returning an iterator of the node's children. >>> import nltk >>... |
170,533 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Given a byte string, attempt to decode it. Tries the standard 'UTF8' and 'latin-1' encodings, Plus several gathered from locale information. The calling program *must* first call:: locale.setlocale(locale.LC_ALL, '') If successful it returns ``(decoded_unicode, successful_encoding)``. If unsuccessful it raises a ``Unic... |
170,534 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | null |
170,535 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | null |
170,536 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Calculate the transitive closure of a directed graph, optionally the reflexive transitive closure. The algorithm is a slight modification of the "Marking Algorithm" of Ioannidis & Ramakrishnan (1998) "Efficient Transitive Closure Algorithms". :param graph: the initial graph, represented as a dictionary of sets :type gr... |
170,537 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Inverts a directed graph. :param graph: the graph, represented as a dictionary of sets :type graph: dict(set) :return: the inverted graph :rtype: dict(set) |
170,538 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | null |
170,539 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | null |
170,540 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Return the bigrams generated from a sequence of items, as an iterator. For example: >>> from nltk.util import bigrams >>> list(bigrams([1,2,3,4,5])) [(1, 2), (2, 3), (3, 4), (4, 5)] Use bigrams for a list version of this function. :param sequence: the source data to be converted into bigrams :type sequence: sequence or... |
170,541 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Return the trigrams generated from a sequence of items, as an iterator. For example: >>> from nltk.util import trigrams >>> list(trigrams([1,2,3,4,5])) [(1, 2, 3), (2, 3, 4), (3, 4, 5)] Use trigrams for a list version of this function. :param sequence: the source data to be converted into trigrams :type sequence: seque... |
170,542 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Returns all possible skipgrams generated from a sequence of items, as an iterator. Skipgrams are ngrams that allows tokens to be skipped. Refer to http://homepages.inf.ed.ac.uk/ballison/pdf/lrec_skipgrams.pdf >>> sent = "Insurgents killed in ongoing fighting".split() >>> list(skipgrams(sent, 2, 2)) [('Insurgents', 'kil... |
170,543 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Return the line from the file with first word key. Searches through a sorted file using the binary search algorithm. :type file: file :param file: the file to be searched through. :type key: str :param key: the identifier we are searching for. |
170,544 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Set the HTTP proxy for Python to download through. If ``proxy`` is None then tries to set proxy from environment or system settings. :param proxy: The HTTP proxy server to use. For example: 'http://proxy.example.com:3128/' :param user: The username to authenticate with. Use None to disable authentication. :param passwo... |
170,545 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | Recursive function to indent an ElementTree._ElementInterface used for pretty printing. Run indent on elem and then output in the normal way. :param elem: element to be indented. will be modified. :type elem: ElementTree._ElementInterface :param level: level of indentation for this element :type level: nonnegative inte... |
170,546 | import inspect
import locale
import os
import pydoc
import re
import textwrap
import warnings
from collections import defaultdict, deque
from itertools import chain, combinations, islice, tee
from pprint import pprint
from urllib.request import (
HTTPPasswordMgrWithDefaultRealm,
ProxyBasicAuthHandler,
Proxy... | s -> (s0,s1), (s1,s2), (s2, s3), ... |
170,547 | import os
import tempfile
from nltk.inference.api import BaseModelBuilderCommand, ModelBuilder
from nltk.inference.prover9 import Prover9CommandParent, Prover9Parent
from nltk.sem import Expression, Valuation
from nltk.sem.logic import is_indvar
class MaceCommand(Prover9CommandParent, BaseModelBuilderCommand):
"""
... | null |
170,548 | import os
import tempfile
from nltk.inference.api import BaseModelBuilderCommand, ModelBuilder
from nltk.inference.prover9 import Prover9CommandParent, Prover9Parent
from nltk.sem import Expression, Valuation
from nltk.sem.logic import is_indvar
def test_model_found(arguments):
"""
Try some proofs and exhibit t... | null |
170,549 | from nltk.inference.api import BaseProverCommand, Prover
from nltk.internals import Counter
from nltk.sem.logic import (
AbstractVariableExpression,
AllExpression,
AndExpression,
ApplicationExpression,
EqualityExpression,
ExistsExpression,
Expression,
FunctionVariableExpression,
IffE... | null |
170,550 | import operator
from collections import defaultdict
from functools import reduce
from nltk.inference.api import BaseProverCommand, Prover
from nltk.sem import skolemize
from nltk.sem.logic import (
AndExpression,
ApplicationExpression,
EqualityExpression,
Expression,
IndividualVariableExpression,
... | This method facilitates movement through the terms of 'self' |
170,551 | import operator
from collections import defaultdict
from functools import reduce
from nltk.inference.api import BaseProverCommand, Prover
from nltk.sem import skolemize
from nltk.sem.logic import (
AndExpression,
ApplicationExpression,
EqualityExpression,
Expression,
IndividualVariableExpression,
... | null |
170,552 | import operator
from collections import defaultdict
from functools import reduce
from nltk.inference.api import BaseProverCommand, Prover
from nltk.sem import skolemize
from nltk.sem.logic import (
AndExpression,
ApplicationExpression,
EqualityExpression,
Expression,
IndividualVariableExpression,
... | null |
170,553 | import operator
from collections import defaultdict
from functools import reduce
from nltk.inference.api import BaseProverCommand, Prover
from nltk.sem import skolemize
from nltk.sem.logic import (
AndExpression,
ApplicationExpression,
EqualityExpression,
Expression,
IndividualVariableExpression,
... | null |
170,554 | import os
from abc import ABCMeta, abstractmethod
from functools import reduce
from operator import add, and_
from nltk.data import show_cfg
from nltk.inference.mace import MaceCommand
from nltk.inference.prover9 import Prover9Command
from nltk.parse import load_parser
from nltk.parse.malt import MaltParser
from nltk.s... | Temporarily duplicated from ``nltk.sem.util``. Convert a file of first order formulas into a list of ``Expression`` objects. :param s: the contents of the file :type s: str :return: a list of parsed formulas. :rtype: list(Expression) |
170,555 | import os
from abc import ABCMeta, abstractmethod
from functools import reduce
from operator import add, and_
from nltk.data import show_cfg
from nltk.inference.mace import MaceCommand
from nltk.inference.prover9 import Prover9Command
from nltk.parse import load_parser
from nltk.parse.malt import MaltParser
from nltk.s... | null |
170,556 | import os
from abc import ABCMeta, abstractmethod
from functools import reduce
from operator import add, and_
from nltk.data import show_cfg
from nltk.inference.mace import MaceCommand
from nltk.inference.prover9 import Prover9Command
from nltk.parse import load_parser
from nltk.parse.malt import MaltParser
from nltk.s... | null |
170,557 | from collections import defaultdict
from functools import reduce
from nltk.inference.api import Prover, ProverCommandDecorator
from nltk.inference.prover9 import Prover9, Prover9Command
from nltk.sem.logic import (
AbstractVariableExpression,
AllExpression,
AndExpression,
ApplicationExpression,
Bool... | null |
170,558 | from collections import defaultdict
from functools import reduce
from nltk.inference.api import Prover, ProverCommandDecorator
from nltk.inference.prover9 import Prover9, Prover9Command
from nltk.sem.logic import (
AbstractVariableExpression,
AllExpression,
AndExpression,
ApplicationExpression,
Bool... | null |
170,559 | import os
import subprocess
import nltk
from nltk.inference.api import BaseProverCommand, Prover
from nltk.sem.logic import (
AllExpression,
AndExpression,
EqualityExpression,
ExistsExpression,
Expression,
IffExpression,
ImpExpression,
NegatedExpression,
OrExpression,
)
def test_conf... | null |
170,560 | from abc import ABCMeta, abstractmethod
from tkinter import (
RAISED,
Button,
Canvas,
Entry,
Frame,
Label,
Menu,
Menubutton,
Scrollbar,
StringVar,
Text,
Tk,
Toplevel,
Widget,
)
from tkinter.filedialog import asksaveasfilename
from nltk.util import in_idle
class Te... | A simple demonstration showing how to use canvas widgets. |
170,561 | from tkinter import IntVar, Menu, Tk
from nltk.draw.util import (
BoxWidget,
CanvasFrame,
CanvasWidget,
OvalWidget,
ParenWidget,
TextWidget,
)
from nltk.tree import Tree
from nltk.util import in_idle
def tree_to_treesegment(
canvas, t, make_node=TextWidget, make_leaf=TextWidget, **attribs
):... | null |
170,562 | import operator
from tkinter import Frame, Label, Listbox, Scrollbar, Tk
class Table:
"""
A display widget for a table of values, based on a ``MultiListbox``
widget. For many purposes, ``Table`` can be treated as a
list-of-lists. E.g., table[i] is a list of the values for row i;
and table.append(r... | null |
170,563 |
The provided code snippet includes necessary dependencies for implementing the `dispersion_plot` function. Write a Python function `def dispersion_plot(text, words, ignore_case=False, title="Lexical Dispersion Plot")` to solve the following problem:
Generate a lexical dispersion plot. :param text: The source text :ty... | Generate a lexical dispersion plot. :param text: The source text :type text: list(str) or iter(str) :param words: The target words :type words: list of str :param ignore_case: flag to set if case should be ignored when searching text :type ignore_case: bool :return: a matplotlib Axes object that may still be modified b... |
170,564 | import re
from tkinter import (
Button,
Canvas,
Entry,
Frame,
IntVar,
Label,
Scrollbar,
Text,
Tk,
Toplevel,
)
from nltk.draw.tree import TreeSegmentWidget, tree_to_treesegment
from nltk.draw.util import (
CanvasFrame,
ColorizedList,
ShowText,
SymbolWidget,
Tex... | null |
170,565 | import re
from tkinter import (
Button,
Canvas,
Entry,
Frame,
IntVar,
Label,
Scrollbar,
Text,
Tk,
Toplevel,
)
from nltk.draw.tree import TreeSegmentWidget, tree_to_treesegment
from nltk.draw.util import (
CanvasFrame,
ColorizedList,
ShowText,
SymbolWidget,
Tex... | null |
170,566 | import re
from tkinter import (
Button,
Canvas,
Entry,
Frame,
IntVar,
Label,
Scrollbar,
Text,
Tk,
Toplevel,
)
from nltk.draw.tree import TreeSegmentWidget, tree_to_treesegment
from nltk.draw.util import (
CanvasFrame,
ColorizedList,
ShowText,
SymbolWidget,
Tex... | null |
170,567 | def align(str1, str2, epsilon=0):
"""
Compute the alignment of two phonetic strings.
:param str str1: First string to be aligned
:param str str2: Second string to be aligned
:type epsilon: float (0.0 to 1.0)
:param epsilon: Adjusts threshold similarity score for near-optimal alignments
:rtyp... | A demonstration of the result of aligning phonetic sequences used in Kondrak's (2002) dissertation. |
170,568 |
The provided code snippet includes necessary dependencies for implementing the `ranks_from_sequence` function. Write a Python function `def ranks_from_sequence(seq)` to solve the following problem:
Given a sequence, yields each element with an increasing rank, suitable for use as an argument to ``spearman_correlation... | Given a sequence, yields each element with an increasing rank, suitable for use as an argument to ``spearman_correlation``. |
170,569 | from math import sqrt
The provided code snippet includes necessary dependencies for implementing the `get_words_from_dictionary` function. Write a Python function `def get_words_from_dictionary(lemmas)` to solve the following problem:
Get original set of words used for analysis. :param lemmas: A dictionary where keys ... | Get original set of words used for analysis. :param lemmas: A dictionary where keys are lemmas and values are sets or lists of words corresponding to that lemma. :type lemmas: dict(str): list(str) :return: Set of words that exist as values in the dictionary :rtype: set(str) |
170,570 | from math import sqrt
The provided code snippet includes necessary dependencies for implementing the `_truncate` function. Write a Python function `def _truncate(words, cutlength)` to solve the following problem:
Group words by stems defined by truncating them at given length. :param words: Set of words used for analy... | Group words by stems defined by truncating them at given length. :param words: Set of words used for analysis :param cutlength: Words are stemmed by cutting at this length. :type words: set(str) or list(str) :type cutlength: int :return: Dictionary where keys are stems and values are sets of words corresponding to that... |
170,571 | from math import sqrt
The provided code snippet includes necessary dependencies for implementing the `_count_intersection` function. Write a Python function `def _count_intersection(l1, l2)` to solve the following problem:
Count intersection between two line segments defined by coordinate pairs. :param l1: Tuple of tw... | Count intersection between two line segments defined by coordinate pairs. :param l1: Tuple of two coordinate pairs defining the first line segment :param l2: Tuple of two coordinate pairs defining the second line segment :type l1: tuple(float, float) :type l2: tuple(float, float) :return: Coordinates of the intersectio... |
170,572 | from math import sqrt
The provided code snippet includes necessary dependencies for implementing the `_get_derivative` function. Write a Python function `def _get_derivative(coordinates)` to solve the following problem:
Get derivative of the line from (0,0) to given coordinates. :param coordinates: A coordinate pair :... | Get derivative of the line from (0,0) to given coordinates. :param coordinates: A coordinate pair :type coordinates: tuple(float, float) :return: Derivative; inf if x is zero :rtype: float |
170,573 | from math import sqrt
def _calculate_cut(lemmawords, stems):
"""Count understemmed and overstemmed pairs for (lemma, stem) pair with common words.
:param lemmawords: Set or list of words corresponding to certain lemma.
:param stems: A dictionary where keys are stems and values are sets
or lists of words... | Calculate actual and maximum possible amounts of understemmed and overstemmed word pairs. :param lemmas: A dictionary where keys are lemmas and values are sets or lists of words corresponding to that lemma. :param stems: A dictionary where keys are stems and values are sets or lists of words corresponding to that stem.... |
170,574 | from math import sqrt
The provided code snippet includes necessary dependencies for implementing the `_indexes` function. Write a Python function `def _indexes(gumt, gdmt, gwmt, gdnt)` to solve the following problem:
Count Understemming Index (UI), Overstemming Index (OI) and Stemming Weight (SW). :param gumt, gdmt, g... | Count Understemming Index (UI), Overstemming Index (OI) and Stemming Weight (SW). :param gumt, gdmt, gwmt, gdnt: Global unachieved merge total (gumt), global desired merge total (gdmt), global wrongly merged total (gwmt) and global desired non-merge total (gdnt). :type gumt, gdmt, gwmt, gdnt: float :return: Understemmi... |
170,575 | from math import sqrt
class Paice:
"""Class for storing lemmas, stems and evaluation metrics."""
def __init__(self, lemmas, stems):
"""
:param lemmas: A dictionary where keys are lemmas and values are sets
or lists of words corresponding to that lemma.
:param stems: A diction... | Demonstration of the module. |
170,576 |
The provided code snippet includes necessary dependencies for implementing the `windowdiff` function. Write a Python function `def windowdiff(seg1, seg2, k, boundary="1", weighted=False)` to solve the following problem:
Compute the windowdiff score for a pair of segmentations. A segmentation is any sequence over a vo... | Compute the windowdiff score for a pair of segmentations. A segmentation is any sequence over a vocabulary of two items (e.g. "0", "1"), where the specified boundary value is used to mark the edge of a segmentation. >>> s1 = "000100000010" >>> s2 = "000010000100" >>> s3 = "100000010000" >>> '%.2f' % windowdiff(s1, s1, ... |
170,577 | def _init_mat(nrows, ncols, ins_cost, del_cost):
mat = np.empty((nrows, ncols))
mat[0, :] = ins_cost * np.arange(ncols)
mat[:, 0] = del_cost * np.arange(nrows)
return mat
def _ghd_aux(mat, rowv, colv, ins_cost, del_cost, shift_cost_coeff):
for i, rowi in enumerate(rowv):
for j, colj in enume... | Compute the Generalized Hamming Distance for a reference and a hypothetical segmentation, corresponding to the cost related to the transformation of the hypothetical segmentation into the reference segmentation through boundary insertion, deletion and shift operations. A segmentation is any sequence over a vocabulary o... |
170,578 |
The provided code snippet includes necessary dependencies for implementing the `pk` function. Write a Python function `def pk(ref, hyp, k=None, boundary="1")` to solve the following problem:
Compute the Pk metric for a pair of segmentations A segmentation is any sequence over a vocabulary of two items (e.g. "0", "1")... | Compute the Pk metric for a pair of segmentations A segmentation is any sequence over a vocabulary of two items (e.g. "0", "1"), where the specified boundary value is used to mark the edge of a segmentation. >>> '%.2f' % pk('0100'*100, '1'*400, 2) '0.50' >>> '%.2f' % pk('0100'*100, '0'*400, 2) '0.50' >>> '%.2f' % pk('0... |
170,579 | from nltk.probability import FreqDist
class ConfusionMatrix:
"""
The confusion matrix between a list of reference values and a
corresponding list of test values. Entry *[r,t]* of this
matrix is a count of the number of times that the reference value
*r* corresponds to the test value *t*. E.g.:
... | null |
170,580 | import operator
import warnings
def _edit_dist_init(len1, len2):
lev = []
for i in range(len1):
lev.append([0] * len2) # initialize 2D array to zero
for i in range(len1):
lev[i][0] = i # column 0: 0,1,2,3,4,...
for j in range(len2):
lev[0][j] = j # row 0: 0,1,2,3,4,...
ret... | Calculate the minimum Levenshtein edit-distance based alignment mapping between two strings. The alignment finds the mapping from string s1 to s2 that minimizes the edit distance cost. For example, mapping "rain" to "shine" would involve 2 substitutions, 2 matches and an insertion resulting in the following mapping: [(... |
170,581 | import operator
import warnings
The provided code snippet includes necessary dependencies for implementing the `interval_distance` function. Write a Python function `def interval_distance(label1, label2)` to solve the following problem:
Krippendorff's interval distance metric >>> from nltk.metrics import interval_dist... | Krippendorff's interval distance metric >>> from nltk.metrics import interval_distance >>> interval_distance(1,10) 81 Krippendorff 1980, Content Analysis: An Introduction to its Methodology |
170,582 | import operator
import warnings
The provided code snippet includes necessary dependencies for implementing the `presence` function. Write a Python function `def presence(label)` to solve the following problem:
Higher-order function to test presence of a given label
Here is the function:
def presence(label):
"""H... | Higher-order function to test presence of a given label |
170,583 | import operator
import warnings
def fractional_presence(label):
return (
lambda x, y: abs((1.0 / len(x)) - (1.0 / len(y))) * (label in x and label in y)
or 0.0 * (label not in x and label not in y)
or abs(1.0 / len(x)) * (label in x and label not in y)
or (1.0 / len(y)) * (label not... | null |
170,584 | import operator
import warnings
def custom_distance(file):
data = {}
with open(file) as infile:
for l in infile:
labelA, labelB, dist = l.strip().split("\t")
labelA = frozenset([labelA])
labelB = frozenset([labelB])
data[frozenset([labelA, labelB])] = flo... | null |
170,585 | import operator
import warnings
def edit_distance(s1, s2, substitution_cost=1, transpositions=False):
"""
Calculate the Levenshtein edit-distance between two strings.
The edit distance is the number of characters that need to be
substituted, inserted, or deleted, to transform s1 into s2. For
exampl... | null |
170,586 | import operator
from functools import reduce
from math import fabs
from random import shuffle
from nltk.util import LazyConcatenation, LazyMap
The provided code snippet includes necessary dependencies for implementing the `log_likelihood` function. Write a Python function `def log_likelihood(reference, test)` to solve... | Given a list of reference values and a corresponding list of test probability distributions, return the average log likelihood of the reference values, given the probability distributions. :param reference: A list of reference values :type reference: list :param test: A list of probability distributions over values to ... |
170,587 | import operator
from functools import reduce
from math import fabs
from random import shuffle
from nltk.util import LazyConcatenation, LazyMap
def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ...
def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ...
de... | Returns an approximate significance level between two lists of independently generated test values. Approximate randomization calculates significance by randomly drawing from a sample of the possible permutations. At the limit of the number of possible permutations, the significance level is exact. The approximate sign... |
170,588 | import operator
from functools import reduce
from math import fabs
from random import shuffle
from nltk.util import LazyConcatenation, LazyMap
def accuracy(reference, test):
"""
Given a list of reference values and a corresponding list of test
values, return the fraction of corresponding values that are
... | null |
170,589 | import math as _math
from abc import ABCMeta, abstractmethod
from functools import reduce
def fisher_exact(*_args, **_kwargs):
raise NotImplementedError | null |
170,590 | import copy
import re
from functools import total_ordering
from nltk.internals import raise_unorderable_types, read_str
from nltk.sem.logic import (
Expression,
LogicalExpressionException,
LogicParser,
SubstituteBindingsI,
Variable,
)
_FROZEN_ERROR = "Frozen FeatStructs may not be modified."
_FROZEN... | Given a method function, return a new method function that first checks if ``self._frozen`` is true; and if so, raises ``ValueError`` with an appropriate message. Otherwise, call the method and return its result. |
170,591 | import copy
import re
from functools import total_ordering
from nltk.internals import raise_unorderable_types, read_str
from nltk.sem.logic import (
Expression,
LogicalExpressionException,
LogicParser,
SubstituteBindingsI,
Variable,
)
def _retract_bindings(fstruct, inv_bindings, fs_class, visited):
... | Return the feature structure that is obtained by replacing each feature structure value that is bound by ``bindings`` with the variable that binds it. A feature structure value must be identical to a bound value (i.e., have equal id) to be replaced. ``bindings`` is modified to point to this new feature structure, rathe... |
170,592 | import copy
import re
from functools import total_ordering
from nltk.internals import raise_unorderable_types, read_str
from nltk.sem.logic import (
Expression,
LogicalExpressionException,
LogicParser,
SubstituteBindingsI,
Variable,
)
def find_variables(fstruct, fs_class="default"):
"""
:ret... | Return the feature structure that is obtained by replacing any of this feature structure's variables that are in ``vars`` with new variables. The names for these new variables will be names that are not used by any variable in ``vars``, or in ``used_vars``, or in this feature structure. :type vars: set :param vars: The... |
170,593 | import copy
import re
from functools import total_ordering
from nltk.internals import raise_unorderable_types, read_str
from nltk.sem.logic import (
Expression,
LogicalExpressionException,
LogicParser,
SubstituteBindingsI,
Variable,
)
def _remove_variables(fstruct, fs_class, visited):
if id(fstr... | :rtype: FeatStruct :return: The feature structure that is obtained by deleting all features whose values are ``Variables``. |
170,594 | import copy
import re
from functools import total_ordering
from nltk.internals import raise_unorderable_types, read_str
from nltk.sem.logic import (
Expression,
LogicalExpressionException,
LogicParser,
SubstituteBindingsI,
Variable,
)
def unify(
fstruct1,
fstruct2,
bindings=None,
tra... | Return True if ``fstruct1`` subsumes ``fstruct2``. I.e., return true if unifying ``fstruct1`` with ``fstruct2`` would result in a feature structure equal to ``fstruct2.`` :rtype: bool |
170,595 | import copy
import re
from functools import total_ordering
from nltk.internals import raise_unorderable_types, read_str
from nltk.sem.logic import (
Expression,
LogicalExpressionException,
LogicParser,
SubstituteBindingsI,
Variable,
)
def unify(
fstruct1,
fstruct2,
bindings=None,
tra... | Return a list of the feature paths of all features which are assigned incompatible values by ``fstruct1`` and ``fstruct2``. :rtype: list(tuple) |
170,596 | import copy
import re
from functools import total_ordering
from nltk.internals import raise_unorderable_types, read_str
from nltk.sem.logic import (
Expression,
LogicalExpressionException,
LogicParser,
SubstituteBindingsI,
Variable,
)
The provided code snippet includes necessary dependencies for im... | Helper function -- return a copy of list, with all elements of type ``cls`` spliced in rather than appended in. |
170,597 | import copy
import re
from functools import total_ordering
from nltk.internals import raise_unorderable_types, read_str
from nltk.sem.logic import (
Expression,
LogicalExpressionException,
LogicParser,
SubstituteBindingsI,
Variable,
)
class FeatStruct(SubstituteBindingsI):
"""
A mapping from... | null |
170,598 | import copy
import re
from functools import total_ordering
from nltk.internals import raise_unorderable_types, read_str
from nltk.sem.logic import (
Expression,
LogicalExpressionException,
LogicParser,
SubstituteBindingsI,
Variable,
)
class FeatStruct(SubstituteBindingsI):
"""
A mapping from... | Just for testing |
170,599 | import subprocess
from collections import namedtuple
def _giza2pair(pair_string):
i, j = pair_string.split("-")
return int(i), int(j) | null |
170,600 | import subprocess
from collections import namedtuple
def _naacl2pair(pair_string):
i, j, p = pair_string.split("-")
return int(i), int(j) | null |
170,601 | import subprocess
from collections import namedtuple
class Alignment(frozenset):
"""
A storage class for representing alignment between two sequences, s1, s2.
In general, an alignment is a set of tuples of the form (i, j, ...)
representing an alignment between the i-th element of s1 and the
j-th ele... | Check whether the alignments are legal. :param num_words: the number of source language words :type num_words: int :param num_mots: the number of target language words :type num_mots: int :param alignment: alignment to be checked :type alignment: Alignment :raise IndexError: if alignment falls outside the sentence |
170,602 | def extract(
f_start,
f_end,
e_start,
e_end,
alignment,
f_aligned,
srctext,
trgtext,
srclen,
trglen,
max_phrase_length,
):
"""
This function checks for alignment point consistency and extracts
phrases using the chunk of consistent phrases.
A phrase pair (e, f ... | Phrase extraction algorithm extracts all consistent phrase pairs from a word-aligned sentence pair. The idea is to loop over all possible source language (e) phrases and find the minimal foreign phrase (f) that matches each of them. Matching is done by identifying all alignment points for the source phrase and finding ... |
170,603 | from bisect import insort_left
from collections import defaultdict
from copy import deepcopy
from math import ceil
The provided code snippet includes necessary dependencies for implementing the `longest_target_sentence_length` function. Write a Python function `def longest_target_sentence_length(sentence_aligned_corpu... | :param sentence_aligned_corpus: Parallel corpus under consideration :type sentence_aligned_corpus: list(AlignedSent) :return: Number of words in the longest target language sentence of ``sentence_aligned_corpus`` |
170,604 | from collections import Counter
from nltk.util import everygrams, ngrams
def corpus_gleu(list_of_references, hypotheses, min_len=1, max_len=4):
"""
Calculate a single corpus-level GLEU score (aka. system-level GLEU) for all
the hypotheses and their respective references.
Instead of averaging the sentenc... | Calculates the sentence level GLEU (Google-BLEU) score described in Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V. Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, Yuan Cao, Qin Gao, Klaus Macherey, Jeff Klingner, Apurva Shah, Melvin Johnson, Xiaobing Liu, Lukasz Kaiser, Stephan Gouws, Yoshikiyo Kato, Taku Kudo... |
170,605 | from itertools import chain, product
from typing import Callable, Iterable, List, Tuple
from nltk.corpus import WordNetCorpusReader, wordnet
from nltk.stem.api import StemmerI
from nltk.stem.porter import PorterStemmer
def _generate_enums(
hypothesis: Iterable[str],
reference: Iterable[str],
preprocess: Cal... | matches exact words in hypothesis and reference and returns a word mapping based on the enumerated word id between hypothesis and reference :param hypothesis: pre-tokenized hypothesis :param reference: pre-tokenized reference :return: enumerated matched tuples, enumerated unmatched hypothesis tuples, enumerated unmatch... |
170,606 | from itertools import chain, product
from typing import Callable, Iterable, List, Tuple
from nltk.corpus import WordNetCorpusReader, wordnet
from nltk.stem.api import StemmerI
from nltk.stem.porter import PorterStemmer
def _generate_enums(
hypothesis: Iterable[str],
reference: Iterable[str],
preprocess: Cal... | Stems each word and matches them in hypothesis and reference and returns a word mapping between hypothesis and reference :param hypothesis: pre-tokenized hypothesis :param reference: pre-tokenized reference :param stemmer: nltk.stem.api.StemmerI object (default PorterStemmer()) :return: enumerated matched tuples, enume... |
170,607 | from itertools import chain, product
from typing import Callable, Iterable, List, Tuple
from nltk.corpus import WordNetCorpusReader, wordnet
from nltk.stem.api import StemmerI
from nltk.stem.porter import PorterStemmer
def _generate_enums(
hypothesis: Iterable[str],
reference: Iterable[str],
preprocess: Cal... | Matches each word in reference to a word in hypothesis if any synonym of a hypothesis word is the exact match to the reference word. :param hypothesis: pre-tokenized hypothesis :param reference: pre-tokenized reference :param wordnet: a wordnet corpus reader object (default nltk.corpus.wordnet) :return: list of mapped ... |
170,608 | from itertools import chain, product
from typing import Callable, Iterable, List, Tuple
from nltk.corpus import WordNetCorpusReader, wordnet
from nltk.stem.api import StemmerI
from nltk.stem.porter import PorterStemmer
def _generate_enums(
hypothesis: Iterable[str],
reference: Iterable[str],
preprocess: Cal... | Aligns/matches words in the hypothesis to reference by sequentially applying exact match, stemmed match and wordnet based synonym match. In case there are multiple matches the match which has the least number of crossing is chosen. :param hypothesis: pre-tokenized hypothesis :param reference: pre-tokenized reference :p... |
170,609 | from itertools import chain, product
from typing import Callable, Iterable, List, Tuple
from nltk.corpus import WordNetCorpusReader, wordnet
from nltk.stem.api import StemmerI
from nltk.stem.porter import PorterStemmer
def single_meteor_score(
reference: Iterable[str],
hypothesis: Iterable[str],
preprocess:... | Calculates METEOR score for hypothesis with multiple references as described in "Meteor: An Automatic Metric for MT Evaluation with HighLevels of Correlation with Human Judgments" by Alon Lavie and Abhaya Agarwal, in Proceedings of ACL. https://www.cs.cmu.edu/~alavie/METEOR/pdf/Lavie-Agarwal-2007-METEOR.pdf In case of ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.