text
stringlengths
185
73.3k
repo
stringlengths
7
100
path
stringlengths
4
146
language
stringclasses
7 values
hash
stringlengths
16
16
score
float64
7
8.5
stars
int64
0
237k
from __future__ import annotations import argparse import sys from importlib.resources import files from typing import TYPE_CHECKING from grascii.dictionary.common import INSTALLATION_DIR, get_dictionary_installed_name if TYPE_CHECKING: from collections.abc import Collection description = "List built-in and ins...
grascii/grascii
grascii/dictionary/list.py
.py
e7968fb005ede0b8
7.63
17
from __future__ import annotations import logging from collections.abc import Callable from pathlib import Path from typing import TYPE_CHECKING if TYPE_CHECKING: import os PipelineFunc = Callable[[str, str, logging.LoggerAdapter], tuple[str, str]] """A function for dictionary builds that checks and/or transform...
grascii/grascii
grascii/dictionary/pipeline.py
.py
c5539950b2243335
7.63
17
from __future__ import annotations import argparse import sys from shutil import rmtree from typing import TYPE_CHECKING from grascii.dictionary.common import ( INSTALLATION_DIR, DictionaryNotFound, get_dictionary_path_name, ) if TYPE_CHECKING: from pathlib import Path description = "Uninstall a Gra...
grascii/grascii
grascii/dictionary/uninstall.py
.py
c201b961664e655d
7.63
17
""" Acts as the main entry point for the grascii interpret command. This can be invoked as a standalone program: ``$ python -m grascii.interpret --help`` """ from __future__ import annotations import argparse import sys from grascii import InvalidGrascii from grascii.interpreter import interpretation_to_string from...
grascii/grascii
grascii/interpret.py
.py
576ed90a346fa56d
7.63
17
from __future__ import annotations import re from functools import reduce from grascii import grammar from grascii.validator import GrasciiValidator Interpretation = list[str | list[str]] """ Represents an interpretation of a Grascii string. An ``Interpretation`` is a list of strokes and annotation lists. Each strok...
grascii/grascii
grascii/interpreter.py
.py
51595ad524ea66ca
7.63
17
""" MIT License Copyright (c) 2022 chanicpanic Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, d...
grascii/grascii
grascii/lark_ambig_tools.py
.py
191b4e258b6892b7
7.63
17
""" Contains metrics for comparing search queries to regular expression matches. """ from __future__ import annotations from typing import ( TYPE_CHECKING, Any, NamedTuple, Protocol, TypeVar, ) from grascii import grammar from grascii.similarities import get_similar if TYPE_CHECKING: from co...
grascii/grascii
grascii/metrics.py
.py
96c8088600be81c5
7.63
17
from __future__ import annotations from typing import TYPE_CHECKING from lark import Lark, Token, Transformer, Tree, UnexpectedInput from grascii import grammar from grascii.lark_ambig_tools import Disambiguator if TYPE_CHECKING: from collections.abc import Iterator from grascii.interpreter import Interpre...
grascii/grascii
grascii/parser.py
.py
fb2f3f707122e39c
7.63
17
""" Acts as the main entry point for the grascii search command. This can be invoked as a standalone program: ``$ python -m grascii.search --help`` """ from __future__ import annotations import argparse import sys from typing import TYPE_CHECKING, overload from grascii import regen from grascii.dictionary import Di...
grascii/grascii
grascii/search.py
.py
afc25c4a03a1da2c
7.63
17
"""Contains methods for determining the similarity of grascii strokes.""" from __future__ import annotations from functools import lru_cache from typing import TYPE_CHECKING, cast from grascii import grammar if TYPE_CHECKING: from collections.abc import Hashable, Iterable _equiv_nodes: dict[str, tuple[str, ......
grascii/grascii
grascii/similarities.py
.py
b9db8470ff2c0124
7.63
17
from __future__ import annotations import re from functools import lru_cache from lark import Lark @lru_cache(maxsize=1) def get_grascii_regex_str() -> str: """Get a string that can be compiled into a regular expression that matches Grascii strings. """ parser = Lark.open_from_package("grascii.gramm...
grascii/grascii
grascii/validator.py
.py
fb33c5cffc91ddee
7.63
17
from __future__ import annotations from pathlib import Path from lark import Lark, Token, Transformer, Tree from lark.reconstruct import Reconstructor class GrasciiProcessor(Transformer): def __init__(self, parser): super().__init__(visit_tokens=True) self.parser = parser def start(self, ch...
grascii/grascii
scripts/create_grascii_regex.py
.py
da1ccccd8a446939
7.63
17
from __future__ import annotations import pytest from grascii.interpreter import GrasciiInterpreter from grascii.parser import GrasciiParser, InvalidGrascii class TestGrasciiInterpreter: @pytest.fixture(scope="class", autouse=True) def interpreter(self): return GrasciiInterpreter() @pytest.fixt...
grascii/grascii
tests/test_interpreter.py
.py
df00a75fdec56907
7.13
17
import itertools import random import irc3 from irc3.plugins.command import command from relbot.ircformat import Color, format_text from relbot.redflare_client import RedflareClient from relbot.util import make_logger @irc3.plugin class RELBotBNPlugin: def __init__(self, bot): self.logger = make_logger(...
TheAssassin/relbot
relbot/bn_plugin.py
.py
dd9f821a32d25348
7.42
6
import re import irc3 from lxml import html from relbot.github_issues_matcher import GitHubIssuesMatcher from relbot.util import managed_proxied_session, make_logger, format_github_event logger = make_logger("github_integration") class GitHubChatMonitorError(Exception): def __init__(self, message): sel...
TheAssassin/relbot
relbot/github_chat_monitor.py
.py
27f8b0c1a3a7005f
7.42
6
import irc3 import requests from irc3.plugins.command import command from irc3.plugins.cron import cron from relbot.github_events_api_client import GithubEventsAPIClient from relbot.util import format_github_event, make_logger @irc3.plugin class RELBotGitHubEventsFeedPlugin: def __init__(self, bot): self...
TheAssassin/relbot
relbot/github_events_feed_plugin.py
.py
9bc83601e5775d12
7.42
6
import re import string import urllib.parse from typing import NamedTuple, List, Dict from relbot.util import make_logger class GitHubIssue(NamedTuple): repo_owner: str repo_name: str issue_id: int def __str__(self): """ A string representation of a GitHub issue equivalent to GitHub'...
TheAssassin/relbot
relbot/github_issues_matcher.py
.py
b81cadad2c7769ac
7.42
6
""" IRC formatting based on https://modern.ircdocs.horse/formatting. """ from enum import IntEnum class Color(IntEnum): WHITE = 0 BLACK = 1 BLUE = 2 GREEN = 3 RED = 4 BROWN = 5 MAGENTA = 6 ORANGE = 7 YELLOW = 8 LIGHT_GREEN = 9 CYAN = 10 LIGHT_CYAN = 11 LIGHT_BLUE ...
TheAssassin/relbot
relbot/ircformat.py
.py
fee7969ce82a01f9
7.42
6
import contextlib import logging import os import sys import requests def format_github_event(event): s = "[GitHub] {}".format(event) return s @contextlib.contextmanager def managed_proxied_session(): """ Set up requests session with proxies preconfigured. HTTP(S) requests done via this session obj...
TheAssassin/relbot
relbot/util.py
.py
bebfdc06960cf5ef
7.42
6
"""Date module.""" __all__ = ["compare", "get_first_day_of_month", "get_last_day_of_month"] import system.date from java.util import Date def compare(date_1, date_2): # type: (Date, Date) -> int """Compare two dates. Args: date_1: The first date. date_2: The second date. Returns: ...
ignition-devs/incendium
src/incendium/date.py
.py
6196ae278b839c80
7.57
13
"""GUI Module.""" __all__ = ["validate_form"] from typing import Dict, Optional, Tuple from incendium import constants from incendium.helper.types import AnyStr, Number def _format_error_message(counter, error_message, key): # type: (int, AnyStr, AnyStr) -> AnyStr """Format error message. Args: ...
ignition-devs/incendium
src/incendium/gui.py
.py
044965c1691158d2
7.57
13
"""Net module.""" from __future__ import unicode_literals __all__ = [ "HTML_ESCAPE_TABLE", "report_error", "send_high_priority_email", "send_html_email", "send_plain_text_email", ] from typing import Dict, List import system.net from incendium import constants from incendium.helper.types import...
ignition-devs/incendium
src/incendium/net.py
.py
5ab5ff608aa4580f
7.57
13
"""Tag module.""" __all__ = ["read", "write"] from typing import Any import system.tag from com.inductiveautomation.ignition.common.model.values import BasicQualifiedValue from incendium.helper.types import AnyStr def read(tag_path): # type: (AnyStr) -> BasicQualifiedValue """Read the value of the Tags at...
ignition-devs/incendium
src/incendium/tag.py
.py
4f291a2774f9f180
7.57
13
"""Time module.""" __all__ = ["get_timer", "get_timestamp"] from typing import Union import system.date from java.util import Date from incendium.helper.types import AnyStr def get_timestamp(value): # type: (int) -> AnyStr """Get timestamp in "hh:mm:ss" format. Args: value: Time represented i...
ignition-devs/incendium
src/incendium/time.py
.py
49bd825f93c32b5a
7.57
13
"""Navigation module.""" from __future__ import unicode_literals __all__ = ["swap_to", "swap_windows"] from typing import List, Optional import system.vision from incendium.helper.types import AnyStr, DictStringAny def _get_full_path(from_path, to_path): # type: (AnyStr, AnyStr) -> AnyStr """Return the f...
ignition-devs/incendium
src/incendium/vision/nav.py
.py
3cf29e606a5e9284
7.57
13
import logging import os import shutil import subprocess import time from selenium import webdriver from selenium.common.exceptions import InvalidArgumentException from selenium.webdriver.chrome.service import Service as ChromeService from tqdm import tqdm from webdriver_manager.chrome import ChromeDriverManager from...
Esgrove/recordpool-dl
src/RecordPool.py
.py
df7a22adeb50a432
7.5
9
""" Record Pool Downloader Akseli Lukkarila 2019 """ import logging import os import sys import threading import traceback from Bandcamp import Bandcamp from Beatjunkies import Beatjunkies from BPMSupreme import BPMSupreme from colorprint import print_bold, print_cyan, print_error, print_error_and_exit, print_red, pr...
Esgrove/recordpool-dl
src/RecordPoolDownloader.py
.py
b2d9a6048bcb29fb
7.5
9
import platform from enum import Enum from typing import Self class Site(Enum): """Supported Recordpool websites.""" BANDCAMP = "Bandcamp" BEATJUNKIES = "Beatjunkies" BPMSUPREME = "BPMSupreme" DJCITY = "DJCity" # Not using StrEnum here since that will use the variable name in lowercase, ...
Esgrove/recordpool-dl
src/utils.py
.py
5bdb95fca8a5d59e
7.5
9
from imdb.parser.search_id_base import BaseSearchID class search_character_id(BaseSearchID): """ 'IMDbID' method takes a character name, searches for the similar character names available in IMDb. and suggests the character name to the user. Based upon user's selection it returns a list of character ids. ...
santhoshse7en/imdby
imdb/parser/character/search_character_id.py
.py
528f2adabe5c8a64
7.52
10
from imdb.parser.search_id_base import BaseSearchID class search_company_id(BaseSearchID): """ 'IMDbID' method takes a company name, searches for the similar company names available in IMDb. and suggests the company name to the user. Based upon user's selection it returns a list of company ids. Input...
santhoshse7en/imdby
imdb/parser/company/search_company_id.py
.py
9b348868a21532db
7.52
10
from imdb.parser.search_id_base import BaseSearchID class search_event_id(BaseSearchID): """ 'IMDbID' method takes an event name, searches for the similar event names available in IMDb. and suggests the event name to the user. Based upon user's selection it returns a list of event ids. Input serial n...
santhoshse7en/imdby
imdb/parser/event/search_event_id.py
.py
cfc5a13b1bfced8b
7.52
10
from imdb.utils.config import base_uri, imdb_uris from imdb.utils.helpers import catch, critic_df, unicode from imdb.utils.utils import BeautifulSoup, get, re # Retrieves IMDb Plot Details class critic_reviews: """ Collects IMDb Ratings Details of the multi-media content in IMDb when title_id is given. :...
santhoshse7en/imdby
imdb/parser/movie/critic_reviews.py
.py
00a5b9643c91abc5
7.52
10
from imdb.utils.config import imdb_uris from imdb.utils.helpers import catch, top_250, top_box_office from imdb.utils.utils import BeautifulSoup, get # Retrieves IMDb Charts Details class imdb_charts: """ Collects top rated movies details of the multi-media content in IMDb. """ def __init__(self): ...
santhoshse7en/imdby
imdb/parser/movie/imdb_charts.py
.py
79e1947805245e99
7.52
10
from imdb.parser.search_id_base import BaseSearchID class search_title_id(BaseSearchID): """ 'IMDbID' method takes a title name, searches for the similar title names available in IMDb. and suggests the title name to the user. Based upon user's selection it returns a list of title ids. Input serial nu...
santhoshse7en/imdby
imdb/parser/movie/search_title_id.py
.py
0e8a67df8e3ace50
7.52
10
from imdb.utils.config import imdb_uris from imdb.utils.helpers import catch, top_250 from imdb.utils.utils import BeautifulSoup, get # Retrieves IMDb Top India Charts Details class top_india_charts: """ Collects top india charts details of the multi-media content in IMDb. """ def __init__(self): ...
santhoshse7en/imdby
imdb/parser/movie/top_india_charts.py
.py
4100b2ea78191654
7.52
10
from imdb.utils.config import imdb_uris from imdb.utils.helpers import catch, trending_now, trending_now_df from imdb.utils.utils import BeautifulSoup, get # Retrieves IMDb Trending Now in India Details class trending_now_in_india: """ Collects trending_now_in_india details of the multi-media content in IMDb...
santhoshse7en/imdby
imdb/parser/movie/trending_now_in_india.py
.py
162ad665a26a7b4d
7.52
10
from imdb.utils.config import base_uri, imdb_uris from imdb.utils.helpers import catch, digits, review_df, unicode from imdb.utils.utils import (BeautifulSoup, By, Options, SentimentIntensityAnalyzer, WebDriverWait, ec, get, re, sys, time, webdriver) # Retri...
santhoshse7en/imdby
imdb/parser/movie/user_reviews.py
.py
ab731c265ab7b0a2
7.52
10
from imdb.parser.search_id_base import BaseSearchID class search_news_id(BaseSearchID): """ 'IMDbID' method takes a news title, searches for the similar news titles available in IMDb. and suggests the news title to the user. Based upon user's selection it returns a list of news ids. Input serial numb...
santhoshse7en/imdby
imdb/parser/news/search_news_id.py
.py
2480674ee8836437
7.52
10
from imdb.parser.search_id_base import BaseSearchID class search_person_id(BaseSearchID): """ 'IMDbID' method takes a person name, searches for the similar person names available in IMDb. and suggests the person name to the user. Based upon user's selection it returns a list of person ids. Input seri...
santhoshse7en/imdby
imdb/parser/person/search_person_id.py
.py
a675bae2e12f726e
7.52
10
"""Support custom filters for jinja2 templating""" import ast import base64 import json import re import urllib.parse import zlib import logging import datetime import dateutil.parser from random import Random, SystemRandom, shuffle from homeassistant.helpers import template _LOGGER = logging.getLogger(__name__) _T...
zvldz/ha_custom_filters
custom_components/custom_filters/__init__.py
.py
74cdd897db867026
7.57
13
# Copyright (C) 2017 Ashish Gupta # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distrib...
ashish-code/entropic_image_contrast_measure
src/entropic_contrast/_legacy_pycontrast.py
.py
1369f7a4bb08b7a9
7.56
12
""" metrics.py — Mutual Information between discrete histogram sequences. This module provides the core information-theoretic measures used by the Entropic Contrast algorithm. Both functions operate on histogram arrays (counts or densities) — they do not accept images directly. Algorithm context ----------------- Th...
ashish-code/entropic_image_contrast_measure
src/entropic_contrast/metrics.py
.py
fa03c667143745b4
7.56
12
""" tests/test_metrics.py — Unit tests for the metrics module. Key behavioral contract of the contingency-table MI: - MI is measured between two 1-D arrays treated as paired label sequences. - Each unique float value becomes a distinct class label. - Two IDENTICAL arrays with K distinct values → MI = ln(K) (maximum). ...
ashish-code/entropic_image_contrast_measure
tests/test_metrics.py
.py
5a90349ab2f10ff6
8.06
12
""" Created on Jun 29, 2015 @author: ash @organization: OSU """ """ Read graphs in Open Street Maps osm format Based on osm.py from brianw's osmgeocode http://github.com/brianw/osmgeocode, which is based on osm.py from comes from Graphserver: http://github.com/bmander/graphserver/tree/master and is copyright (c) 200...
ashish-code/gps-denied-geospatial-positioning
src/pyNetXOsm.py
.py
518edc728bb96895
7.45
7
"""Saving and loading a trained map. Not a hot path, and tracked anyway: this is the boundary where a map becomes a file someone keeps, and the format deliberately refuses pickle. A change that made loading slow enough to discourage saving would quietly push people back toward ``pickle.dump``, which is arbitrary code ...
andremsouza/python-som
asv_benchmarks/benchmarks/artifacts.py
.py
7bd1f697dd35ddbc
7.52
10
"""Shared fixtures and parameter sets for the asv suite. Kept in one place so that every benchmark measures the same map on the same data, and so a change to the case sizes moves all of them together rather than some of them. """ from __future__ import annotations import numpy as np import python_som #: Fixed, so ...
andremsouza/python-som
asv_benchmarks/benchmarks/common.py
.py
7e81486a4d8c86e8
7.52
10
"""Matching inputs to models: the other half of batch training, and all of scoring. ``accumulate`` is roughly 40% of a batch iteration and loops over samples in Python, so it is the half of the cost that scales with the dataset rather than with the grid. """ from __future__ import annotations from typing import TYPE...
andremsouza/python-som
asv_benchmarks/benchmarks/matching.py
.py
f4a340b573987a50
7.52
10
"""Compare the pure update rules against the in-place form that 0.3.0 shipped. The functional core returns new arrays instead of mutating in place. That is an architectural choice, and this script keeps it an *informed* one: it measures the cost rather than assuming it, and it refuses to report a timing until it has p...
andremsouza/python-som
benchmarks/bench_update.py
.py
9efd6410d7e09466
7.52
10
r"""Compare this package against SOMPY, across a process boundary because it has to be. Run it directly, once the environment below exists:: uv run python benchmarks/bench_vs_sompy.py **SOMPY needs an environment of its own, and you have to build it by hand.** Nothing here installs anything; if the environment i...
andremsouza/python-som
benchmarks/bench_vs_sompy.py
.py
93a736d33d1ea552
7.52
10
"""Optional numba kernel for the best-matching-unit search. Import is always safe. Enabled by ``pip install numba``, which this package detects and uses automatically. Without it :func:`bmu_kernel` returns None and everything runs on the NumPy path, which stays the reference implementation and the default. **Delibera...
andremsouza/python-som
src/python_som/_accelerate.py
.py
1c851d810ae7c672
7.52
10
"""Saving and loading a trained map, with the provenance needed to defend a result. Wilson et al., *Best Practices for Scientific Computing*: a result should carry its inputs, parameters and versions. **One file.** A single ``.npz`` holding the models as an array and the metadata as a JSON string. Provenance that can...
andremsouza/python-som
src/python_som/_artifact.py
.py
6e0184f355d59454
7.52
10
"""Decay functions for the learning rate and the neighborhood radius. Each function maps an initial value, the current iteration and the total number of iterations to the current value. They share one signature so that any of them, or a user-supplied equivalent, can be passed as ``learning_rate_decay`` or ``neighborho...
andremsouza/python-som
src/python_som/_core/_decay.py
.py
2e06489f67cee7c0
7.52
10
"""Distance measures between input vectors and the models of the network.""" from __future__ import annotations from typing import TYPE_CHECKING, Final import numpy as np import numpy.typing as npt if TYPE_CHECKING: # pragma: no cover from ._protocols import DistanceFunction __all__ = ["DISTANCE_FUNCTIONS", "...
andremsouza/python-som
src/python_som/_core/_distance.py
.py
11c2902115039015
7.52
10
"""The three ways of choosing initial models, each returning a new array. Kohonen (2013) Section 4.3 recommends the linear one: "much faster and convergence follow if the initial values are selected as a regular, two-dimensional sequence of vectors taken along a hyperplane spanned by the two largest principal componen...
andremsouza/python-som
src/python_som/_core/_initialize.py
.py
7744f75d69f87f01
7.52
10
"""Principal component analysis, and the map sizing that depends on it. Built on ``np.linalg.svd`` rather than scikit-learn, which it reproduces exactly, sign convention and degenerate columns included. ``tests/test_linalg_matches_sklearn.py`` re-checks that against the real scikit-learn on every CI run, which is why ...
andremsouza/python-som
src/python_som/_core/_linalg.py
.py
0f98b8afc2c2a3fd
7.52
10
"""Summaries of a trained map: the U-matrix, and the three per-node mappings.""" from __future__ import annotations from collections import Counter from typing import TYPE_CHECKING, Any import numpy as np from ._match import bmu_indices, winner from ._neighborhood import bubble if TYPE_CHECKING: # pragma: no cove...
andremsouza/python-som
src/python_som/_core/_maps.py
.py
22c0d83edf2dea52
7.52
10
"""Matching inputs to models: which node wins, and how far away it is. Everything here is used by both training and analysis, which is why it is its own module rather than living beside either. """ from __future__ import annotations from typing import TYPE_CHECKING, Any import numpy as np from ._distance import eu...
andremsouza/python-som
src/python_som/_core/_match.py
.py
6448a51e60c31016
7.52
10
"""The two update rules, as pure functions returning new models. Both return a new array rather than mutating their argument, so they can be tested without constructing a :class:`~python_som.SOM`. That costs roughly 10% on small maps and nothing on large ones; ``benchmarks/bench_update.py`` measures it. """ from __fu...
andremsouza/python-som
src/python_som/_core/_update.py
.py
5ae38e097b5bd9fc
7.52
10
"""Names for the string-valued options, so a typo is a type error rather than a runtime one. Every option is also accepted as a plain string, permanently. ``mode=TrainingMode.BATCH`` and ``mode="batch"`` are interchangeable, compare equal, hash equal and serialise identically, because each member *is* a ``str``. 0.5.0...
andremsouza/python-som
src/python_som/_enums.py
.py
d5c4399e5a8d03d7
7.52
10
"""scikit-learn adapter. Import this only if you want a map to work inside scikit-learn. :class:`~python_som.SOM` already has ``fit``, ``transform``, ``predict`` and ``score``, which is enough when you call them yourself. It is not enough when scikit-learn does: since 1.7, ``Pipeline.predict``, ``GridSearchCV`` and ``...
andremsouza/python-som
src/python_som/sklearn.py
.py
f1babecd18508759
7.52
10
"""Shared fixtures for the python_som test suite.""" from __future__ import annotations from typing import Any import numpy as np import numpy.typing as npt import pandas as pd import pytest from hypothesis import settings import python_som # Deterministic replay in CI, so a failure reported by a run can be reprod...
andremsouza/python-som
tests/conftest.py
.py
a85ea6bf0ef59bdb
8.02
10
"""Constructor validation, automatic sizing and accessors.""" from __future__ import annotations from typing import TYPE_CHECKING import numpy as np import pytest import sklearn.decomposition import sklearn.preprocessing import python_som from python_som import Neighborhood from tests.conftest import SEED, make_som...
andremsouza/python-som
tests/test_construction.py
.py
e01b73d4df67d366
8.02
10
"""Properties of the decay functions.""" from __future__ import annotations from collections.abc import Callable from itertools import pairwise from typing import TypeAlias import numpy as np import pytest from hypothesis import given from hypothesis import strategies as st from python_som import ( asymptotic_d...
andremsouza/python-som
tests/test_decay.py
.py
f079418ee912875b
8.02
10
"""End-to-end runs, marked ``slow``. These exist because every other test in the suite checks one property in isolation. A map can pass all of them and still fail to do the thing the library is for: take a dataset with structure in it and lay that structure out on the grid. Deselect with ``-m 'not slow'``. Nothing he...
andremsouza/python-som
tests/test_end_to_end.py
.py
9b5d731d9d42c28d
8.02
10
"""Check the NumPy PCA and z-score against the scikit-learn implementations they replaced. 0.4.0 dropped scikit-learn as a runtime dependency and reimplemented the two things this package used it for on ``np.linalg.svd``. That trades 264 MB of required install for about twenty lines of linear algebra, and it is the on...
andremsouza/python-som
tests/test_linalg_matches_sklearn.py
.py
270cce70b763ed12
8.02
10
"""The optional numba kernel must select exactly the nodes the NumPy path selects. ``pip install numba`` swaps a compiled kernel into the best-matching-unit search. It is a second implementation of the hottest code in the package, and the whole reason that is acceptable is that the NumPy path stays the reference and t...
andremsouza/python-som
tests/test_numba_kernel.py
.py
9a2ad1340d5843bd
8.02
10
"""The packaging contract: typing marker, public surface, version and metadata.""" from __future__ import annotations import pathlib import sys from importlib.metadata import metadata, version from typing import Any import pytest if sys.version_info >= (3, 11): import tomllib else: # pragma: no cover impor...
andremsouza/python-som
tests/test_packaging.py
.py
70d913405662604c
8.02
10
"""Training behaviour and the invariants that must hold for any input. The invariants are the point of this module. The bugs found in this library were not wrong formulas so much as properties nobody had asserted: that no model is silently destroyed, that a requested iteration count is honoured, that a training step c...
andremsouza/python-som
tests/test_training.py
.py
d1f57c45f0f018a4
8.02
10
import yaml def check_config_keys(cfg, required_keys): """ Checks the config file and raise a value if there is a problem Args: cfg (omegaconf.dictconfig.DictConfig): A config file that is shared through 'hydra' required_keys (list): A list of required keys to be checked Raises: ...
sadafnazari/Persian_handwriting_recognition
src/utils/config.py
.py
f076f4338fc55101
7.66
20
"""Configuration management for GOV.UK statistics counter.""" from pathlib import Path from pydantic import Field, computed_field from pydantic_settings import BaseSettings class Config(BaseSettings): """Application configuration with sensible defaults.""" # Scraping configuration gov_url: str = "https...
ivyleavedtoadflax/GOVUK_stats_counter
src/config.py
.py
11afd7898db00376
7.42
6
#!/usr/bin/env python3 """ Create visualization of GOV.UK statistics count over time. Reads the JSON log file and creates a line plot showing the growth of statistics published on GOV.UK. """ import json from datetime import datetime import matplotlib.dates as mdates import matplotlib.pyplot as plt from matplotlib.t...
ivyleavedtoadflax/GOVUK_stats_counter
src/create_visualization.py
.py
c04c6f6ab5cad41e
7.42
6
"""Tests for configuration module.""" import os import tempfile from pathlib import Path from src.config import Config def test_config_default_logfile(): """Test that config uses default logfile path when LOGFILE env var not set.""" # Ensure LOGFILE env var is not set if "LOGFILE" in os.environ: ...
ivyleavedtoadflax/GOVUK_stats_counter
tests/test_config.py
.py
8e1a3a3e3e35b369
7.92
6
"""Tests for visualization module.""" import json import tempfile from datetime import datetime from pathlib import Path import pytest from src.config import config from src.create_visualization import format_thousands, load_data def test_load_data_empty_file(): """Test loading data from empty file.""" wit...
ivyleavedtoadflax/GOVUK_stats_counter
tests/test_visualization.py
.py
a391c3c4bf8850c6
7.92
6
"""Tests for JSON logging functionality.""" import json import tempfile from pathlib import Path from src.write_json_log import write_json_log def test_write_json_log_new_file(): """Test writing to a new log file.""" test_data = {"time": "2022-01-01 12:00:00", "count": 1000} with tempfile.NamedTemporar...
ivyleavedtoadflax/GOVUK_stats_counter
tests/test_write_json_log.py
.py
161f45794a03c976
7.92
6
"""Conditionally configure runtime typechecking.""" from contextlib import suppress from datetime import datetime, timezone from enum import Enum from os import getenv from warnings import filterwarnings from typing_extensions import Self NAME = 'calcipy'.upper() """Package name to allow more targeted usage.""" cl...
KyleKing/calcipy
calcipy/_runtime_type_check_setup.py
.py
26b9d4ddebaf73f9
7.6
15
"""Extend Invoke for Calcipy.""" import sys from base64 import b64encode from functools import wraps from pathlib import Path from types import ModuleType from beartype.typing import Any, Callable, Dict, List, Optional, Union from invoke.collection import Collection as InvokeCollection # noqa: TID251 from invoke.con...
KyleKing/calcipy
calcipy/cli.py
.py
db44e635686c27c5
7.6
15
"""Extend Invoke for Calcipy.""" from __future__ import annotations import logging import os from contextlib import redirect_stderr, redirect_stdout from dataclasses import dataclass, field from functools import wraps from io import StringIO from pathlib import Path from types import ModuleType from beartype.typing ...
KyleKing/calcipy
calcipy/collection.py
.py
1ce8307b78ed742e
7.6
15
"""Experiment with checking for duplicate test names.""" import ast from pathlib import Path from beartype.typing import List, Union from corallium.log import LOGGER def _show_info(function: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> None: """Print info about the function.""" LOGGER.info('> name', nam...
KyleKing/calcipy
calcipy/experiments/check_duplicate_test_names.py
.py
e8a82e13353112d7
8.1
15
"""Markup Machine.""" from __future__ import annotations import json import re import shlex import subprocess # noqa: S404 from pathlib import Path from beartype.typing import Any, Callable, Dict, List, Optional from corallium.file_helpers import read_lines from corallium.file_search import find_project_files_by_su...
KyleKing/calcipy
calcipy/markup_writer/_writer.py
.py
05724a15351d07e6
7.6
15
"""nox with uv backend configuration. Modern nox configuration using uv as the virtual environment backend. Automatically discovers Python versions from mise.toml, mise.lock, or .tool-versions. [Useful snippets from docs](https://nox.thea.codes/en/stable/usage.html) ```sh # List all sessions nox -l # Run tests for ...
KyleKing/calcipy
calcipy/noxfile/_noxfile.py
.py
23c19dadd39c21e3
7.6
15
"""Start the command line program.""" from types import ModuleType from beartype.typing import List from corallium.log import LOGGER from . import __pkg_name__, __version__ from .cli import start_program from .collection import Collection def start() -> None: # pragma: no cover """Run the customized Invoke Pr...
KyleKing/calcipy
calcipy/scripts.py
.py
8b09d2ae1b6c38cb
7.6
15
"""Tasks can be imported piecemeal or imported in their entirety from here.""" from beartype.typing import Any, List, Union from corallium.log import LOGGER from invoke.context import Context from invoke.tasks import Call from calcipy.cli import task from calcipy.collection import DeferredTask, _build_task from . im...
KyleKing/calcipy
calcipy/tasks/all_tasks.py
.py
f2a95b5774869286
7.6
15
"""Changelog CLI.""" from beartype.typing import Literal, Optional from invoke.context import Context from calcipy.cli import task from calcipy.invoke_helpers import get_doc_subdir, get_project_path, run from .executable_utils import python_m SuffixT = Optional[Literal['alpha', 'beta', 'rc']] """Prerelease Suffix T...
KyleKing/calcipy
calcipy/tasks/cl.py
.py
78a17b266201bf22
7.6
15
"""Calcipy-Invoke Defaults.""" import json from contextlib import suppress from pathlib import Path from invoke.context import Context from calcipy.collection import Collection DEFAULTS = { 'tags': { 'filename': 'CODE_TAG_SUMMARY.md', 'ignore_patterns': '', }, 'test': { 'min_cove...
KyleKing/calcipy
calcipy/tasks/defaults.py
.py
889afe6ecbff6108
7.6
15
"""Document CLI.""" import webbrowser from contextlib import suppress from pathlib import Path from corallium.file_helpers import ( MKDOCS_CONFIG, open_in_browser, read_yaml_file, ) from invoke.context import Context from invoke.exceptions import UnexpectedExit from calcipy.cli import task from calcipy.i...
KyleKing/calcipy
calcipy/tasks/doc.py
.py
f3fe054915f66782
7.6
15
"""Utilities for working in calcipy's python environment.""" import sys from contextlib import suppress from functools import lru_cache from pathlib import Path from beartype.typing import Optional from invoke.context import Context from invoke.runners import Result from calcipy.invoke_helpers import run @lru_cach...
KyleKing/calcipy
calcipy/tasks/executable_utils.py
.py
fb947795e330e31b
7.6
15
"""Packaging CLI.""" from corallium import ( can_skip, # Required for mocking can_skip.can_skip file_helpers, # Required for mocking read_pyproject ) from corallium.file_helpers import PROJECT_TOML, get_lock from corallium.log import LOGGER from invoke.context import Context from calcipy.cli import task fro...
KyleKing/calcipy
calcipy/tasks/pack.py
.py
8a60ea9c9c626a7e
7.6
15
"""Test CLI.""" from pathlib import Path from beartype.typing import Optional from corallium.file_helpers import open_in_browser, read_package_name from invoke.context import Context from calcipy.cli import task from calcipy.experiments import check_duplicate_test_names from calcipy.invoke_helpers import run from ....
KyleKing/calcipy
calcipy/tasks/test.py
.py
1a30e4032782ad36
8.1
15
"""Types CLI.""" from corallium.file_helpers import read_package_name from invoke.context import Context from calcipy.cli import task from calcipy.invoke_helpers import run from .executable_utils import PYRIGHT_MESSAGE, check_installed, python_m @task() def pyright(ctx: Context) -> None: """Run pyright using t...
KyleKing/calcipy
calcipy/tasks/types.py
.py
bf75ffcded59ee26
7.6
15
"""Global variables for testing.""" from pathlib import Path from corallium.file_helpers import delete_dir, ensure_dir TEST_DIR = Path(__file__).resolve().parent """Path to the `test` directory that contains this file and all other tests.""" APP_DIR = TEST_DIR.parent """Application directory.""" TEST_DATA_DIR = TE...
KyleKing/calcipy
tests/configuration.py
.py
939da9e100c83f14
7.1
15
"""Pytest configuration.""" from pathlib import Path import pytest from invoke.context import MockContext from .configuration import TEST_TMP_CACHE, clear_test_cache @pytest.fixture def fix_test_cache() -> Path: """Fixture to clear and return the test cache directory for use. Returns: Path: Path t...
KyleKing/calcipy
tests/conftest.py
.py
24e253d95c72c90f
8.1
15
from pathlib import Path from calcipy.experiments.check_duplicate_test_names import run class ClassTest: """Test check_duplicate_test_names for searching by Class.""" def method_test(self) -> None: """Test check_duplicate_test_names for searching by method.""" def intentional_duplicate(): """I...
KyleKing/calcipy
tests/experiments/test_check_duplicate_test_names.py
.py
96dcd8ef8157f5e6
7.1
15
from typing import Any from calcipy.noxfile._noxfile import _has_ci_group def test__has_ci_group_with_ci(): """Test that _has_ci_group returns True when ci group exists.""" pyproject_data = { 'dependency-groups': { 'ci': [ 'hypothesis[cli] >=6.112.4', 'pyte...
KyleKing/calcipy
tests/noxfile/test_noxfile.py
.py
ad83c8112857c182
8.1
15
"""E2E listener tests for ovos-stt-plugin-vosk. Tests: 1. Direct transcription via VoskKaldiSTT.execute() 2. Full listener pipeline via ovoscope get_mini_listener() Fixture: test/fixtures/command.wav — 16 kHz mono, speech "what time is it in london" The Vosk small-en model is downloaded once and cached under XDG_DATA...
OpenVoiceOS/ovos-stt-plugin-vosk
test/end2end/test_e2e_listener.py
.py
a6ed51998e2daf14
8.1
15
"""Module for handling API requests to CGHMC APIs.""" import asyncio import logging from http import HTTPStatus from typing import Any from aiohttp import ClientSession from compuglobal.api.endpoint import PreparedRequest, RequestMethod from compuglobal.errors import APIPageStatusError, MaximumRetriesExceededError ...
MitchellAW/CompuGlobal
compuglobal/api/client.py
.py
896a7d7588eb120a
7.57
13
"""The configuration for a CGHMC API (title + font).""" import dataclasses import logging from dataclasses import dataclass, field from compuglobal.models.font import FontFamily from compuglobal.models.overlay import OverlayFormat log = logging.getLogger(__name__) @dataclass class CompuGlobalAPIConfig: """The ...
MitchellAW/CompuGlobal
compuglobal/api/config.py
.py
789e7d75bce30232
7.57
13
"""All errors/exceptions returned by CompuGlobal APIs.""" from http import HTTPStatus class NoSearchResultsFoundError(Exception): """Raised when no search results are found.""" def __init__(self, message: str = "No search results found.") -> None: super().__init__(message) class MaximumRetriesExce...
MitchellAW/CompuGlobal
compuglobal/errors.py
.py
efd44f791ed012f0
7.57
13
"""Models for building a comic panel, or comic strip.""" import json from base64 import b64encode from enum import IntEnum, StrEnum from pydantic import Field, model_validator from compuglobal.models.base import BaseCompuGlobalModel from compuglobal.models.overlay import OverlayFormat from .font import FontAlignmen...
MitchellAW/CompuGlobal
compuglobal/models/comic.py
.py
70d7248e768a785e
7.57
13
"""Models used for representing an entire episode, or metadata/summaries of a TV episode.""" from pydantic import Field from compuglobal.models.base import BaseCompuGlobalModel from .subtitle import Subtitle class EpisodeMetadata(BaseCompuGlobalModel): """The metadata for an episode of a TV show. Attribut...
MitchellAW/CompuGlobal
compuglobal/models/episode.py
.py
6378e99ca2d452cc
7.57
13
"""Definitions for fonts and text in Comic/Stream overlays.""" from enum import StrEnum from pydantic import Field from compuglobal.models.base import BaseCompuGlobalModel class FontFamily(StrEnum): """An enumeration of font families.""" #: The impact font family IMPACT = "impact" #: The Comic Ne...
MitchellAW/CompuGlobal
compuglobal/models/font.py
.py
c0391c1db9df60a5
7.57
13