_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q258100 | BaseWindow.clear_values | validation | def clear_values(self, red=0.0, green=0.0, blue=0.0, alpha=0.0, depth=1.0):
"""
Sets the clear values for the window buffer.
Args:
red (float): red compoent
green (float): green compoent
blue (float): blue compoent
alpha (float): alpha compoent
... | python | {
"resource": ""
} |
q258101 | BaseWindow.keyboard_event | validation | def keyboard_event(self, key, action, modifier):
"""
Handles the standard keyboard events such as camera movements,
taking a screenshot, closing the window etc.
Can be overriden add new keyboard events. Ensure this method
is also called if you want to keep the standard features.... | python | {
"resource": ""
} |
q258102 | BaseWindow.cursor_event | validation | def cursor_event(self, x, y, dx, dy):
"""
The standard mouse movement event method.
Can be overriden to add new functionality.
By default this feeds the system camera with new values.
Args:
x: The current mouse x position
y: The current mouse y position
... | python | {
"resource": ""
} |
q258103 | BaseWindow.set_default_viewport | validation | def set_default_viewport(self):
"""
Calculates the viewport based on the configured aspect ratio in settings.
Will add black borders if the window do not match the viewport.
"""
# The expected height with the current viewport width
expected_height = int(self.buffer_width ... | python | {
"resource": ""
} |
q258104 | Timer.start | validation | def start(self):
"""Start the timer"""
self.music.start()
if not self.start_paused:
self.rocket.start() | python | {
"resource": ""
} |
q258105 | Timer.toggle_pause | validation | def toggle_pause(self):
"""Toggle pause mode"""
self.controller.playing = not self.controller.playing
self.music.toggle_pause() | python | {
"resource": ""
} |
q258106 | SceneLoader.supports_file | validation | def supports_file(cls, meta):
"""Check if the loader has a supported file extension"""
path = Path(meta.path)
for ext in cls.file_extensions:
if path.suffixes[:len(ext)] == ext:
return True
return False | python | {
"resource": ""
} |
q258107 | Tracks.get | validation | def get(self, name) -> Track:
"""
Get or create a Track object.
:param name: Name of the track
:return: Track object
"""
name = name.lower()
track = self.track_map.get(name)
if not track:
track = Track(name)
self.tacks.append(track... | python | {
"resource": ""
} |
q258108 | find_commands | validation | def find_commands(command_dir: str) -> List[str]:
"""
Get all command names in the a folder
:return: List of commands names
"""
if not command_dir:
return []
return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir])
if not is_pkg and not name.startswith('_')] | python | {
"resource": ""
} |
q258109 | Settings.update | validation | def update(self, **kwargs):
"""Override settings values"""
for name, value in kwargs.items():
setattr(self, name, value) | python | {
"resource": ""
} |
q258110 | Settings.add_program_dir | validation | def add_program_dir(self, directory):
"""Hack in program directory"""
dirs = list(self.PROGRAM_DIRS)
dirs.append(directory)
self.PROGRAM_DIRS = dirs | python | {
"resource": ""
} |
q258111 | Settings.add_texture_dir | validation | def add_texture_dir(self, directory):
"""Hack in texture directory"""
dirs = list(self.TEXTURE_DIRS)
dirs.append(directory)
self.TEXTURE_DIRS = dirs | python | {
"resource": ""
} |
q258112 | Settings.add_data_dir | validation | def add_data_dir(self, directory):
"""Hack in a data directory"""
dirs = list(self.DATA_DIRS)
dirs.append(directory)
self.DATA_DIRS = dirs | python | {
"resource": ""
} |
q258113 | VAO.render | validation | def render(self, program: moderngl.Program, mode=None, vertices=-1, first=0, instances=1):
"""
Render the VAO.
Args:
program: The ``moderngl.Program``
Keyword Args:
mode: Override the draw mode (``TRIANGLES`` etc)
vertices (int): The number of vertic... | python | {
"resource": ""
} |
q258114 | VAO.transform | validation | def transform(self, program: moderngl.Program, buffer: moderngl.Buffer,
mode=None, vertices=-1, first=0, instances=1):
"""
Transform vertices. Stores the output in a single buffer.
Args:
program: The ``moderngl.Program``
buffer: The ``moderngl.buffer`` ... | python | {
"resource": ""
} |
q258115 | VAO.index_buffer | validation | def index_buffer(self, buffer, index_element_size=4):
"""
Set the index buffer for this VAO
Args:
buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes``
Keyword Args:
index_element_size (int): Byte size of each element. 1, 2 or 4
"""
if not ty... | python | {
"resource": ""
} |
q258116 | VAO.instance | validation | def instance(self, program: moderngl.Program) -> moderngl.VertexArray:
"""
Obtain the ``moderngl.VertexArray`` instance for the program.
The instance is only created once and cached internally.
Returns: ``moderngl.VertexArray`` instance
"""
vao = self.vaos.get(program.gl... | python | {
"resource": ""
} |
q258117 | VAO.release | validation | def release(self, buffer=True):
"""
Destroy the vao object
Keyword Args:
buffers (bool): also release buffers
"""
for key, vao in self.vaos:
vao.release()
if buffer:
for buff in self.buffers:
buff.buffer.release()
... | python | {
"resource": ""
} |
q258118 | MeshProgram.draw | validation | def draw(self, mesh, projection_matrix=None, view_matrix=None, camera_matrix=None, time=0):
"""
Draw code for the mesh. Should be overriden.
:param projection_matrix: projection_matrix (bytes)
:param view_matrix: view_matrix (bytes)
:param camera_matrix: camera_matrix (bytes)
... | python | {
"resource": ""
} |
q258119 | parse_package_string | validation | def parse_package_string(path):
"""
Parse the effect package string.
Can contain the package python path or path to effect class in an effect package.
Examples::
# Path to effect pacakge
examples.cubes
# Path to effect class
examples.cubes.Cubes
Args:
path... | python | {
"resource": ""
} |
q258120 | EffectRegistry.get_dirs | validation | def get_dirs(self) -> List[str]:
"""
Get all effect directories for registered effects.
"""
for package in self.packages:
yield os.path.join(package.path, 'resources') | python | {
"resource": ""
} |
q258121 | EffectRegistry.get_effect_resources | validation | def get_effect_resources(self) -> List[Any]:
"""
Get all resources registed in effect packages.
These are typically located in ``resources.py``
"""
resources = []
for package in self.packages:
resources.extend(package.resources)
return resources | python | {
"resource": ""
} |
q258122 | EffectRegistry.add_package | validation | def add_package(self, name):
"""
Registers a single package
:param name: (str) The effect package to add
"""
name, cls_name = parse_package_string(name)
if name in self.package_map:
return
package = EffectPackage(name)
package.load()
... | python | {
"resource": ""
} |
q258123 | EffectRegistry.get_package | validation | def get_package(self, name) -> 'EffectPackage':
"""
Get a package by python path. Can also contain path to an effect.
Args:
name (str): Path to effect package or effect
Returns:
The requested EffectPackage
Raises:
EffectError when no package... | python | {
"resource": ""
} |
q258124 | EffectRegistry.find_effect_class | validation | def find_effect_class(self, path) -> Type[Effect]:
"""
Find an effect class by class name or full python path to class
Args:
path (str): effect class name or full python path to effect class
Returns:
Effect class
Raises:
EffectError if no cl... | python | {
"resource": ""
} |
q258125 | EffectPackage.runnable_effects | validation | def runnable_effects(self) -> List[Type[Effect]]:
"""Returns the runnable effect in the package"""
return [cls for cls in self.effect_classes if cls.runnable] | python | {
"resource": ""
} |
q258126 | EffectPackage.load_package | validation | def load_package(self):
"""FInd the effect package"""
try:
self.package = importlib.import_module(self.name)
except ModuleNotFoundError:
raise ModuleNotFoundError("Effect package '{}' not found.".format(self.name)) | python | {
"resource": ""
} |
q258127 | EffectPackage.load_effects_classes | validation | def load_effects_classes(self):
"""Iterate the module attributes picking out effects"""
self.effect_classes = []
for _, cls in inspect.getmembers(self.effect_module):
if inspect.isclass(cls):
if cls == Effect:
continue
if issubcla... | python | {
"resource": ""
} |
q258128 | EffectPackage.load_resource_module | validation | def load_resource_module(self):
"""Fetch the resource list"""
# Attempt to load the dependencies module
try:
name = '{}.{}'.format(self.name, 'dependencies')
self.dependencies_module = importlib.import_module(name)
except ModuleNotFoundError as err:
ra... | python | {
"resource": ""
} |
q258129 | Timeline.draw | validation | def draw(self, time, frametime, target):
"""
Fetch track value for every runnable effect.
If the value is > 0.5 we draw it.
"""
for effect in self.effects:
value = effect.rocket_timeline_track.time_value(time)
if value > 0.5:
effect... | python | {
"resource": ""
} |
q258130 | Loader.load | validation | def load(self):
"""Load a 2d texture"""
self._open_image()
components, data = image_data(self.image)
texture = self.ctx.texture(
self.image.size,
components,
data,
)
texture.extra = {'meta': self.meta}
if self.me... | python | {
"resource": ""
} |
q258131 | ProgramShaders.from_single | validation | def from_single(cls, meta: ProgramDescription, source: str):
"""Initialize a single glsl string containing all shaders"""
instance = cls(meta)
instance.vertex_source = ShaderSource(
VERTEX_SHADER,
meta.path or meta.vertex_shader,
source
)
... | python | {
"resource": ""
} |
q258132 | ProgramShaders.from_separate | validation | def from_separate(cls, meta: ProgramDescription, vertex_source, geometry_source=None, fragment_source=None,
tess_control_source=None, tess_evaluation_source=None):
"""Initialize multiple shader strings"""
instance = cls(meta)
instance.vertex_source = ShaderSource(
... | python | {
"resource": ""
} |
q258133 | ShaderSource.print | validation | def print(self):
"""Print the shader lines"""
print("---[ START {} ]---".format(self.name))
for i, line in enumerate(self.lines):
print("{}: {}".format(str(i).zfill(3), line))
print("---[ END {} ]---".format(self.name)) | python | {
"resource": ""
} |
q258134 | BaseProject.load | validation | def load(self):
"""
Loads this project instance
"""
self.create_effect_classes()
self._add_resource_descriptions_to_pools(self.create_external_resources())
self._add_resource_descriptions_to_pools(self.create_resources())
for meta, resource in resources... | python | {
"resource": ""
} |
q258135 | BaseProject._add_resource_descriptions_to_pools | validation | def _add_resource_descriptions_to_pools(self, meta_list):
"""
Takes a list of resource descriptions adding them
to the resource pool they belong to scheduling them for loading.
"""
if not meta_list:
return
for meta in meta_list:
getattr(r... | python | {
"resource": ""
} |
q258136 | BaseProject.reload_programs | validation | def reload_programs(self):
"""
Reload all shader programs with the reloadable flag set
"""
print("Reloading programs:")
for name, program in self._programs.items():
if getattr(program, 'program', None):
print(" - {}".format(program.meta.label))
... | python | {
"resource": ""
} |
q258137 | image_data | validation | def image_data(image):
"""Get components and bytes for an image"""
# NOTE: We might want to check the actual image.mode
# and convert to an acceptable format.
# At the moment we load the data as is.
data = image.tobytes()
components = len(data) // (image.size[0] * image.size[1]... | python | {
"resource": ""
} |
q258138 | BaseLoader._find_last_of | validation | def _find_last_of(self, path, finders):
"""Find the last occurance of the file in finders"""
found_path = None
for finder in finders:
result = finder.find(path)
if result:
found_path = result
return found_path | python | {
"resource": ""
} |
q258139 | Command.initial_sanity_check | validation | def initial_sanity_check(self):
"""Checks if we can create the project"""
# Check for python module collision
self.try_import(self.project_name)
# Is the name a valid identifier?
self.validate_name(self.project_name)
# Make sure we don't mess with existing direc... | python | {
"resource": ""
} |
q258140 | Command.create_entrypoint | validation | def create_entrypoint(self):
"""Write manage.py in the current directory"""
with open(os.path.join(self.template_dir, 'manage.py'), 'r') as fd:
data = fd.read().format(project_name=self.project_name)
with open('manage.py', 'w') as fd:
fd.write(data)
os.c... | python | {
"resource": ""
} |
q258141 | Command.get_template_dir | validation | def get_template_dir(self):
"""Returns the absolute path to template directory"""
directory = os.path.dirname(os.path.abspath(__file__))
directory = os.path.dirname(os.path.dirname(directory))
directory = os.path.join(directory, 'project_template')
return directory | python | {
"resource": ""
} |
q258142 | Programs.resolve_loader | validation | def resolve_loader(self, meta: ProgramDescription):
"""
Resolve program loader
"""
if not meta.loader:
meta.loader = 'single' if meta.path else 'separate'
for loader_cls in self._loaders:
if loader_cls.name == meta.loader:
meta.loader_cls ... | python | {
"resource": ""
} |
q258143 | ac_encode | validation | def ac_encode(text, probs):
"""Encode a text using arithmetic coding with the provided probabilities.
This is a wrapper for :py:meth:`Arithmetic.encode`.
Parameters
----------
text : str
A string to encode
probs : dict
A probability statistics dictionary generated by
:p... | python | {
"resource": ""
} |
q258144 | Arithmetic.train | validation | def train(self, text):
r"""Generate a probability dict from the provided text.
Text to 0-order probability statistics as a dict
Parameters
----------
text : str
The text data over which to calculate probability statistics. This
must not contain the NUL (... | python | {
"resource": ""
} |
q258145 | Arithmetic.encode | validation | def encode(self, text):
"""Encode a text using arithmetic coding.
Text and the 0-order probability statistics -> longval, nbits
The encoded number is Fraction(longval, 2**nbits)
Parameters
----------
text : str
A string to encode
Returns
--... | python | {
"resource": ""
} |
q258146 | NGramCorpus.corpus_importer | validation | def corpus_importer(self, corpus, n_val=1, bos='_START_', eos='_END_'):
r"""Fill in self.ngcorpus from a Corpus argument.
Parameters
----------
corpus :Corpus
The Corpus from which to initialize the n-gram corpus
n_val : int
Maximum n value for n-grams
... | python | {
"resource": ""
} |
q258147 | NGramCorpus.get_count | validation | def get_count(self, ngram, corpus=None):
r"""Get the count of an n-gram in the corpus.
Parameters
----------
ngram : str
The n-gram to retrieve the count of from the n-gram corpus
corpus : Corpus
The corpus
Returns
-------
int
... | python | {
"resource": ""
} |
q258148 | NGramCorpus._add_to_ngcorpus | validation | def _add_to_ngcorpus(self, corpus, words, count):
"""Build up a corpus entry recursively.
Parameters
----------
corpus : Corpus
The corpus
words : [str]
Words to add to the corpus
count : int
Count of words
"""
if word... | python | {
"resource": ""
} |
q258149 | NGramCorpus.gng_importer | validation | def gng_importer(self, corpus_file):
"""Fill in self.ngcorpus from a Google NGram corpus file.
Parameters
----------
corpus_file : file
The Google NGram file from which to initialize the n-gram corpus
"""
with c_open(corpus_file, 'r', encoding='utf-8') as gn... | python | {
"resource": ""
} |
q258150 | NGramCorpus.tf | validation | def tf(self, term):
r"""Return term frequency.
Parameters
----------
term : str
The term for which to calculate tf
Returns
-------
float
The term frequency (tf)
Raises
------
ValueError
tf can only cal... | python | {
"resource": ""
} |
q258151 | BWT.encode | validation | def encode(self, word, terminator='\0'):
r"""Return the Burrows-Wheeler transformed form of a word.
Parameters
----------
word : str
The word to transform using BWT
terminator : str
A character added to signal the end of the string
Returns
... | python | {
"resource": ""
} |
q258152 | BWT.decode | validation | def decode(self, code, terminator='\0'):
r"""Return a word decoded from BWT form.
Parameters
----------
code : str
The word to transform from BWT form
terminator : str
A character added to signal the end of the string
Returns
-------
... | python | {
"resource": ""
} |
q258153 | Indel.dist_abs | validation | def dist_abs(self, src, tar):
"""Return the indel distance between two strings.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
int
Indel distance
... | python | {
"resource": ""
} |
q258154 | Indel.dist | validation | def dist(self, src, tar):
"""Return the normalized indel distance between two strings.
This is equivalent to normalized Levenshtein distance, when only
inserts and deletes are possible.
Parameters
----------
src : str
Source string for comparison
tar... | python | {
"resource": ""
} |
q258155 | _Distance.sim | validation | def sim(self, src, tar, *args, **kwargs):
"""Return similarity.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
*args
Variable length argument list.
**kwargs
Arbit... | python | {
"resource": ""
} |
q258156 | _Distance.dist_abs | validation | def dist_abs(self, src, tar, *args, **kwargs):
"""Return absolute distance.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
*args
Variable length argument list.
**kwargs
... | python | {
"resource": ""
} |
q258157 | dist_baystat | validation | def dist_baystat(src, tar, min_ss_len=None, left_ext=None, right_ext=None):
"""Return the Baystat distance.
This is a wrapper for :py:meth:`Baystat.dist`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
min_ss_len : int
... | python | {
"resource": ""
} |
q258158 | dist_tversky | validation | def dist_tversky(src, tar, qval=2, alpha=1, beta=1, bias=None):
"""Return the Tversky distance between two strings.
This is a wrapper for :py:meth:`Tversky.dist`.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (o... | python | {
"resource": ""
} |
q258159 | LCSseq.lcsseq | validation | def lcsseq(self, src, tar):
"""Return the longest common subsequence of two strings.
Based on the dynamic programming algorithm from
http://rosettacode.org/wiki/Longest_common_subsequence
:cite:`rosettacode:2018b`. This is licensed GFDL 1.2.
Modifications include:
c... | python | {
"resource": ""
} |
q258160 | LCSseq.sim | validation | def sim(self, src, tar):
r"""Return the longest common subsequence similarity of two strings.
Longest common subsequence similarity (:math:`sim_{LCSseq}`).
This employs the LCSseq function to derive a similarity metric:
:math:`sim_{LCSseq}(s,t) = \frac{|LCSseq(s,t)|}{max(|s|, |t|)}`
... | python | {
"resource": ""
} |
q258161 | Prefix.sim | validation | def sim(self, src, tar):
"""Return the prefix similarity of two strings.
Prefix similarity is the ratio of the length of the shorter term that
exactly matches the longer term to the length of the shorter term,
beginning at the start of both terms.
Parameters
----------
... | python | {
"resource": ""
} |
q258162 | Corpus.docs_of_words | validation | def docs_of_words(self):
r"""Return the docs in the corpus, with sentences flattened.
Each list within the corpus represents all the words of that document.
Thus the sentence level of lists has been flattened.
Returns
-------
[[str]]
The docs in the corpus a... | python | {
"resource": ""
} |
q258163 | Corpus.raw | validation | def raw(self):
r"""Return the raw corpus.
This is reconstructed by joining sub-components with the corpus' split
characters
Returns
-------
str
The raw corpus
Example
-------
>>> tqbf = 'The quick brown fox jumped over the lazy dog.\... | python | {
"resource": ""
} |
q258164 | Corpus.idf | validation | def idf(self, term, transform=None):
r"""Calculate the Inverse Document Frequency of a term in the corpus.
Parameters
----------
term : str
The term to calculate the IDF of
transform : function
A function to apply to each document term before checking for... | python | {
"resource": ""
} |
q258165 | PaiceHusk.stem | validation | def stem(self, word):
"""Return Paice-Husk stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = PaiceHusk()
>>> stmr.stem('assumption')
... | python | {
"resource": ""
} |
q258166 | BeiderMorse._language | validation | def _language(self, name, name_mode):
"""Return the best guess language ID for the word and language choices.
Parameters
----------
name : str
The term to guess the language of
name_mode : str
The name mode of the algorithm: ``gen`` (default),
... | python | {
"resource": ""
} |
q258167 | BeiderMorse._redo_language | validation | def _redo_language(
self, term, name_mode, rules, final_rules1, final_rules2, concat
):
"""Reassess the language of the terms and call the phonetic encoder.
Uses a split multi-word term.
Parameters
----------
term : str
The term to encode via Beider-Mors... | python | {
"resource": ""
} |
q258168 | BeiderMorse._apply_final_rules | validation | def _apply_final_rules(self, phonetic, final_rules, language_arg, strip):
"""Apply a set of final rules to the phonetic encoding.
Parameters
----------
phonetic : str
The term to which to apply the final rules
final_rules : tuple
The set of final phonetic... | python | {
"resource": ""
} |
q258169 | BeiderMorse._expand_alternates | validation | def _expand_alternates(self, phonetic):
"""Expand phonetic alternates separated by |s.
Parameters
----------
phonetic : str
A Beider-Morse phonetic encoding
Returns
-------
str
A Beider-Morse phonetic code
"""
alt_start =... | python | {
"resource": ""
} |
q258170 | BeiderMorse._pnums_with_leading_space | validation | def _pnums_with_leading_space(self, phonetic):
"""Join prefixes & suffixes in cases of alternate phonetic values.
Parameters
----------
phonetic : str
A Beider-Morse phonetic encoding
Returns
-------
str
A Beider-Morse phonetic code
... | python | {
"resource": ""
} |
q258171 | BeiderMorse._phonetic_numbers | validation | def _phonetic_numbers(self, phonetic):
"""Prepare & join phonetic numbers.
Split phonetic value on '-', run through _pnums_with_leading_space,
and join with ' '
Parameters
----------
phonetic : str
A Beider-Morse phonetic encoding
Returns
--... | python | {
"resource": ""
} |
q258172 | BeiderMorse._remove_dupes | validation | def _remove_dupes(self, phonetic):
"""Remove duplicates from a phonetic encoding list.
Parameters
----------
phonetic : str
A Beider-Morse phonetic encoding
Returns
-------
str
A Beider-Morse phonetic code
"""
alt_string ... | python | {
"resource": ""
} |
q258173 | BeiderMorse._normalize_lang_attrs | validation | def _normalize_lang_attrs(self, text, strip):
"""Remove embedded bracketed attributes.
This (potentially) bitwise-ands bracketed attributes together and adds
to the end.
This is applied to a single alternative at a time -- not to a
parenthesized list.
It removes all embe... | python | {
"resource": ""
} |
q258174 | BeiderMorse._apply_rule_if_compat | validation | def _apply_rule_if_compat(self, phonetic, target, language_arg):
"""Apply a phonetic regex if compatible.
tests for compatible language rules
to do so, apply the rule, expand the results, and detect alternatives
with incompatible attributes
then drop each alternative that ... | python | {
"resource": ""
} |
q258175 | BeiderMorse._language_index_from_code | validation | def _language_index_from_code(self, code, name_mode):
"""Return the index value for a language code.
This returns l_any if more than one code is specified or the code is
out of bounds.
Parameters
----------
code : int
The language code to interpret
n... | python | {
"resource": ""
} |
q258176 | dist_strcmp95 | validation | def dist_strcmp95(src, tar, long_strings=False):
"""Return the strcmp95 distance between two strings.
This is a wrapper for :py:meth:`Strcmp95.dist`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
long_strings : bool
... | python | {
"resource": ""
} |
q258177 | NRL.encode | validation | def encode(self, word):
"""Return the Naval Research Laboratory phonetic encoding of a word.
Parameters
----------
word : str
The word to transform
Returns
-------
str
The NRL phonetic encoding
Examples
--------
>... | python | {
"resource": ""
} |
q258178 | LCSstr.lcsstr | validation | def lcsstr(self, src, tar):
"""Return the longest common substring of two strings.
Longest common substring (LCSstr).
Based on the code from
https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring
:cite:`Wikibooks:2018`.
This is licensed ... | python | {
"resource": ""
} |
q258179 | LCSstr.sim | validation | def sim(self, src, tar):
r"""Return the longest common substring similarity of two strings.
Longest common substring similarity (:math:`sim_{LCSstr}`).
This employs the LCS function to derive a similarity metric:
:math:`sim_{LCSstr}(s,t) = \frac{|LCSstr(s,t)|}{max(|s|, |t|)}`
... | python | {
"resource": ""
} |
q258180 | needleman_wunsch | validation | def needleman_wunsch(src, tar, gap_cost=1, sim_func=sim_ident):
"""Return the Needleman-Wunsch score of two strings.
This is a wrapper for :py:meth:`NeedlemanWunsch.dist_abs`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
... | python | {
"resource": ""
} |
q258181 | NeedlemanWunsch.sim_matrix | validation | def sim_matrix(
src,
tar,
mat=None,
mismatch_cost=0,
match_cost=1,
symmetric=True,
alphabet=None,
):
"""Return the matrix similarity of two strings.
With the default parameters, this is identical to sim_ident.
It is possible for sim_ma... | python | {
"resource": ""
} |
q258182 | PhoneticSpanish.encode | validation | def encode(self, word, max_length=-1):
"""Return the PhoneticSpanish coding of word.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to unlimited)
Returns
-------
s... | python | {
"resource": ""
} |
q258183 | NCDbwtrle.dist | validation | def dist(self, src, tar):
"""Return the NCD between two strings using BWT plus RLE.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Compression ... | python | {
"resource": ""
} |
q258184 | ConfusionTable.to_tuple | validation | def to_tuple(self):
"""Cast to tuple.
Returns
-------
tuple
The confusion table as a 4-tuple (tp, tn, fp, fn)
Example
-------
>>> ct = ConfusionTable(120, 60, 20, 30)
>>> ct.to_tuple()
(120, 60, 20, 30)
"""
return sel... | python | {
"resource": ""
} |
q258185 | ConfusionTable.to_dict | validation | def to_dict(self):
"""Cast to dict.
Returns
-------
dict
The confusion table as a dict
Example
-------
>>> ct = ConfusionTable(120, 60, 20, 30)
>>> import pprint
>>> pprint.pprint(ct.to_dict())
{'fn': 30, 'fp': 20, 'tn': 60, '... | python | {
"resource": ""
} |
q258186 | ConfusionTable.population | validation | def population(self):
"""Return population, N.
Returns
-------
int
The population (N) of the confusion table
Example
-------
>>> ct = ConfusionTable(120, 60, 20, 30)
>>> ct.population()
230
"""
return self._tp + self.... | python | {
"resource": ""
} |
q258187 | ConfusionTable.precision | validation | def precision(self):
r"""Return precision.
Precision is defined as :math:`\frac{tp}{tp + fp}`
AKA positive predictive value (PPV)
Cf. https://en.wikipedia.org/wiki/Precision_and_recall
Cf. https://en.wikipedia.org/wiki/Information_retrieval#Precision
Returns
... | python | {
"resource": ""
} |
q258188 | ConfusionTable.precision_gain | validation | def precision_gain(self):
r"""Return gain in precision.
The gain in precision is defined as:
:math:`G(precision) = \frac{precision}{random~ precision}`
Cf. https://en.wikipedia.org/wiki/Gain_(information_retrieval)
Returns
-------
float
The gain in ... | python | {
"resource": ""
} |
q258189 | ConfusionTable.recall | validation | def recall(self):
r"""Return recall.
Recall is defined as :math:`\frac{tp}{tp + fn}`
AKA sensitivity
AKA true positive rate (TPR)
Cf. https://en.wikipedia.org/wiki/Precision_and_recall
Cf. https://en.wikipedia.org/wiki/Sensitivity_(test)
Cf. https://en.wikip... | python | {
"resource": ""
} |
q258190 | ConfusionTable.specificity | validation | def specificity(self):
r"""Return specificity.
Specificity is defined as :math:`\frac{tn}{tn + fp}`
AKA true negative rate (TNR)
Cf. https://en.wikipedia.org/wiki/Specificity_(tests)
Returns
-------
float
The specificity of the confusion table
... | python | {
"resource": ""
} |
q258191 | ConfusionTable.fallout | validation | def fallout(self):
r"""Return fall-out.
Fall-out is defined as :math:`\frac{fp}{fp + tn}`
AKA false positive rate (FPR)
Cf. https://en.wikipedia.org/wiki/Information_retrieval#Fall-out
Returns
-------
float
The fall-out of the confusion table
... | python | {
"resource": ""
} |
q258192 | ConfusionTable.accuracy | validation | def accuracy(self):
r"""Return accuracy.
Accuracy is defined as :math:`\frac{tp + tn}{population}`
Cf. https://en.wikipedia.org/wiki/Accuracy
Returns
-------
float
The accuracy of the confusion table
Example
-------
>>> ct = Confusi... | python | {
"resource": ""
} |
q258193 | ConfusionTable.accuracy_gain | validation | def accuracy_gain(self):
r"""Return gain in accuracy.
The gain in accuracy is defined as:
:math:`G(accuracy) = \frac{accuracy}{random~ accuracy}`
Cf. https://en.wikipedia.org/wiki/Gain_(information_retrieval)
Returns
-------
float
The gain in accura... | python | {
"resource": ""
} |
q258194 | ConfusionTable.pr_lmean | validation | def pr_lmean(self):
r"""Return logarithmic mean of precision & recall.
The logarithmic mean is:
0 if either precision or recall is 0,
the precision if they are equal,
otherwise :math:`\frac{precision - recall}
{ln(precision) - ln(recall)}`
Cf. https://en.wikiped... | python | {
"resource": ""
} |
q258195 | CLEFGerman.stem | validation | def stem(self, word):
"""Return CLEF German stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = CLEFGerman()
>>> stmr.stem('lesen')
'l... | python | {
"resource": ""
} |
q258196 | Sift4Simplest.dist_abs | validation | def dist_abs(self, src, tar, max_offset=5):
"""Return the "simplest" Sift4 distance between two terms.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
max_offset : int
The number of c... | python | {
"resource": ""
} |
q258197 | sim_typo | validation | def sim_typo(
src, tar, metric='euclidean', cost=(1, 1, 0.5, 0.5), layout='QWERTY'
):
"""Return the normalized typo similarity between two strings.
This is a wrapper for :py:meth:`Typo.sim`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target strin... | python | {
"resource": ""
} |
q258198 | manhattan | validation | def manhattan(src, tar, qval=2, normalized=False, alphabet=None):
"""Return the Manhattan distance between two strings.
This is a wrapper for :py:meth:`Manhattan.dist_abs`.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target... | python | {
"resource": ""
} |
q258199 | dist_manhattan | validation | def dist_manhattan(src, tar, qval=2, alphabet=None):
"""Return the normalized Manhattan distance between two strings.
This is a wrapper for :py:meth:`Manhattan.dist`.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target strin... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.