_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q258200 | sim_manhattan | validation | def sim_manhattan(src, tar, qval=2, alphabet=None):
"""Return the normalized Manhattan similarity of two strings.
This is a wrapper for :py:meth:`Manhattan.sim`.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : int
The length of each q-gram; 0 for non-q-gram version
alphabet : collection or int
The values or size of the alphabet
Returns
-------
float
The normalized Manhattan similarity
| python | {
"resource": ""
} |
q258201 | dist_jaro_winkler | validation | def dist_jaro_winkler(
src,
tar,
qval=1,
mode='winkler',
long_strings=False,
boost_threshold=0.7,
scaling_factor=0.1,
):
"""Return the Jaro or Jaro-Winkler distance between two strings.
This is a wrapper for :py:meth:`JaroWinkler.dist`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
qval : int
The length of each q-gram (defaults to 1: character-wise matching)
mode : str
Indicates which variant of this distance metric to compute:
- ``winkler`` -- computes the Jaro-Winkler distance (default) which
increases the score for matches near the start of the word
- ``jaro`` -- computes the Jaro distance
long_strings : bool
Set to True to "Increase the probability of a match when the number of
matched characters is large. This option allows for a little more
tolerance when the strings are large. It is not an appropriate test
when comparing fixedlength fields such as phone and social security
numbers." (Used in 'winkler' mode only.)
boost_threshold : float
A value between 0 and 1, below which the Winkler boost is not applied
(defaults to 0.7). (Used in 'winkler' mode only.)
scaling_factor : float
A value between 0 and 0.25, indicating by how much to boost scores for
matching prefixes (defaults to 0.1). (Used in 'winkler' | python | {
"resource": ""
} |
q258202 | sim_hamming | validation | def sim_hamming(src, tar, diff_lens=True):
"""Return the normalized Hamming similarity of two strings.
This is a wrapper for :py:meth:`Hamming.sim`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
diff_lens : bool
If True (default), this returns the Hamming distance for those
characters that have a matching character in both strings plus the
difference in the strings' lengths. This is equivalent to extending the
shorter string with obligatorily non-matching characters. If False, an
exception is raised in the case of strings of unequal lengths.
Returns
-------
| python | {
"resource": ""
} |
q258203 | SkeletonKey.fingerprint | validation | def fingerprint(self, word):
"""Return the skeleton key.
Parameters
----------
word : str
The word to transform into its skeleton key
Returns
-------
str
The skeleton key
Examples
--------
>>> sk = SkeletonKey()
>>> sk.fingerprint('The quick brown fox jumped over the lazy dog.')
'THQCKBRWNFXJMPDVLZYGEUIOA'
>>> sk.fingerprint('Christopher')
'CHRSTPIOE'
>>> sk.fingerprint('Niall')
| python | {
"resource": ""
} |
q258204 | mean_pairwise_similarity | validation | def mean_pairwise_similarity(
collection, metric=sim, mean_func=hmean, symmetric=False
):
"""Calculate the mean pairwise similarity of a collection of strings.
Takes the mean of the pairwise similarity between each member of a
collection, optionally in both directions (for asymmetric similarity
metrics.
Parameters
----------
collection : list
A collection of terms or a string that can be split
metric : function
A similarity metric function
mean_func : function
A mean function that takes a list of values and returns a float
symmetric : bool
Set to True if all pairwise similarities should be calculated in both
directions
Returns
-------
float
The mean pairwise similarity of a collection of strings
Raises
------
ValueError
mean_func must be a function
ValueError
metric must be a function
ValueError
collection is neither a string nor iterable type
ValueError
collection has fewer than two members
Examples
--------
>>> round(mean_pairwise_similarity(['Christopher', 'Kristof',
... 'Christobal']), 12)
0.519801980198
>>> round(mean_pairwise_similarity(['Niall', 'Neal', 'Neil']), 12)
0.545454545455
"""
if not callable(mean_func):
raise ValueError('mean_func must be a function')
if not callable(metric):
| python | {
"resource": ""
} |
q258205 | pairwise_similarity_statistics | validation | def pairwise_similarity_statistics(
src_collection,
tar_collection,
metric=sim,
mean_func=amean,
symmetric=False,
):
"""Calculate the pairwise similarity statistics a collection of strings.
Calculate pairwise similarities among members of two collections,
returning the maximum, minimum, mean (according to a supplied function,
arithmetic mean, by default), and (population) standard deviation
of those similarities.
Parameters
----------
src_collection : list
A collection of terms or a string that can be split
tar_collection : list
A collection of terms or a string that can be split
metric : function
A similarity metric function
mean_func : function
A mean function that takes a list of values and returns a float
symmetric : bool
Set to True if all pairwise similarities should be calculated in both
directions
Returns
-------
tuple
The max, min, mean, and standard deviation of similarities
Raises
------
ValueError
mean_func must be a function
ValueError
metric must be a function
ValueError
src_collection is neither a string nor iterable
ValueError
tar_collection is neither a string nor iterable
Example
-------
>>> tuple(round(_, 12) for _ in pairwise_similarity_statistics(
... ['Christopher', 'Kristof', 'Christobal'], ['Niall', 'Neal', 'Neil']))
(0.2, 0.0, 0.118614718615, 0.075070477184)
"""
if not callable(mean_func):
raise ValueError('mean_func | python | {
"resource": ""
} |
q258206 | _Snowball._sb_r1 | validation | def _sb_r1(self, term, r1_prefixes=None):
"""Return the R1 region, as defined in the Porter2 specification.
Parameters
----------
term : str
The term to examine
r1_prefixes : set
Prefixes to consider
Returns
-------
int
Length of the R1 region
"""
vowel_found = False
if hasattr(r1_prefixes, '__iter__'):
for prefix in r1_prefixes:
if term[: len(prefix)] == prefix: | python | {
"resource": ""
} |
q258207 | _Snowball._sb_r2 | validation | def _sb_r2(self, term, r1_prefixes=None):
"""Return the R2 region, as defined in the Porter2 specification.
Parameters
----------
term : str
The term to examine | python | {
"resource": ""
} |
q258208 | _Snowball._sb_ends_in_short_syllable | validation | def _sb_ends_in_short_syllable(self, term):
"""Return True iff term ends in a short syllable.
(...according to the Porter2 specification.)
NB: This is akin to the CVC test from the Porter stemmer. The
description is unfortunately poor/ambiguous.
Parameters
----------
term : str
The term to examine
Returns
-------
bool
True iff term ends in a short syllable
"""
if not term:
| python | {
"resource": ""
} |
q258209 | _Snowball._sb_short_word | validation | def _sb_short_word(self, term, r1_prefixes=None):
"""Return True iff term is a short word.
(...according to the Porter2 specification.)
Parameters
----------
term : str
The term to examine
r1_prefixes : set
Prefixes to consider
Returns
-------
bool
True iff term is | python | {
"resource": ""
} |
q258210 | _Snowball._sb_has_vowel | validation | def _sb_has_vowel(self, term):
"""Return Porter helper function _sb_has_vowel value.
Parameters
----------
term : str
The term to examine
| python | {
"resource": ""
} |
q258211 | Eudex.encode | validation | def encode(self, word, max_length=8):
"""Return the eudex phonetic hash of a word.
Parameters
----------
word : str
The word to transform
max_length : int
The length in bits of the code returned (default 8)
Returns
-------
int
The eudex hash
Examples
--------
>>> pe = Eudex()
>>> pe.encode('Colin')
432345564238053650
>>> pe.encode('Christopher')
433648490138894409
>>> pe.encode('Niall')
648518346341351840
>>> pe.encode('Smith')
720575940412906756
>>> pe.encode('Schmidt')
720589151732307997
"""
# Lowercase input & filter unknown characters
word = ''.join(
char for char in word.lower() if char in self._initial_phones
)
if not word:
word = '÷'
# Perform initial eudex coding of each character
values = [self._initial_phones[word[0]]]
values += [self._trailing_phones[char] for char in word[1:]]
# Right-shift by one to determine if second instance should be skipped
shifted_values = [_ | python | {
"resource": ""
} |
q258212 | _TokenDistance._get_qgrams | validation | def _get_qgrams(self, src, tar, qval=0, skip=0):
"""Return the Q-Grams in src & tar.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : int
The length of each q-gram; 0 for non-q-gram version
skip : int
The number of characters to skip (only works when src | python | {
"resource": ""
} |
q258213 | NCDlzma.dist | validation | def dist(self, src, tar):
"""Return the NCD between two strings using LZMA compression.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Compression distance
Raises
------
ValueError
Install the PylibLZMA module in order to use LZMA
Examples
--------
>>> cmp = NCDlzma()
>>> cmp.dist('cat', 'hat')
0.08695652173913043
>>> cmp.dist('Niall', 'Neil')
0.16
>>> cmp.dist('aluminum', 'Catalan')
0.16
>>> cmp.dist('ATCG', 'TAGC')
0.08695652173913043
"""
if src == tar:
return 0.0
src = src.encode('utf-8')
tar = tar.encode('utf-8')
if lzma is not None:
src_comp | python | {
"resource": ""
} |
q258214 | sim_levenshtein | validation | def sim_levenshtein(src, tar, mode='lev', cost=(1, 1, 1, 1)):
"""Return the Levenshtein similarity of two strings.
This is a wrapper of :py:meth:`Levenshtein.sim`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
mode : str
Specifies a mode for computing the Levenshtein distance:
- ``lev`` (default) computes the ordinary Levenshtein distance, in
which edits may include inserts, deletes, and substitutions
- ``osa`` computes the Optimal String Alignment distance, in which
edits may include inserts, deletes, substitutions, and
transpositions but substrings may only be edited once
cost : tuple
| python | {
"resource": ""
} |
q258215 | OmissionKey.fingerprint | validation | def fingerprint(self, word):
"""Return the omission key.
Parameters
----------
word : str
The word to transform into its omission key
Returns
-------
str
The omission key
Examples
--------
>>> ok = OmissionKey()
>>> ok.fingerprint('The quick brown fox jumped over the lazy dog.')
'JKQXZVWYBFMGPDHCLNTREUIOA'
>>> ok.fingerprint('Christopher')
'PHCTSRIOE'
>>> ok.fingerprint('Niall')
'LNIA'
"""
word = unicode_normalize('NFKD', text_type(word.upper()))
word = ''.join(c for c in word if | python | {
"resource": ""
} |
q258216 | sim_minkowski | validation | def sim_minkowski(src, tar, qval=2, pval=1, alphabet=None):
"""Return normalized Minkowski similarity of two strings.
This is a wrapper for :py:meth:`Minkowski.sim`.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : int
The length of each q-gram; 0 for non-q-gram version
pval : int or float
The :math:`p`-value of the :math:`L^p`-space
alphabet : collection or int
The values or size of the alphabet
Returns
-------
float
| python | {
"resource": ""
} |
q258217 | Cosine.sim | validation | def sim(self, src, tar, qval=2):
r"""Return the cosine similarity of two strings.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : int
The length of each q-gram; 0 for non-q-gram version
Returns
-------
float
Cosine similarity
| python | {
"resource": ""
} |
q258218 | dist_monge_elkan | validation | def dist_monge_elkan(src, tar, sim_func=sim_levenshtein, symmetric=False):
"""Return the Monge-Elkan distance between two strings.
This is a wrapper for :py:meth:`MongeElkan.dist`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
sim_func : function
The internal similarity metric to employ
symmetric : bool
Return a symmetric similarity measure
Returns
-------
float
Monge-Elkan distance
Examples
--------
| python | {
"resource": ""
} |
q258219 | Phonem.encode | validation | def encode(self, word):
"""Return the Phonem code for a word.
Parameters
----------
word : str
The word to transform
Returns
-------
str
The Phonem value
Examples
--------
>>> pe = Phonem()
>>> pe.encode('Christopher')
'CRYSDOVR'
>>> pe.encode('Niall')
'NYAL'
>>> pe.encode('Smith')
'SMYD'
>>> pe.encode('Schmidt')
'CMYD'
""" | python | {
"resource": ""
} |
q258220 | CLEFSwedish.stem | validation | def stem(self, word):
"""Return CLEF Swedish stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> clef_swedish('undervisa')
'undervis'
>>> clef_swedish('suspension')
'suspensio'
>>> clef_swedish('visshet')
| python | {
"resource": ""
} |
q258221 | SnowballDutch._undouble | validation | def _undouble(self, word):
"""Undouble endings -kk, -dd, and -tt.
Parameters
----------
word : str
The word to stem
Returns
-------
str
The word with doubled endings undoubled
"""
if (
len(word) > 1
| python | {
"resource": ""
} |
q258222 | String.fingerprint | validation | def fingerprint(self, phrase, joiner=' '):
"""Return string fingerprint.
Parameters
----------
phrase : str
The string from which to calculate the fingerprint
joiner : str
The string that will be placed between each word
Returns
-------
str
The fingerprint of the phrase
Example
-------
>>> sf = String()
>>> sf.fingerprint('The quick brown fox jumped over the lazy dog.')
| python | {
"resource": ""
} |
q258223 | ipa_to_features | validation | def ipa_to_features(ipa):
"""Convert IPA to features.
This translates an IPA string of one or more phones to a list of ints
representing the features of the string.
Parameters
----------
ipa : str
The IPA representation of a phone or series of phones
Returns
-------
list of ints
A representation of the features of the input string
Examples
--------
>>> ipa_to_features('mut')
[2709662981243185770, 1825831513894594986, 2783230754502126250]
>>> ipa_to_features('fon')
[2781702983095331242, 1825831531074464170, 2711173160463936106]
>>> ipa_to_features('telz')
[2783230754502126250, 1826957430176000426, 2693158761954453926,
2783230754501863834]
"""
features = []
pos = 0
ipa = normalize('NFD', text_type(ipa.lower()))
maxsymlen = max(len(_) for _ in _PHONETIC_FEATURES)
while pos < | python | {
"resource": ""
} |
q258224 | get_feature | validation | def get_feature(vector, feature):
"""Get a feature vector.
This returns a list of ints, equal in length to the vector input,
representing presence/absence/neutrality with respect to a particular
phonetic feature.
Parameters
----------
vector : list
A tuple or list of ints representing the phonetic features of a phone
or series of phones (such as is returned by the ipa_to_features
function)
feature : str
A feature name from the set:
- ``consonantal``
- ``sonorant``
- ``syllabic``
- ``labial``
- ``round``
- ``coronal``
- ``anterior``
- ``distributed``
- ``dorsal``
- ``high``
- ``low``
- ``back``
- ``tense``
- ``pharyngeal``
- ``ATR``
- ``voice``
- ``spread_glottis``
- ``constricted_glottis``
- ``continuant``
- ``strident``
- ``lateral``
- ``delayed_release``
- ``nasal``
Returns
-------
list of ints
A list indicating presence/absence/neutrality with respect to the
feature
Raises
------
AttributeError
feature must be one of ...
Examples
--------
>>> tails = ipa_to_features('telz')
>>> get_feature(tails, 'consonantal')
[1, -1, 1, 1]
>>> get_feature(tails, 'sonorant')
[-1, 1, 1, -1]
>>> get_feature(tails, 'nasal')
[-1, -1, -1, -1]
>>> get_feature(tails, 'coronal')
[1, -1, 1, 1]
"""
# :param bool binary: if False, -1, 0, & 1 represent -, 0, & +
# if True, only binary oppositions are allowed:
# 0 & 1 represent - & + and 0s are mapped to -
if feature not in _FEATURE_MASK:
raise AttributeError(
"feature must be one of: '"
+ "', '".join(
(
'consonantal',
'sonorant',
'syllabic',
| python | {
"resource": ""
} |
q258225 | cmp_features | validation | def cmp_features(feat1, feat2):
"""Compare features.
This returns a number in the range [0, 1] representing a comparison of two
feature bundles.
If one of the bundles is negative, -1 is returned (for unknown values)
If the bundles are identical, 1 is returned.
If they are inverses of one another, 0 is returned.
Otherwise, a float representing their similarity is returned.
Parameters
----------
feat1 : int
A feature bundle
feat2 : int
A feature bundle
Returns
-------
| python | {
"resource": ""
} |
q258226 | Length.sim | validation | def sim(self, src, tar):
"""Return the length similarity of two strings.
Length similarity is the ratio of the length of the shorter string to
the longer.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Length similarity
Examples
--------
>>> cmp = Length()
>>> cmp.sim('cat', 'hat')
| python | {
"resource": ""
} |
q258227 | hmean | validation | def hmean(nums):
r"""Return harmonic mean.
The harmonic mean is defined as:
:math:`\frac{|nums|}{\sum\limits_{i}\frac{1}{nums_i}}`
Following the behavior of Wolfram|Alpha:
- If one of the values in nums is 0, return 0.
- If more than one value in nums is 0, return NaN.
Cf. https://en.wikipedia.org/wiki/Harmonic_mean
Parameters
----------
nums : list
A series of numbers
Returns
-------
float
The harmonic mean of nums
Raises
------
AttributeError
hmean requires at least one value
Examples
--------
>>> hmean([1, 2, 3, 4])
1.9200000000000004
>>> hmean([1, 2])
1.3333333333333333
| python | {
"resource": ""
} |
q258228 | lmean | validation | def lmean(nums):
r"""Return logarithmic mean.
The logarithmic mean of an arbitrarily long series is defined by
http://www.survo.fi/papers/logmean.pdf
as:
:math:`L(x_1, x_2, ..., x_n) =
(n-1)! \sum\limits_{i=1}^n \frac{x_i}
{\prod\limits_{\substack{j = 1\\j \ne i}}^n
ln \frac{x_i}{x_j}}`
Cf. https://en.wikipedia.org/wiki/Logarithmic_mean
Parameters
----------
nums : list
A series of numbers
Returns
-------
float
The logarithmic mean of nums
Raises
------
AttributeError
No two values in the nums list may be equal
Examples
--------
>>> | python | {
"resource": ""
} |
q258229 | seiffert_mean | validation | def seiffert_mean(nums):
r"""Return Seiffert's mean.
Seiffert's mean of two numbers x and y is:
:math:`\frac{x - y}{4 \cdot arctan \sqrt{\frac{x}{y}} - \pi}`
It is defined in :cite:`Seiffert:1993`.
Parameters
----------
nums : list
A series of numbers
Returns
-------
float
Sieffert's mean of nums
Raises
------
AttributeError
seiffert_mean supports no more than two values
Examples
--------
>>> seiffert_mean([1, 2])
1.4712939827611637
>>> seiffert_mean([1, 0])
0.3183098861837907
>>> seiffert_mean([2, 4])
2.9425879655223275
>>> seiffert_mean([2, 1000])
336.84053300118825
"""
| python | {
"resource": ""
} |
q258230 | lehmer_mean | validation | def lehmer_mean(nums, exp=2):
r"""Return Lehmer mean.
The Lehmer mean is:
:math:`\frac{\sum\limits_i{x_i^p}}{\sum\limits_i{x_i^(p-1)}}`
Cf. https://en.wikipedia.org/wiki/Lehmer_mean
Parameters
----------
nums : list
A series of numbers
| python | {
"resource": ""
} |
q258231 | heronian_mean | validation | def heronian_mean(nums):
r"""Return Heronian mean.
The Heronian mean is:
:math:`\frac{\sum\limits_{i, j}\sqrt{{x_i \cdot x_j}}}
{|nums| \cdot \frac{|nums| + 1}{2}}`
for :math:`j \ge i`
Cf. https://en.wikipedia.org/wiki/Heronian_mean
Parameters
----------
nums : list
A series of numbers
Returns
-------
float
The Heronian mean of nums
Examples
--------
>>> heronian_mean([1, 2, 3, 4])
2.3888282852609093
>>> heronian_mean([1, 2])
1.4714045207910316
>>> heronian_mean([0, 5, 1000])
179.28511301977582
"""
| python | {
"resource": ""
} |
q258232 | agmean | validation | def agmean(nums):
"""Return arithmetic-geometric mean.
Iterates between arithmetic & geometric means until they converge to
a single value (rounded to 12 digits).
Cf. https://en.wikipedia.org/wiki/Arithmetic-geometric_mean
Parameters
----------
nums : list
A series of numbers
Returns
| python | {
"resource": ""
} |
q258233 | ghmean | validation | def ghmean(nums):
"""Return geometric-harmonic mean.
Iterates between geometric & harmonic means until they converge to
a single value (rounded to 12 digits).
Cf. https://en.wikipedia.org/wiki/Geometric-harmonic_mean
Parameters
----------
nums : list
A series of numbers
Returns
-------
float
The geometric-harmonic mean of nums
Examples
--------
>>> ghmean([1, 2, 3, 4])
2.058868154613003
>>> ghmean([1, 2])
1.3728805006183502
>>> ghmean([0, 5, 1000])
0.0
>>> ghmean([0, 0])
0.0
| python | {
"resource": ""
} |
q258234 | aghmean | validation | def aghmean(nums):
"""Return arithmetic-geometric-harmonic mean.
Iterates over arithmetic, geometric, & harmonic means until they
converge to a single value (rounded to 12 digits), following the
method described in :cite:`Raissouli:2009`.
Parameters
----------
nums : list
A series of numbers
Returns
-------
float
The arithmetic-geometric-harmonic mean of nums
Examples
--------
>>> aghmean([1, 2, 3, 4])
2.198327159900212
>>> aghmean([1, 2])
1.4142135623731884
>>> aghmean([0, 5, 1000])
335.0
"""
m_a = amean(nums)
m_g = gmean(nums)
| python | {
"resource": ""
} |
q258235 | median | validation | def median(nums):
"""Return median.
With numbers sorted by value, the median is the middle value (if there is
an odd number of values) or the arithmetic mean of the two middle values
(if there is an even number of values).
Cf. https://en.wikipedia.org/wiki/Median
Parameters
----------
nums : list
A series of numbers
Returns
-------
int or float
The median of nums
Examples
--------
>>> median([1, 2, 3])
2
>>> | python | {
"resource": ""
} |
q258236 | var | validation | def var(nums, mean_func=amean, ddof=0):
r"""Calculate the variance.
The variance (:math:`\sigma^2`) of a series of numbers (:math:`x_i`) with
mean :math:`\mu` and population :math:`N` is:
:math:`\sigma^2 = \frac{1}{N}\sum_{i=1}^{N}(x_i-\mu)^2`.
Cf. https://en.wikipedia.org/wiki/Variance
Parameters
----------
nums : list
A series of numbers
mean_func : function
A mean function (amean by default)
ddof : int
The degrees of freedom (0 by default)
Returns
-------
| python | {
"resource": ""
} |
q258237 | Schinke.stem | validation | def stem(self, word):
"""Return the stem of a word according to the Schinke stemmer.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = Schinke()
>>> stmr.stem('atque')
{'n': 'atque', 'v': 'atque'}
>>> stmr.stem('census')
{'n': 'cens', 'v': 'censu'}
>>> stmr.stem('virum')
{'n': 'uir', 'v': 'uiru'}
>>> stmr.stem('populusque')
{'n': 'popul', 'v': 'populu'}
>>> stmr.stem('senatus')
{'n': 'senat', 'v': 'senatu'}
"""
word = normalize('NFKD', text_type(word.lower()))
word = ''.join(
c
for c in word
if c
in {
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z',
}
)
# Rule 2
word = word.replace('j', 'i').replace('v', 'u')
# Rule 3
if word[-3:] == 'que':
# This diverges from the paper by also returning 'que' itself
# unstemmed
if word[:-3] in self._keep_que or word == 'que':
return {'n': word, 'v': word}
else:
word = word[:-3]
# Base case will mean returning the words as is
noun = word
verb = word
# Rule 4
for endlen in range(4, 0, -1):
if word[-endlen:] in self._n_endings[endlen]:
| python | {
"resource": ""
} |
q258238 | sim_editex | validation | def sim_editex(src, tar, cost=(0, 1, 2), local=False):
"""Return the normalized Editex similarity of two strings.
This is a wrapper for :py:meth:`Editex.sim`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
cost : tuple
A 3-tuple representing the cost of the four possible edits: match,
same-group, and mismatch respectively (by default: (0, 1, 2))
local : bool
If True, the local variant of Editex is used
Returns
-------
int
Normalized Editex similarity | python | {
"resource": ""
} |
q258239 | NCDarith.dist | validation | def dist(self, src, tar, probs=None):
"""Return the NCD between two strings using arithmetic coding.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
probs : dict
A dictionary trained with :py:meth:`Arithmetic.train`
Returns
-------
float
Compression distance
Examples
--------
>>> cmp = NCDarith()
>>> cmp.dist('cat', 'hat')
0.5454545454545454
>>> cmp.dist('Niall', 'Neil')
0.6875
>>> cmp.dist('aluminum', 'Catalan')
0.8275862068965517
>>> cmp.dist('ATCG', 'TAGC')
0.6923076923076923
"""
if src == tar:
return 0.0
if probs is None:
# lacking a reasonable dictionary, train on the strings themselves
| python | {
"resource": ""
} |
q258240 | readfile | validation | def readfile(fn):
"""Read fn and return the contents.
Parameters
----------
fn : str
A filename
Returns
-------
str
The content of the file
"""
| python | {
"resource": ""
} |
q258241 | FONEM.encode | validation | def encode(self, word):
"""Return the FONEM code of a word.
Parameters
----------
word : str
The word to transform
Returns
-------
str
The FONEM code
Examples
--------
>>> pe = FONEM()
>>> pe.encode('Marchand')
'MARCHEN'
>>> pe.encode('Beaulieu')
'BOLIEU'
>>> pe.encode('Beaumont')
'BOMON'
>>> pe.encode('Legrand')
'LEGREN'
>>> pe.encode('Pelletier')
'PELETIER'
"""
# normalize, upper-case, and filter non-French letters
| python | {
"resource": ""
} |
q258242 | Synoname._synoname_strip_punct | validation | def _synoname_strip_punct(self, word):
"""Return a word with punctuation stripped out.
Parameters
----------
word : str
A word to strip punctuation from
Returns
-------
str
| python | {
"resource": ""
} |
q258243 | Synoname.dist | validation | def dist(
self,
src,
tar,
word_approx_min=0.3,
char_approx_min=0.73,
tests=2 ** 12 - 1,
):
"""Return the normalized Synoname distance between two words.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
word_approx_min : float
The minimum word approximation value to signal a 'word_approx'
match
char_approx_min : float
The minimum character approximation value to signal a 'char_approx'
match
| python | {
"resource": ""
} |
q258244 | Jaccard.sim | validation | def sim(self, src, tar, qval=2):
r"""Return the Jaccard similarity of two strings.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : int
The length of each q-gram; 0 for non-q-gram version
Returns
-------
float
Jaccard similarity
Examples
--------
| python | {
"resource": ""
} |
q258245 | Jaccard.tanimoto_coeff | validation | def tanimoto_coeff(self, src, tar, qval=2):
"""Return the Tanimoto distance between two strings.
Tanimoto distance :cite:`Tanimoto:1958` is
:math:`-log_{2} sim_{Tanimoto}(X, Y)`.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : int
| python | {
"resource": ""
} |
q258246 | sim_sift4 | validation | def sim_sift4(src, tar, max_offset=5, max_distance=0):
"""Return the normalized "common" Sift4 similarity of two terms.
This is a wrapper for :py:meth:`Sift4.sim`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
max_offset : int
The number of characters to search for matching letters
max_distance : int
The distance at which to stop and exit
Returns
-------
float
The normalized Sift4 similarity
Examples
| python | {
"resource": ""
} |
q258247 | NCDbz2.dist | validation | def dist(self, src, tar):
"""Return the NCD between two strings using bzip2 compression.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Compression distance
Examples
--------
>>> cmp = NCDbz2()
>>> cmp.dist('cat', 'hat')
0.06666666666666667
>>> cmp.dist('Niall', 'Neil')
0.03125
>>> cmp.dist('aluminum', 'Catalan')
0.17647058823529413
>>> cmp.dist('ATCG', 'TAGC')
0.03125
"""
if src == tar: | python | {
"resource": ""
} |
q258248 | MetaSoundex.encode | validation | def encode(self, word, lang='en'):
"""Return the MetaSoundex code for a word.
Parameters
----------
word : str
The word to transform
lang : str
Either ``en`` for English or ``es`` for Spanish
Returns
-------
str
The MetaSoundex code
Examples
--------
>>> pe = MetaSoundex()
>>> pe.encode('Smith')
'4500'
>>> pe.encode('Waters')
'7362'
| python | {
"resource": ""
} |
q258249 | SStemmer.stem | validation | def stem(self, word):
"""Return the S-stemmed form of a word.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = SStemmer()
>>> stmr.stem('summaries')
'summary'
>>> stmr.stem('summary')
'summary'
>>> stmr.stem('towers')
'tower'
>>> stmr.stem('reading')
'reading'
>>> stmr.stem('census')
'census'
"""
| python | {
"resource": ""
} |
q258250 | RatcliffObershelp.sim | validation | def sim(self, src, tar):
"""Return the Ratcliff-Obershelp similarity of two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Ratcliff-Obershelp similarity
Examples
--------
>>> cmp = RatcliffObershelp()
>>> round(cmp.sim('cat', 'hat'), 12)
0.666666666667
>>> round(cmp.sim('Niall', 'Neil'), 12)
0.666666666667
>>> round(cmp.sim('aluminum', 'Catalan'), 12)
0.4
>>> cmp.sim('ATCG', 'TAGC')
0.5
"""
def _lcsstr_stl(src, tar):
"""Return start positions & length for Ratcliff-Obershelp.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
tuple
The start position in the source string, start position in the
target string, and length of the longest common substring of
strings src and tar.
"""
lengths = np_zeros((len(src) + 1, len(tar) + 1), dtype=np_int)
longest, src_longest, tar_longest = 0, 0, 0
for i in range(1, len(src) + 1):
for j in range(1, len(tar) + 1):
if src[i - 1] == tar[j - 1]:
lengths[i, j] = lengths[i - 1, j - 1] + 1
if lengths[i, j] > longest:
longest = lengths[i, j]
src_longest = i
tar_longest = j
else:
lengths[i, j] = 0
| python | {
"resource": ""
} |
q258251 | MRA.dist_abs | validation | def dist_abs(self, src, tar):
"""Return the MRA comparison rating of two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
int
MRA comparison rating
Examples
--------
>>> cmp = MRA()
>>> cmp.dist_abs('cat', 'hat')
5
>>> cmp.dist_abs('Niall', 'Neil')
6
>>> cmp.dist_abs('aluminum', 'Catalan')
0
>>> cmp.dist_abs('ATCG', 'TAGC')
5
"""
if src == tar:
return 6
if src == '' or tar == '':
return 0
src = list(mra(src))
tar = list(mra(tar))
if abs(len(src) - len(tar)) > 2:
return 0
length_sum = len(src) + len(tar)
if length_sum < 5:
min_rating = 5
elif length_sum < 8:
| python | {
"resource": ""
} |
q258252 | ParmarKumbharana.encode | validation | def encode(self, word):
"""Return the Parmar-Kumbharana encoding of a word.
Parameters
----------
word : str
The word to transform
Returns
-------
str
The Parmar-Kumbharana encoding
Examples
--------
>>> pe = ParmarKumbharana()
>>> pe.encode('Gough')
'GF'
>>> pe.encode('pneuma')
'NM'
>>> pe.encode('knight')
'NT'
>>> pe.encode('trice')
'TRS'
>>> pe.encode('judge')
'JJ'
"""
word = word.upper() # Rule 3
word = self._delete_consecutive_repeats(word) # Rule 4
# Rule 5
i = 0
while i < len(word):
for match_len in range(4, 1, -1):
if word[i : i + | python | {
"resource": ""
} |
q258253 | eudex_hamming | validation | def eudex_hamming(
src, tar, weights='exponential', max_length=8, normalized=False
):
"""Calculate the Hamming distance between the Eudex hashes of two terms.
This is a wrapper for :py:meth:`Eudex.eudex_hamming`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
weights : str, iterable, or generator function
The weights or weights generator function
max_length : int
The number of characters to encode as a eudex hash
normalized : bool
Normalizes to [0, 1] if True
Returns
-------
int
The Eudex Hamming distance
Examples
--------
>>> eudex_hamming('cat', 'hat')
128
>>> eudex_hamming('Niall', 'Neil')
2
>>> eudex_hamming('Colin', 'Cuilen')
10
>>> eudex_hamming('ATCG', 'TAGC')
403
>>> eudex_hamming('cat', 'hat', weights='fibonacci')
34
>>> eudex_hamming('Niall', 'Neil', weights='fibonacci')
2
>>> | python | {
"resource": ""
} |
q258254 | dist_eudex | validation | def dist_eudex(src, tar, weights='exponential', max_length=8):
"""Return normalized Hamming distance between Eudex hashes of two terms.
This is a wrapper for :py:meth:`Eudex.dist`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
weights : str, iterable, or generator function
The weights or weights generator function
max_length : int
The number of characters to encode as a eudex hash
Returns
-------
int
The normalized Eudex Hamming distance
Examples | python | {
"resource": ""
} |
q258255 | sim_eudex | validation | def sim_eudex(src, tar, weights='exponential', max_length=8):
"""Return normalized Hamming similarity between Eudex hashes of two terms.
This is a wrapper for :py:meth:`Eudex.sim`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
weights : str, iterable, or generator function
The weights or weights generator function
max_length : int
The number of characters to encode as a eudex hash
Returns
-------
int
The normalized Eudex Hamming similarity
| python | {
"resource": ""
} |
q258256 | Eudex.gen_fibonacci | validation | def gen_fibonacci():
"""Yield the next Fibonacci number.
Based on https://www.python-course.eu/generators.php
Starts at Fibonacci number 3 (the second 1)
Yields
------
int
| python | {
"resource": ""
} |
q258257 | Eudex.dist_abs | validation | def dist_abs(
self, src, tar, weights='exponential', max_length=8, normalized=False
):
"""Calculate the distance between the Eudex hashes of two terms.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
weights : str, iterable, or generator function
The weights or weights generator function
- If set to ``None``, a simple Hamming distance is calculated.
- If set to ``exponential``, weight decays by powers of 2, as
proposed in the eudex specification:
https://github.com/ticki/eudex.
- If set to ``fibonacci``, weight decays through the Fibonacci
series, as in the eudex reference implementation.
- If set to a callable function, this assumes it creates a
generator and the generator is used to populate a series of
weights.
- If set to an iterable, the iterable's values should be
integers and will be used as the weights.
max_length : int
The number of characters to encode as a eudex hash
normalized : bool
Normalizes to [0, 1] if True
Returns
-------
int
The Eudex Hamming distance
Examples
--------
>>> cmp = Eudex()
>>> cmp.dist_abs('cat', 'hat')
128
>>> cmp.dist_abs('Niall', 'Neil')
2
>>> cmp.dist_abs('Colin', 'Cuilen')
10
>>> cmp.dist_abs('ATCG', 'TAGC')
403
>>> cmp.dist_abs('cat', 'hat', weights='fibonacci')
34
>>> cmp.dist_abs('Niall', 'Neil', weights='fibonacci')
2
>>> cmp.dist_abs('Colin', 'Cuilen', weights='fibonacci')
7
>>> cmp.dist_abs('ATCG', 'TAGC', weights='fibonacci')
117
>>> cmp.dist_abs('cat', 'hat', weights=None)
1
>>> cmp.dist_abs('Niall', 'Neil', weights=None)
1
>>> cmp.dist_abs('Colin', 'Cuilen', weights=None)
2
>>> cmp.dist_abs('ATCG', 'TAGC', weights=None)
9
>>> # Using the OEIS A000142:
>>> cmp.dist_abs('cat', 'hat', [1, 1, 2, 6, 24, 120, 720, 5040])
1
>>> cmp.dist_abs('Niall', 'Neil', [1, 1, 2, 6, 24, 120, 720, 5040])
720
| python | {
"resource": ""
} |
q258258 | Eudex.dist | validation | def dist(self, src, tar, weights='exponential', max_length=8):
"""Return normalized distance between the Eudex hashes of two terms.
This is Eudex distance normalized to [0, 1].
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
weights : str, iterable, or generator function
The weights or weights generator function
max_length : int
The number of characters to encode as a eudex hash
Returns
-------
int
| python | {
"resource": ""
} |
q258259 | euclidean | validation | def euclidean(src, tar, qval=2, normalized=False, alphabet=None):
"""Return the Euclidean distance between two strings.
This is a wrapper for :py:meth:`Euclidean.dist_abs`.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : int
The length of each q-gram; 0 for non-q-gram version
normalized : bool
Normalizes to [0, 1] if True
alphabet : collection or int
The values or size of the alphabet
Returns
------- | python | {
"resource": ""
} |
q258260 | dist_euclidean | validation | def dist_euclidean(src, tar, qval=2, alphabet=None):
"""Return the normalized Euclidean distance between two strings.
This is a wrapper for :py:meth:`Euclidean.dist`.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : int
The length of each q-gram; 0 for non-q-gram version
alphabet : collection or int
The values or size of the alphabet
Returns
-------
float
The normalized Euclidean distance
| python | {
"resource": ""
} |
q258261 | sim_euclidean | validation | def sim_euclidean(src, tar, qval=2, alphabet=None):
"""Return the normalized Euclidean similarity of two strings.
This is a wrapper for :py:meth:`Euclidean.sim`.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : int
The length of each q-gram; 0 for non-q-gram version
alphabet : collection or int
The values or size of the alphabet
Returns
-------
float
The normalized Euclidean similarity
| python | {
"resource": ""
} |
q258262 | Lovins._cond_k | validation | def _cond_k(self, word, suffix_len):
"""Return Lovins' condition K.
Parameters
----------
word : str
Word to check
suffix_len : int
Suffix length
| python | {
"resource": ""
} |
q258263 | Lovins._cond_n | validation | def _cond_n(self, word, suffix_len):
"""Return Lovins' condition N.
Parameters
----------
word : str
Word to check
suffix_len : int
Suffix length
Returns
-------
bool
True if condition is met
"""
if len(word) - suffix_len >= 3:
| python | {
"resource": ""
} |
q258264 | Lovins._cond_s | validation | def _cond_s(self, word, suffix_len):
"""Return Lovins' condition S.
Parameters
----------
word : str
Word to check
suffix_len : int
| python | {
"resource": ""
} |
q258265 | Lovins._cond_x | validation | def _cond_x(self, word, suffix_len):
"""Return Lovins' condition X.
Parameters
----------
word : str
Word to check
suffix_len : int
Suffix length
Returns
-------
bool
True if condition is met
"""
| python | {
"resource": ""
} |
q258266 | Lovins._cond_bb | validation | def _cond_bb(self, word, suffix_len):
"""Return Lovins' condition BB.
Parameters
----------
word : str
Word to check
suffix_len : int
Suffix length
Returns
-------
bool
True if condition is met
"""
return (
| python | {
"resource": ""
} |
q258267 | Lovins.stem | validation | def stem(self, word):
"""Return Lovins stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = Lovins()
>>> stmr.stem('reading')
'read'
>>> stmr.stem('suspension')
'suspens'
>>> stmr.stem('elusiveness')
'elus'
"""
# lowercase, normalize, and compose
word = normalize('NFC', text_type(word.lower()))
for suffix_len in range(11, 0, -1):
ending = word[-suffix_len:]
if (
ending in self._suffix
and len(word) - suffix_len >= 2
and (
self._suffix[ending] is None
or self._suffix[ending](word, suffix_len)
)
| python | {
"resource": ""
} |
q258268 | NCDzlib.dist | validation | def dist(self, src, tar):
"""Return the NCD between two strings using zlib compression.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Compression distance
Examples
--------
>>> cmp = NCDzlib()
>>> cmp.dist('cat', 'hat')
0.3333333333333333
>>> cmp.dist('Niall', 'Neil')
0.45454545454545453
>>> cmp.dist('aluminum', 'Catalan')
| python | {
"resource": ""
} |
q258269 | pylint_color | validation | def pylint_color(score):
"""Return Pylint badge color.
Parameters
----------
score : float
A Pylint score
Returns
-------
str
Badge color
"""
# These are the score cutoffs for each color above.
# I.e. score==10 -> brightgreen, down to 7.5 > score >= 5 -> orange
score_cutoffs = (10, 9.5, 8.5, 7.5, 5)
| python | {
"resource": ""
} |
q258270 | pydocstyle_color | validation | def pydocstyle_color(score):
"""Return pydocstyle badge color.
Parameters
----------
score : float
A pydocstyle score
Returns
-------
str
Badge color
"""
# These are the score cutoffs for each color above.
# I.e. score==0 -> brightgreen, down to 100 < score <= 200 -> orange
score_cutoffs = (0, 10, 25, 50, 100) | python | {
"resource": ""
} |
q258271 | flake8_color | validation | def flake8_color(score):
"""Return flake8 badge color.
Parameters
----------
score : float
A flake8 score
Returns
-------
str
Badge color
"""
# These are the score cutoffs for each color above.
# I.e. score==0 -> brightgreen, down to 100 < score <= 200 -> orange
score_cutoffs = (0, 20, 50, 100, 200)
| python | {
"resource": ""
} |
q258272 | Bag.dist_abs | validation | def dist_abs(self, src, tar):
"""Return the bag distance between two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
int
Bag distance
Examples
--------
>>> cmp = Bag()
>>> cmp.dist_abs('cat', 'hat')
1
>>> cmp.dist_abs('Niall', 'Neil')
2
>>> cmp.dist_abs('aluminum', 'Catalan')
5
>>> cmp.dist_abs('ATCG', 'TAGC')
0
>>> | python | {
"resource": ""
} |
q258273 | Bag.dist | validation | def dist(self, src, tar):
"""Return the normalized bag distance between two strings.
Bag distance is normalized by dividing by :math:`max( |src|, |tar| )`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Normalized bag distance
Examples
--------
>>> cmp = Bag()
>>> cmp.dist('cat', 'hat')
| python | {
"resource": ""
} |
q258274 | CLEFGermanPlus.stem | validation | def stem(self, word):
"""Return 'CLEF German stemmer plus' stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = CLEFGermanPlus()
>>> clef_german_plus('lesen')
'les'
>>> clef_german_plus('graues')
'grau'
>>> clef_german_plus('buchstabieren')
'buchstabi'
"""
# lowercase, normalize, and compose
word = normalize('NFC', text_type(word.lower()))
# remove umlauts
word = word.translate(self._accents)
# Step 1
wlen = len(word) - 1
if wlen > 4 and word[-3:] == 'ern':
word = word[:-3]
elif wlen > 3 and word[-2:] in {'em', 'en', 'er', 'es'}:
word = word[:-2]
elif wlen > 2 and (
word[-1] == 'e'
| python | {
"resource": ""
} |
q258275 | dist_mlipns | validation | def dist_mlipns(src, tar, threshold=0.25, max_mismatches=2):
"""Return the MLIPNS distance between two strings.
This is a wrapper for :py:meth:`MLIPNS.dist`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
threshold : float
A number [0, 1] indicating the maximum similarity score, below which
the strings are considered 'similar' (0.25 by default)
max_mismatches : int
A number indicating the allowable number of mismatches to remove before
declaring two strings not similar (2 by default)
Returns
-------
| python | {
"resource": ""
} |
q258276 | sim | validation | def sim(src, tar, method=sim_levenshtein):
"""Return a similarity of two strings.
This is a generalized function for calling other similarity functions.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
method : function
Specifies the similarity metric (:py:func:`sim_levenshtein` by default)
Returns
-------
float
Similarity according to the specified function
Raises
------
AttributeError
Unknown distance function
Examples
--------
| python | {
"resource": ""
} |
q258277 | dist | validation | def dist(src, tar, method=sim_levenshtein):
"""Return a distance between two strings.
This is a generalized function for calling other distance functions.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
method : function
Specifies the similarity metric (:py:func:`sim_levenshtein` by default)
-- Note that this takes a similarity metric function, not a distance
metric function.
Returns
-------
float
Distance according to the specified function
Raises
------
AttributeError
| python | {
"resource": ""
} |
q258278 | Porter._m_degree | validation | def _m_degree(self, term):
"""Return Porter helper function _m_degree value.
m-degree is equal to the number of V to C transitions
Parameters
----------
term : str
The word for which to calculate the m-degree
Returns
-------
int
The m-degree as defined in the Porter stemmer definition
"""
mdeg = 0
last_was_vowel = False
| python | {
"resource": ""
} |
q258279 | Porter._has_vowel | validation | def _has_vowel(self, term):
"""Return Porter helper function _has_vowel value.
Parameters
----------
term : str
The word to scan for vowels
| python | {
"resource": ""
} |
q258280 | Porter._ends_in_doubled_cons | validation | def _ends_in_doubled_cons(self, term):
"""Return Porter helper function _ends_in_doubled_cons value.
Parameters
----------
term : str
The word to check for a final doubled consonant
| python | {
"resource": ""
} |
q258281 | Porter._ends_in_cvc | validation | def _ends_in_cvc(self, term):
"""Return Porter helper function _ends_in_cvc value.
Parameters
----------
term : str
The word to scan for cvc
Returns
-------
bool
True iff the stem ends in cvc (as defined in the Porter stemmer
definition)
"""
return len(term) > 2 and (
| python | {
"resource": ""
} |
q258282 | filter_symlog | validation | def filter_symlog(y, base=10.0):
"""Symmetrical logarithmic scale.
Optional arguments:
*base*:
The base of the logarithm.
""" | python | {
"resource": ""
} |
q258283 | usage_function | validation | def usage_function(parser):
"""Show usage and available curve functions."""
parser.print_usage()
print('')
print('available functions:')
for function in sorted(FUNCTION):
doc | python | {
"resource": ""
} |
q258284 | usage_palette | validation | def usage_palette(parser):
"""Show usage and available palettes."""
parser.print_usage()
print('')
print('available palettes:')
for palette in | python | {
"resource": ""
} |
q258285 | Terminal.size | validation | def size(self):
"""Get the current terminal size."""
for fd in range(3):
cr = self._ioctl_GWINSZ(fd)
if cr:
break
if not cr:
try:
| python | {
"resource": ""
} |
q258286 | Terminal.color | validation | def color(self, index):
"""Get the escape sequence for indexed color ``index``.
The ``index`` is a color index in the 256 color space. The color space
consists of:
* 0x00-0x0f: default EGA colors
* 0x10-0xe7: 6x6x6 RGB cubes
* 0xe8-0xff: gray scale ramp
"""
if self.colors == 16:
if index >= 8:
| python | {
"resource": ""
} |
q258287 | Terminal.csi | validation | def csi(self, capname, *args):
"""Return the escape sequence for the selected Control Sequence."""
value = curses.tigetstr(capname)
| python | {
"resource": ""
} |
q258288 | Terminal.csi_wrap | validation | def csi_wrap(self, value, capname, *args):
"""Return a value wrapped in the selected CSI and does a reset."""
if isinstance(value, str):
value = value.encode('utf-8')
| python | {
"resource": ""
} |
q258289 | Graph.consume | validation | def consume(self, istream, ostream, batch=False):
"""Read points from istream and output to ostream."""
datapoints = [] # List of 2-tuples
if batch:
sleep = max(0.01, self.option.sleep)
fd = istream.fileno()
while True:
try:
if select.select([fd], [], [], sleep):
try:
line = istream.readline()
if line == '':
break
datapoints.append(self.consume_line(line))
except ValueError:
continue
if self.option.sort_by_column:
datapoints = sorted(datapoints, key=itemgetter(self.option.sort_by_column - 1))
if len(datapoints) > 1:
datapoints = datapoints[-self.maximum_points:]
| python | {
"resource": ""
} |
q258290 | Graph.consume_line | validation | def consume_line(self, line):
"""Consume data from a line."""
data = RE_VALUE_KEY.split(line.strip(), 1)
if len(data) == 1:
| python | {
"resource": ""
} |
q258291 | Graph.update | validation | def update(self, points, values=None):
"""Add a set of data points."""
self.values = values or [None] * len(points)
if np is None:
if self.option.function:
warnings.warn('numpy not available, function ignored')
self.points = points
self.minimum = min(self.points)
self.maximum = max(self.points)
self.current = self.points[-1]
else:
self.points = self.apply_function(points)
self.minimum = np.min(self.points)
| python | {
"resource": ""
} |
q258292 | Graph.color_ramp | validation | def color_ramp(self, size):
"""Generate a color ramp for the current screen height."""
color = PALETTE.get(self.option.palette, {})
color = color.get(self.term.colors, None)
color_ramp = []
if color is not None:
| python | {
"resource": ""
} |
q258293 | Graph.human | validation | def human(self, size, base=1000, units=' kMGTZ'):
"""Convert the input ``size`` to human readable, short form."""
sign = '+' if size >= 0 else '-'
size = abs(size)
if size < 1000:
return '%s%d' | python | {
"resource": ""
} |
q258294 | Graph.apply_function | validation | def apply_function(self, points):
"""Run the filter function on the provided points."""
if not self.option.function:
return points
if np is None:
raise ImportError('numpy is not available')
if ':' in self.option.function:
function, arguments = self.option.function.split(':', 1)
arguments = arguments.split(',')
else:
function = self.option.function
arguments = []
# Resolve arguments
arguments = list(map(self._function_argument, arguments))
# | python | {
"resource": ""
} |
q258295 | Graph.line | validation | def line(self, p1, p2, resolution=1):
"""Resolve the points to make a line between two points."""
xdiff = max(p1.x, p2.x) - min(p1.x, p2.x)
ydiff = max(p1.y, p2.y) - min(p1.y, p2.y)
xdir = [-1, 1][int(p1.x <= p2.x)]
ydir = [-1, 1][int(p1.y <= p2.y)]
r = int(round(max(xdiff, ydiff)))
if r == 0:
return
for i in range((r + 1) * resolution):
x = p1.x
| python | {
"resource": ""
} |
q258296 | Graph.set_text | validation | def set_text(self, point, text):
"""Set a text value in the screen canvas."""
if not self.option.legend:
return
if not isinstance(point, Point):
point = Point(point)
| python | {
"resource": ""
} |
q258297 | AxisGraph.render | validation | def render(self, stream):
"""Render graph to stream."""
encoding = self.option.encoding or self.term.encoding or "utf8"
if self.option.color:
ramp = self.color_ramp(self.size.y)[::-1]
else:
ramp = None
if self.cycle >= 1 and self.lines:
stream.write(self.term.csi('cuu', self.lines))
zero = int(self.null / 4) # Zero crossing
lines = 0
for y in range(self.screen.size.y):
if y == zero and self.size.y > 1:
stream.write(self.term.csi('smul'))
if ramp:
stream.write(ramp[y])
for x in range(self.screen.size.x):
point = Point((x, y))
| python | {
"resource": ""
} |
q258298 | AxisGraph._normalised_numpy | validation | def _normalised_numpy(self):
"""Normalised data points using numpy."""
dx = (self.screen.width / float(len(self.points)))
oy = (self.screen.height)
points = np.array(self.points) - self.minimum
points = points * 4.0 / self.extents * self.size.y
| python | {
"resource": ""
} |
q258299 | AxisGraph._normalised_python | validation | def _normalised_python(self):
"""Normalised data points using pure Python."""
dx = (self.screen.width / float(len(self.points)))
oy = (self.screen.height)
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.