update bots

This commit is contained in:
2026-05-18 14:15:59 +07:00
parent b0ce866a2f
commit b9054d178e
5775 changed files with 832577 additions and 38 deletions

View File

@@ -0,0 +1,23 @@
from typing import List
def _digits_of(number: float) -> List[int]:
return [int(digit) for digit in str(number)]
def luhn_checksum(number: float) -> int:
digits = _digits_of(number)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = sum(odd_digits) + sum(sum(_digits_of(digit * 2)) for digit in even_digits)
return checksum % 10
def calculate_luhn(partial_number: float) -> int:
"""
Generates the Checksum using Luhn's algorithm
"""
check_digit = luhn_checksum(int(partial_number) * 10)
return check_digit if check_digit == 0 else 10 - check_digit

View File

@@ -0,0 +1,8 @@
from itertools import chain
from faker.typing import OrderedDictType
def add_ordereddicts(*odicts: OrderedDictType) -> OrderedDictType:
items = [odict.items() for odict in odicts]
return OrderedDictType(chain(*items))

View File

@@ -0,0 +1,38 @@
from functools import wraps
from typing import Callable, Dict, Tuple, TypeVar
from faker.utils import text
T = TypeVar("T")
def slugify(fn: Callable) -> Callable:
@wraps(fn)
def wrapper(*args: Tuple[T, ...], **kwargs: Dict[str, T]) -> str:
return text.slugify(fn(*args, **kwargs))
return wrapper
def slugify_domain(fn: Callable) -> Callable:
@wraps(fn)
def wrapper(*args: Tuple[T, ...], **kwargs: Dict[str, T]) -> str:
return text.slugify(fn(*args, **kwargs), allow_dots=True)
return wrapper
def slugify_unicode(fn: Callable) -> Callable:
@wraps(fn)
def wrapper(*args: Tuple[T, ...], **kwargs: Dict[str, T]) -> str:
return text.slugify(fn(*args, **kwargs), allow_unicode=True)
return wrapper
def lowercase(fn: Callable) -> Callable:
@wraps(fn)
def wrapper(*args: Tuple[T, ...], **kwargs: Dict[str, T]) -> str:
return fn(*args, **kwargs).lower()
return wrapper

View File

@@ -0,0 +1,88 @@
import bisect
import itertools
from random import Random
from typing import Generator, Iterable, Optional, Sequence, TypeVar
from faker.generator import random as mod_random
def random_sample(random: Optional[Random] = None) -> float:
if random is None:
random = mod_random
return random.uniform(0, 1.0)
def cumsum(it: Iterable[float]) -> Generator[float, None, None]:
total: float = 0
for x in it:
total += x
yield total
T = TypeVar("T")
def choices_distribution_unique(
a: Sequence[T],
p: Optional[Sequence[float]],
random: Optional[Random] = None,
length: int = 1,
) -> Sequence[T]:
# As of Python 3.7, there isn't a way to sample unique elements that takes
# weight into account.
if random is None:
random = mod_random
assert p is not None
assert len(a) == len(p)
assert len(a) >= length, "You can't request more unique samples than elements in the dataset."
choices = []
items = list(a)
probabilities = list(p)
for _ in range(length):
cdf = tuple(cumsum(probabilities))
normal = cdf[-1]
cdf2 = [i / normal for i in cdf]
uniform_sample = random_sample(random=random)
idx = bisect.bisect_right(cdf2, uniform_sample)
item = items[idx]
choices.append(item)
probabilities.pop(idx)
items.pop(idx)
return choices
def choices_distribution(
a: Sequence[T],
p: Optional[Sequence[float]],
random: Optional[Random] = None,
length: int = 1,
) -> Sequence[T]:
if random is None:
random = mod_random
if p is not None:
assert len(a) == len(p)
if hasattr(random, "choices"):
if length == 1 and p is None:
return [random.choice(a)]
else:
return random.choices(a, weights=p, k=length)
else:
choices = []
if p is None:
p = itertools.repeat(1, len(a)) # type: ignore
cdf = list(cumsum(p)) # type: ignore
normal = cdf[-1]
cdf2 = [i / normal for i in cdf]
for _ in range(length):
uniform_sample = random_sample(random=random)
idx = bisect.bisect_right(cdf2, uniform_sample)
item = a[idx]
choices.append(item)
return choices

View File

@@ -0,0 +1,60 @@
import pkgutil
import sys
from importlib import import_module
from pathlib import Path
from types import ModuleType
from typing import List
def get_path(module: ModuleType) -> str:
if getattr(sys, "frozen", False):
# frozen
if getattr(sys, "_MEIPASS", False):
# PyInstaller
lib_dir = Path(getattr(sys, "_MEIPASS"))
else:
# others
lib_dir = Path(sys.executable).parent / "lib"
path = lib_dir.joinpath(*module.__package__.split(".")) # type: ignore
else:
# unfrozen
if module.__file__ is not None:
path = Path(module.__file__).parent
else:
raise RuntimeError(f"Can't find path from module `{module}.")
return str(path)
def list_module(module: ModuleType) -> List[str]:
path = get_path(module)
if getattr(sys, "_MEIPASS", False):
# PyInstaller
return [file.parent.name for file in Path(path).glob("*/__init__.py")]
else:
return [name for _, name, is_pkg in pkgutil.iter_modules([str(path)]) if is_pkg]
def find_available_locales(providers: List[str]) -> List[str]:
available_locales = set()
for provider_path in providers:
provider_module = import_module(provider_path)
if getattr(provider_module, "localized", False):
langs = list_module(provider_module)
available_locales.update(langs)
return sorted(available_locales)
def find_available_providers(modules: List[ModuleType]) -> List[str]:
available_providers = set()
for providers_mod in modules:
if providers_mod.__package__:
providers = [
".".join([providers_mod.__package__, mod]) for mod in list_module(providers_mod) if mod != "__pycache__"
]
available_providers.update(providers)
return sorted(available_providers)

View File

@@ -0,0 +1,28 @@
import re
import unicodedata
from typing import Pattern
_re_pattern: Pattern = re.compile(r"[^\w\s-]", flags=re.U)
_re_pattern_allow_dots: Pattern = re.compile(r"[^\.\w\s-]", flags=re.U)
_re_spaces: Pattern = re.compile(r"[-\s]+", flags=re.U)
def slugify(value: str, allow_dots: bool = False, allow_unicode: bool = False) -> str:
"""
Converts to lowercase, removes non-word characters (alphanumerics and
underscores) and converts spaces to hyphens. Also strips leading and
trailing whitespace. Modified to optionally allow dots.
Adapted from Django 1.9
"""
pattern: Pattern = _re_pattern_allow_dots if allow_dots else _re_pattern
value = str(value)
if allow_unicode:
value = unicodedata.normalize("NFKC", value)
value = pattern.sub("", value).strip().lower()
return _re_spaces.sub("-", value)
value = unicodedata.normalize("NFKD", value).encode("ascii", "ignore").decode("ascii")
value = pattern.sub("", value).strip().lower()
return _re_spaces.sub("-", value)