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 |
|---|---|---|---|---|---|---|
"""
see: https://gist.github.com/smhanov/94230b422c2100ae4218
"""
class DAWGNode(object):
"""
This class represents a node in the directed acyclic word graph (DAWG).
It has a list of edges to other nodes.
It has functions for testing whether it is equivalent to another node.
Nodes are equivalent i... | averykhoo/ngram-movers-distance | experiments/dawg.py | .py | fa22cb8b875203cb | 7 | 0 |
from typing import Dict
from typing import Iterable
from typing import List
from typing import Tuple
from typing import Union
import scipy.optimize
from nmd.emd_1d import emd_1d_fast
def _n_gram_locations(word: str, n: int) -> Tuple[Dict[str, List[float]], int]:
"""
n_gram -> [normalized position, ...] for ... | averykhoo/ngram-movers-distance | nmd/nmd_bow.py | .py | b05287939d32d100 | 7 | 0 |
"""
Tests for Earth Mover's Distance (EMD) implementations.
This file contains tests converted from the original correctness-test.py
in the experiments directory.
"""
import itertools
import math
import pytest
from typing import List, Sequence, Union
from nmd.emd_1d import emd_1d_dp
from nmd.emd_1d import emd_1d_hybr... | averykhoo/ngram-movers-distance | tests/test_emd_correctness.py | .py | f7fae8987c23b15b | 7.5 | 0 |
"""
Tests for the Trie implementation in find_replace_trie.py.
This file contains tests converted from the self_test function in find_replace_trie.py.
"""
import random
import re
import pytest
# Import the Trie class from the experiments module
from experiments.find_replace_trie import Trie
class TestTrie:
"""T... | averykhoo/ngram-movers-distance | tests/test_find_replace_trie.py | .py | 8864b1f5e8e274e9 | 7.5 | 0 |
import copy
import itertools
import os
import pathlib
import time
from contextlib import contextmanager
from fractions import Fraction
import moment
from exifinder.conf import config
from exifinder.log import error, info
def error_log(target="", default=None, raise_err=False, raise_exit=False):
def decorator(fu... | s045pd/exif-finder | exifinder/common.py | .py | a1a8db868b5338a6 | 7.24 | 2 |
#!/usr/bin/env python3
"""Record membership of the DELVE Milky Way Census I in the Local Group satellite database.
The DELVE Milky Way Census I (Tan, Drlica-Wagner et al. 2025; arXiv:2509.12313) defines a sample of
Milky Way satellites recovered above a uniform detection threshold across the combined footprints of
DES... | galacticusorg/datasets | static/observations/localGroup/localGroupSatellitesCensusUpdate.py | .py | c1220debed34e372 | 7 | 0 |
#!/usr/bin/env python3
"""Generate random points within the angular mask of the UKIDSS UDS survey.
Construct a set of random points that lie within the angular mask of the UKIDSS UDS sample
used by Caputi et al. (2011; http://adsabs.harvard.edu/abs/2011MNRAS.413..162C). The mask
is defined by a set of boundaries, plus... | galacticusorg/datasets | static/surveyGeometry/UKIDSS_UDS/surveyGeometryRandoms.py | .py | 1a2706b8619ef416 | 7 | 0 |
from abc import ABC, abstractmethod
import base64
import datetime
import requests
from .config import Config
from .consts import MWS_TOKEN, MWSV2_TOKEN
from .exceptions import InauthenticError, MAuthNotPresent, MissingV2Error, UnableToAuthenticateError
from .lambda_helper import generate_mauth
from .rsa_verifier import... | mdsol/mauth-client-python | mauth_client/authenticator.py | .py | 5bbfc4d3c2385a64 | 7.15 | 1 |
import httpx
from mauth_client.config import Config
from mauth_client.signable import RequestSignable
from mauth_client.signer import Signer
class MAuthHttpx(httpx.Auth):
"""
HTTPX authentication for MAuth.
Adds MAuth headers based on method, URL, and body bytes.
"""
# We need the body bytes to s... | mdsol/mauth-client-python | mauth_client/httpx_mauth/client.py | .py | 4e160d3bd94cf343 | 7.15 | 1 |
import json
import logging
from asgiref.typing import (
ASGI3Application,
ASGIReceiveCallable,
ASGIReceiveEvent,
ASGISendCallable,
Scope,
)
from typing import List, Tuple, Optional
from mauth_client.authenticator import LocalAuthenticator
from mauth_client.config import Config
from mauth_client.co... | mdsol/mauth-client-python | mauth_client/middlewares/asgi.py | .py | db072c0bb3892cfb | 7.15 | 1 |
import io
import json
import logging
from urllib.parse import quote
from mauth_client.authenticator import LocalAuthenticator
from mauth_client.config import Config
from mauth_client.consts import (
ENV_APP_UUID,
ENV_AUTHENTIC,
ENV_PROTOCOL_VERSION,
)
from mauth_client.signable import RequestSignable
fro... | mdsol/mauth-client-python | mauth_client/middlewares/wsgi.py | .py | 95279a0c08340a00 | 7.15 | 1 |
import requests
from mauth_client.config import Config
from mauth_client.signable import RequestSignable
from mauth_client.signer import Signer
class MAuth(requests.auth.AuthBase):
"""
Custom requests authorizer for MAuth
"""
def __init__(
self,
app_uuid=Config.APP_UUID,
priva... | mdsol/mauth-client-python | mauth_client/requests_mauth/client.py | .py | 9b0ff89c7dc0fccf | 7.15 | 1 |
# This module exists to reproduce, with the rsa library, the raw signature required by MAuth
# which in OpenSSL is created with private_encrypt(hash). It provides an RSA sign class built from
# code that came from https://www.dlitz.net/software/pycrypto/api/current/ no copyright of that original
# code is claimed.
imp... | mdsol/mauth-client-python | mauth_client/rsa_signer.py | .py | c80a9202a5eda579 | 7.15 | 1 |
import base64
import rsa
from .exceptions import UnableToAuthenticateError
from .key_holder import KeyHolder
from .utils import make_bytes, hexdigest
class RSAVerifier:
"""
Wrapper of the rsa library for verifying
"""
def __init__(self, app_uuid):
"""
:param app_uuid:
"""
... | mdsol/mauth-client-python | mauth_client/rsa_verifier.py | .py | f34b446866025ae5 | 7.15 | 1 |
from abc import ABC, abstractmethod
import posixpath
import re
from urllib.parse import quote, unquote_plus, urlparse
from .utils import hexdigest, make_bytes
from .exceptions import UnableToSignError
class Signable(ABC):
"""
Makes a signature string to sign
"""
def __init__(self, **kwargs):
... | mdsol/mauth-client-python | mauth_client/signable.py | .py | bc320fa8b188c6fb | 7.15 | 1 |
import time
import re
from .rsa_signer import RSASigner
from .consts import AUTH_HEADER_DELIMITER, MWS_TOKEN, X_MWS_AUTH, X_MWS_TIME, MWSV2_TOKEN, MCC_AUTH, MCC_TIME
from .utils import base64_encode
class Signer:
"""
methods to sign requests.
"""
def __init__(self, app_uuid, private_key_data, sign_ve... | mdsol/mauth-client-python | mauth_client/signer.py | .py | 2ae34d3cfa0eaa85 | 7.15 | 1 |
import base64
import charset_normalizer
import re
from hashlib import sha512
HEADER = '-----BEGIN RSA PRIVATE KEY-----'
FOOTER = '-----END RSA PRIVATE KEY-----'
PKCS8_HEADER = '-----BEGIN PRIVATE KEY-----'
PKCS8_FOOTER = '-----END PRIVATE KEY-----'
SUPPORTED_PRIVATE_KEY_FORMATS = (
(HEADER, FOOTER),
(PKCS8_HEA... | mdsol/mauth-client-python | mauth_client/utils.py | .py | 2c42b9bb63ccb6c4 | 7.15 | 1 |
import itertools
Preferences = dict[str, dict[str, int]]
def build_prefs(pref_str_list: list[str]) -> Preferences:
"""Save attendee seating preferences"""
prefs: Preferences = {}
# Save attendee preferences
for pref in pref_str_list:
name, _, impact, count, *_, neighbor = pref.split()
... | cj81499/advent-of-code | src/aoc_cj/aoc2015/day13.py | .py | 8abc387cebc49d7b | 7.39 | 5 |
import itertools
import re
import lark
import more_itertools as mi
ELEMENT_PATTERN = re.compile(r"[A-Z][a-z]*")
import dataclasses
@dataclasses.dataclass(frozen=True)
class Replacement:
input: str
output_molecule: str
output_elements: tuple[str]
@staticmethod
def parse(txt: str) -> "Replaceme... | cj81499/advent-of-code | src/aoc_cj/aoc2015/day19.py | .py | c114fd8d047d3be1 | 7.39 | 5 |
import hashlib
import itertools
from collections.abc import Callable, Generator
import more_itertools as mi
REQUIRED_KEYS = 64
def n_repeat_character(s: str, n: int) -> str | None:
"""Return the first character in `s` that occurs `n` (or more) times in a row, or `None` if no such character exists."""
return... | cj81499/advent-of-code | src/aoc_cj/aoc2016/day14.py | .py | c1fe5a2d15c9e36a | 7.39 | 5 |
"""
Print the current devices as JSON without loading any other part of recs.
"""
import json
import time
from typing import Any
STREAM_INTERVAL = 0.1
def devices_json() -> str:
return json.dumps(_query_devices(), indent=4)
def stream_devices() -> None:
while True:
print(json.dumps(_query_devices(... | rec/recs | recs/base/_query_device.py | .py | fcb4093c9a7a1069 | 7.39 | 5 |
import math
from functools import cached_property
from typing import Generic, TypeVar, cast
from pydantic import BaseModel, ConfigDict, model_validator
from typing_extensions import Self
T = TypeVar('T', float, int)
NO_SCALE = ('noise_floor', 'record_everything')
def db_to_amplitude(db: float) -> float:
return ... | rec/recs | recs/cfg/time_settings.py | .py | 9f9f0f4840f1a8f8 | 7.39 | 5 |
import base64
import enum
import decimal
import re
import requests
import requests.adapters
from requests.exceptions import ChunkedEncodingError, ContentDecodingError
from typing import Any, Optional, Dict, Callable, Generic, TypeVar, Union
from urllib.parse import quote
T = TypeVar("T")
def encode(value) -> str:
... | FacilityApi/FacilityPython | src/facility.py | .py | 32e5e9ddfe7ab133 | 7 | 0 |
# SPDX-FileCopyrightText: 2020 CERN.
# SPDX-License-Identifier: MIT
"""CLI module."""
from functools import update_wrapper
from pathlib import Path
import click
from .config import SERVICE_TYPES
from .env import (
normalize_service_name,
override_default_env,
print_setup_env_config,
set_env,
)
from ... | inveniosoftware/docker-services-cli | docker_services_cli/cli.py | .py | 0970b9f55ab2d884 | 7 | 0 |
# SPDX-FileCopyrightText: 2020 CERN.
# SPDX-FileCopyrightText: 2024 Graz University of Technology.
# SPDX-FileCopyrightText: 2025 CESNET z.s.p.o.
# SPDX-License-Identifier: MIT
"""Environment module."""
import logging
import os
import sys
from distutils.version import StrictVersion
import click
from .config import ... | inveniosoftware/docker-services-cli | docker_services_cli/env.py | .py | ec82e0b9827edde3 | 7 | 0 |
# SPDX-FileCopyrightText: 2020 CERN.
# SPDX-License-Identifier: MIT
"""Module tests."""
import os
import pytest
from docker_services_cli.config import SERVICES
from docker_services_cli.env import (
_is_version,
_load_or_set_env,
override_default_env,
set_env,
)
def test_is_version():
assert _i... | inveniosoftware/docker-services-cli | tests/test_env.py | .py | 992217b907c6417a | 7.5 | 0 |
from __future__ import annotations
from datetime import date, datetime
from enum import Enum
from typing import Any
from ena_api_handler.models import ENAPortalResultType
from ena_api_handler.query import ENABaseQuery, ENAQueryClause, ENARawQuery
from ena_api_handler.types import ENAPortalDataPortal
CONVENIENCE_PORT... | EBI-Metagenomics/ena-api-handler | src/ena_api_handler/_convenience.py | .py | 90c58185b308fea7 | 7.15 | 1 |
"""initial PartIQ Vision schema
Revision ID: 20260825_0001
Revises:
Create Date: 2026-08-25
"""
from alembic import op
revision = "20260825_0001"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute("CREATE EXTENSION IF NOT EXISTS vector")
op.execute("CREATE EXTENS... | IncredibleJoy/Joy | backend/alembic/versions/20260825_0001_initial_schema.py | .py | 113f358b99bf21f4 | 7 | 0 |
"""add token usage tracking
Revision ID: 20260825_0002
Revises: 20260825_0001
Create Date: 2026-08-25
"""
from alembic import op
revision = "20260825_0002"
down_revision = "20260825_0001"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.get_bind().exec_driver_sql(
"""
ALTER TAB... | IncredibleJoy/Joy | backend/alembic/versions/20260825_0002_token_usage.py | .py | 4bc748629acce61b | 7 | 0 |
# MenuTitle: Editar Rename Glyphs
# -*- coding: utf-8 -*-
__doc__="""
Edita o Rename Glyphs em uma ou
mais instâncias ao mesmo tempo
"""
import vanilla
from GlyphsApp import Glyphs, GSInstance
class RenameGlyphsBatchEditor(object):
def __init__(self):
self.font = Glyphs.font
if not self.font:
Glyphs.showNoti... | diegommaldo/Glyphs3-Scripts | Production/EditarRenameGlyphs.py | .py | 83d187d256d98b99 | 7.15 | 1 |
from django.contrib.admin import SimpleListFilter
class JSONFieldFilter(SimpleListFilter):
"""
Base JSONFilter class to use by individual attribute filter classes.
"""
model_json_field_name = None # name of the json field column in the model
json_data_property_name = None # name of one attribut... | C2DH/journal-of-digital-history-backend | jdhapi/filter/languagetagfilter.py | .py | 06c2616c1d8fd569 | 7.35 | 4 |
from django.core.management.base import BaseCommand, CommandError
from jdhapi.tasks import send_confirmation
class Command(BaseCommand):
"""
usage:
ENV=development pipenv run ./manage.py celery_test
or if in docker:
docker exec -it docker_miller_1 \
python manage.py celery_test
"""
def... | C2DH/journal-of-digital-history-backend | jdhapi/management/commands/celery-test.py | .py | 227920066b2872a1 | 7.85 | 4 |
import json
from django.core.management.base import BaseCommand, CommandError
from jdhapi.models import Article
from jdhapi.utils.articles import get_notebook_stats
class Command(BaseCommand):
"""
usage:
pipenv run ./manage.py fingerprint <article_id>
or if in our docker:
docker exec -it journal-d... | C2DH/journal-of-digital-history-backend | jdhapi/management/commands/fingerprint.py | .py | 4c93926ef218aa57 | 7.35 | 4 |
from django import forms
from django.contrib import admin
from django.contrib.admin import TabularInline, register
from django.contrib.auth import get_user_model
from django.contrib.gis.admin import GISModelAdmin
from django.utils.translation import gettext_lazy as _
from common.widgets import HaravaOSMWidget
from .m... | City-of-Helsinki/haravajarjestelma | areas/admin.py | .py | 51cb1bdbb31d5d60 | 7 | 0 |
import logging
logger = logging.getLogger(__name__)
class ModelSyncher:
def __init__(self, queryset, generate_obj_id, delete_func=None, force=False):
d = {}
self.generate_obj_id = generate_obj_id
# Generate a list of all objects
for obj in queryset:
d[generate_obj_id(o... | City-of-Helsinki/haravajarjestelma | areas/importer/utils.py | .py | 6222a21afb717fc5 | 7 | 0 |
from datetime import timedelta
import pytest
from django.db import IntegrityError
from django.utils.timezone import localtime, now
from events.factories import EventFactory
from ..factories import BlockedDateFactory, ContractZoneFactory
@pytest.fixture
def contract_zone():
return ContractZoneFactory()
def te... | City-of-Helsinki/haravajarjestelma | areas/tests/test_blocked_date.py | .py | d3caff50469a25db | 7.5 | 0 |
from django.conf import settings
from django.contrib.gis.forms import OSMWidget
class HaravaOSMWidget(OSMWidget):
"""OSM map widget centred on Helsinki railway station with 3D geometry support.
Uses Helsinki city raster tiles (maptiles.api.hel.fi) instead of the
default tile.openstreetmap.org. This fixe... | City-of-Helsinki/haravajarjestelma | common/widgets.py | .py | f5a981d6e7d5d38c | 7 | 0 |
from datetime import datetime, timedelta
from typing import Any
from django.conf import settings
from django.utils import timezone
from django.utils.timezone import localtime
from django.utils.translation import gettext_lazy as _
from django_filters import rest_framework as filters
from rest_framework import serialize... | City-of-Helsinki/haravajarjestelma | events/api.py | .py | 3b4215654599a5e0 | 7 | 0 |
"""Management command to anonymize old Event PII."""
import logging
import os
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone
from events.models import Event
logger = logging.getLogger(__name__)
# Sentinel value... | City-of-Helsinki/haravajarjestelma | events/management/commands/obfuscate_events.py | .py | aeb7b013c5ab4dc8 | 7 | 0 |
"""
Management command to send approval reminder notifications to contractors.
This command should be run daily via a scheduled task (e.g., cron job).
It sends reminders to contractors about pending events that need approval,
based on two independent triggers:
1. Creation-based: X days after the event was created (sh... | City-of-Helsinki/haravajarjestelma | events/management/commands/send_approval_reminder_notifications.py | .py | 490668a5e9b7f6fe | 7 | 0 |
import os
import logging
import subprocess
import tempfile
import shutil
import contextlib
import pystache
from pystache.parser import _EscapeNode # pylint: disable=protected-access
import git
logger = logging.getLogger('gitoo-definition')
logger.setLevel(logging.INFO)
@contextlib.contextmanager
def temp_repo(url,... | Numigi/gitoo | src/gitoo/core.py | .py | e720a1b1cdc185bd | 7.39 | 5 |
from __future__ import print_function, absolute_import
import unittest
import git
import functools
import os
import mock
from .. import core
class TestTempRepo(unittest.TestCase):
def setUp(self):
super(TestTempRepo, self).setUp()
self.repo_url = "https://github.com/pytest-dev/pytest"
s... | Numigi/gitoo | src/gitoo/tests/test_core.py | .py | 74ae48c92428bea7 | 7.89 | 5 |
#!/usr/bin/env python3
"""Generate a Keep-a-Changelog-formatted markdown block from git conventional commits.
Usage:
python scripts/generate_changelog.py # since last tag
python scripts/generate_changelog.py --base-tag v1.9.14
"""
from __future__ import annotations
import argparse
import re
import... | docdyhr/pigame | scripts/generate_changelog.py | .py | a9774177bf8a7e5e | 7 | 0 |
# !/usr/bin/env python3
"""Tests for the practice mode of pigame."""
import json
import sys
import tempfile
from pathlib import Path
from unittest import mock
import pytest
# Add the src directory to the path for importing pigame
sys.path.insert(0, str(Path(__file__).parent.parent / "src" / "python"))
import pigame... | docdyhr/pigame | tests/test_practice_mode.py | .py | ff81b68ee15421b3 | 7.5 | 0 |
#!/usr/bin/env python3
"""Unit tests for the pigame Python implementation."""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
# Add parent directory to path so we can import the src module
sys.path.insert(0, Path(__file__).parent.resolve().parent.as_posix())
from src.python imp... | docdyhr/pigame | tests/test_python_unit.py | .py | 3701aac5c228122d | 7.5 | 0 |
"""
autonerves — configuration, serialization, and I/O helpers for the PyAuto ecosystem.
Text-format I/O surfaces:
- :mod:`autonerves.dictable` — JSON (``output_to_json`` / ``from_json``)
- :mod:`autonerves.fitsable` — FITS (``output_to_fits`` / ``ndarray_via_fits_from``)
- :mod:`autonerves.csvable` — CSV (``out... | PyAutoLabs/PyAutoNerves | autonerves/__init__.py | .py | 29d168ba7c3cd613 | 7.24 | 2 |
import builtins
import importlib
import re
from typing import List, Type
def get_class_path(cls: type) -> str:
"""
The full import path of the type
"""
if hasattr(cls, "__class_path__"):
cls = cls.__class_path__
return re.search("'(.*)'", str(cls))[1]
def get_class(class_path: str) -> Ty... | PyAutoLabs/PyAutoNerves | autonerves/class_path.py | .py | d9794bd10cd875e7 | 7.24 | 2 |
"""
Generic CSV reader/writer helpers for the PyAuto ecosystem.
Sits alongside :mod:`autonerves.dictable` (JSON) and :mod:`autonerves.fitsable`
(FITS) as the third text-format I/O surface. The functions here are schema
agnostic — callers layer their own column conventions on top (see e.g.
``autolens.point.dataset`` fo... | PyAutoLabs/PyAutoNerves | autonerves/csvable.py | .py | d615b062e42ad32f | 7.24 | 2 |
import inspect
import json
import logging
import os
import numpy as np
from pathlib import Path
from typing import Union, Callable, Set, Tuple
from autonerves.class_path import get_class_path, get_class
logger = logging.getLogger(__name__)
np_type_map = {
"bool": "bool_",
}
def nd_array_as_dict(obj: np.ndarra... | PyAutoLabs/PyAutoNerves | autonerves/dictable.py | .py | a2fca68e9b5fdf27 | 7.24 | 2 |
from __future__ import annotations
from enum import Enum
from typing import TYPE_CHECKING
if TYPE_CHECKING:
try:
from astropy.io import fits
except ImportError:
pass
import numpy as np
from pathlib import Path
from typing import Dict, Optional, Union, List
# Exactly 8 characters, and that c... | PyAutoLabs/PyAutoNerves | autonerves/fitsable.py | .py | cbd66c039149b2bd | 7.24 | 2 |
import importlib.util
import logging
logger = logging.getLogger(__name__)
import os
if importlib.util.find_spec("jax") is None:
logger.warning(
"""
JAX is not installed, so all computations will run on the pure NumPy
path. Performance is significantly reduced without JAX — model fits
... | PyAutoLabs/PyAutoNerves | autonerves/jax_wrapper.py | .py | b9bf6802682a1752 | 7.24 | 2 |
import inspect
import json
import logging
from collections.abc import Sized
from pathlib import Path
from typing import List, Type, Tuple
import yaml
from autonerves.directory_config import family
logger = logging.getLogger(__name__)
default_prior = {
"type": "Uniform",
"lower_limit": 0.0,
"upper_limit"... | PyAutoLabs/PyAutoNerves | autonerves/json_prior/config.py | .py | 5c3f9c3aab7258c4 | 7.24 | 2 |
class Redshift:
def __init__(self, redshift=0.0):
self.redshift = redshift
class SphProfile:
def __init__(self, centre=(0.0, 0.0)):
"""Generic circular profiles class to contain functions shared by light and
mass profiles.
Parameters
----------
centre
... | PyAutoLabs/PyAutoNerves | autonerves/mock/mock_real.py | .py | 785dafb610c68748 | 7.24 | 2 |
from functools import wraps
from typing import Callable
import logging
from autonerves.conf import instance
logger = logging.getLogger(__name__)
def should_output(name: str) -> bool:
"""
Determine whether a file with a given name (excluding extension) should be output.
This is configured in config/outp... | PyAutoLabs/PyAutoNerves | autonerves/output.py | .py | c0f0dda56f94254a | 7.24 | 2 |
"""
Google Colab bootstrap for the PyAuto ecosystem.
Every notebook generated by PyAutoHands begins with a setup cell that calls
``setup_colab.setup("<project>")``. Outside Colab the call is a no-op (it
prints a short confirmation and returns), so the same notebook runs unchanged
locally and on Colab.
On Colab, ``set... | PyAutoLabs/PyAutoNerves | autonerves/setup_colab.py | .py | f5cd61d1b264931b | 7.24 | 2 |
import os
from pathlib import Path
def setup_notebook():
"""
Set up a Jupyter notebook to run from the workspace root.
Finds the workspace root by walking up from the current directory
looking for a ``config`` directory (the marker for a PyAuto workspace),
changes to it, reconfigures autonerves p... | PyAutoLabs/PyAutoNerves | autonerves/setup_notebook.py | .py | e379c8b7a6b9f026 | 7.24 | 2 |
import os
from pathlib import Path
def test_mode_level():
"""
Return the current test mode level.
0 = off (normal operation)
1 = reduce sampler iterations to minimum (existing behavior)
2 = bypass sampler entirely, call likelihood once
3 = bypass sampler entirely, skip likelihood call
"""... | PyAutoLabs/PyAutoNerves | autonerves/test_mode.py | .py | bac7140a353c1598 | 7.74 | 2 |
import functools
import numpy as np
class CachedProperty(object):
"""
A property that is only computed once per instance and then replaces
itself with an ordinary attribute. Deleting the attribute resets the
property.
Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f5... | PyAutoLabs/PyAutoNerves | autonerves/tools/decorators.py | .py | b2f3e17752e007f8 | 7.24 | 2 |
import datetime
import os
import warnings
from pathlib import Path
from autonerves import exc
class WorkspaceVersionMismatchError(exc.ConfigException):
pass
_BYPASS_ENV_VAR = "PYAUTO_SKIP_WORKSPACE_VERSION_CHECK"
# The installed library may legitimately run ahead of a workspace clone —
# releases are frequent... | PyAutoLabs/PyAutoNerves | autonerves/workspace.py | .py | 3bcbc567ed6c916a | 7.24 | 2 |
import pathlib
import pytest
from autonerves import conf
@pytest.fixture(scope="session", name="files_directory")
def make_files_directory():
return pathlib.Path(__file__).parent / "files"
@pytest.fixture(scope="session", name="session_config")
def make_session_config(files_directory):
return conf.Config(... | PyAutoLabs/PyAutoNerves | test_autonerves/conftest.py | .py | 955dbf94c81a6c5e | 7.74 | 2 |
import pytest
from astropy.io import fits
import numpy as np
import os
from pathlib import Path
from autonerves import conf
from autonerves import fitsable
test_path = Path(__file__).resolve().parent
test_data_path = Path(__file__).resolve().parent / "files"
def create_fits(fits_path, array):
fits_path = Path... | PyAutoLabs/PyAutoNerves | test_autonerves/test_fitsable.py | .py | e4008586d3e4cd98 | 7.74 | 2 |
import subprocess
import sys
import types
from unittest import mock
import pytest
from autonerves import setup_colab
class FakeDevice:
def __init__(self, kind):
self.kind = kind
def __str__(self):
return self.kind
@pytest.fixture(name="fake_jax")
def make_fake_jax(monkeypatch):
"""
... | PyAutoLabs/PyAutoNerves | test_autonerves/test_setup_colab.py | .py | bfed1136f6877807 | 7.74 | 2 |
"""Tests for autonerves.test_mode helpers — focused on
``with_test_mode_segment`` since the other helpers (``is_test_mode``,
``skip_fit_output``, etc.) are exercised by PyAutoFit/PyAutoArray
integration tests downstream."""
import os
from pathlib import Path
import pytest
from autonerves.test_mode import (
is_te... | PyAutoLabs/PyAutoNerves | test_autonerves/test_test_mode.py | .py | 86b8352cb3ad4e4a | 7.74 | 2 |
from typing import ClassVar
from directory_client_core.base import AbstractAPIClient
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from directory_forms_api_client import __version__
class APIFormsClient(AbstractAPIClient):
endpoints: ClassVar[dict[str, str]] = {
... | uktrade/directory-forms-api-client | directory_forms_api_client/client.py | .py | a0f2a7f6713e2251 | 7 | 0 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2016 Wikimedia Foundation
import manhole
import os.path
import tempfile
from shutil import which
import thumbor.engines
from thumbor.utils import logger
from thumbor.handlers... | wikimedia/operations-software-thumbor-plugins | wikimedia_thumbor/app.py | .py | 91ee1917b09a4a21 | 7.24 | 2 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
import os
import yaml
import ahjo.util.jsonc as json
from pathlib import Path
from pydantic import BaseModel, ConfigDict, FilePath, ValidationError
from typing import Optional
class Config:
""... | ALMPartners/ahjo | src/ahjo/config.py | .py | ea0f76527b74cd3c | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
import os
import sys
from logging import getLogger
from typing import Union, Any
from sqlalchemy.engine import Engine, Connection
from ahjo.database_utilities import (
create_conn_info,
create... | ALMPartners/ahjo | src/ahjo/context.py | .py | 0e0ce946fb77c840 | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
"""Password information handling."""
import getpass
from base64 import b64decode, b64encode
from logging import getLogger
from pathlib import Path
from typing import Tuple, Union
logger = getLogger("... | ALMPartners/ahjo | src/ahjo/credential_handler.py | .py | 9c409723583f2c48 | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
"""Utily for extracting connection info from configuration json."""
import importlib
from logging import getLogger
from typing import Union
from ahjo.credential_handler import get_credentials
from sql... | ALMPartners/ahjo | src/ahjo/database_utilities/conn_info.py | .py | dc93cd7a85751147 | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
"""Utility functions for executing tsql using sqlcmd.exe"""
from logging import getLogger
from re import search
from subprocess import PIPE, Popen, list2cmdline
from typing import Union
logger = getL... | ALMPartners/ahjo | src/ahjo/database_utilities/sqlcmd.py | .py | ecc856d12e2a0638 | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
from logging import getLogger
from re import sub, compile as re_compile
from typing import Iterable, List, Union
from ahjo.config import Config
logger = getLogger("ahjo")
# Matches ANSI escape sequ... | ALMPartners/ahjo | src/ahjo/interface_methods.py | .py | b06f97f81d4a371b | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
import os
import sys
import ahjo
from logging.config import fileConfig, dictConfig
from logging import getLogger
from ahjo.context import Context
from ahjo.logging.db_logger import load_log_table
from... | ALMPartners/ahjo | src/ahjo/logging/__init__.py | .py | b038c495ec98f976 | 7.35 | 4 |
import logging
import logging.config
class ColoredFormatter(logging.Formatter):
"""Custom formatter to add colors to log messages."""
COLORS = {
"DEBUG": "\033[94m", # Blue
"INFO_DEFAULT": "\033[97m", # White (default INFO)
"INFO_HEADER": "\033[1;36m", # Blue
"INFO_SUCCESS"... | ALMPartners/ahjo | src/ahjo/logging/console_formatter.py | .py | 96f540d31f173bc3 | 7.35 | 4 |
import logging
import re
class DatabaseFormatter(logging.Formatter):
"""Formatter for database logging."""
def __init__(self):
"""Constructor for DatabaseFormatter class."""
super().__init__()
def format(self, record):
"""Format the log record.
Arguments:
-------... | ALMPartners/ahjo | src/ahjo/logging/db_formatter.py | .py | a6843ffe5a34f5f8 | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
import logging
from ahjo.context import Context
from subprocess import check_output
from ahjo.logging.db_logger import DatabaseLogger
from sqlalchemy import Table
class DatabaseHandler(logging.Handl... | ALMPartners/ahjo | src/ahjo/logging/db_handler.py | .py | b1356d8715afb4f2 | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
from ahjo.context import Context
from datetime import datetime
from sqlalchemy import Column, MetaData, String, Table, DateTime, func, Integer
from sqlalchemy.exc import NoSuchTableError
from sqlalche... | ALMPartners/ahjo | src/ahjo/logging/db_logger.py | .py | 5052af830b14557f | 7.35 | 4 |
from logging import Handler, LogRecord
import win32evtlog
import win32evtlogutil
import re
class winEventHandler(Handler):
"""
Custom logging handler for sending messages to Windows Event Log.
"""
def __init__(self):
Handler.__init__(self)
def emit(self, x: LogRecord):
"""
... | ALMPartners/ahjo | src/ahjo/logging/win_event_logger.py | .py | 545d7cfa7a2ac3f6 | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
"""Module for logging, printing and error handling deployment process."""
from datetime import datetime
from logging import getLogger
from traceback import format_exception
logger = getLogger("ahjo"... | ALMPartners/ahjo | src/ahjo/operation_manager.py | .py | 2d44443a9d4ca359 | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
"""Module for Alembic related operations"""
from argparse import Namespace
from logging import getLogger
from os import path
from ahjo.context import AHJO_PATH
from ahjo.interface_methods import rear... | ALMPartners/ahjo | src/ahjo/operations/general/alembic.py | .py | a1a9edcddd1e7a2c | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
"""Bulk insert with SQL Alchemy Core."""
from logging import getLogger
from time import time
from typing import Generator, Optional
from sqlalchemy import Table, event
from sqlalchemy.engine import ... | ALMPartners/ahjo | src/ahjo/operations/general/bulk_insert.py | .py | 9e4423c2463b97e4 | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
"""Module for comparing data from two dataframes and reporting differences."""
from logging import getLogger
from pathlib import Path
import time
try:
import polars as pl
except:
pl = None
... | ALMPartners/ahjo | src/ahjo/operations/general/compare.py | .py | 95aba6fd5c6f088d | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
"""Module for Git operations."""
import os
from logging import getLogger
from shlex import split
from subprocess import check_output, run
from typing import Tuple, Union
from ahjo.interface_methods i... | ALMPartners/ahjo | src/ahjo/operations/general/git_version.py | .py | 73a0e2ab9a416e96 | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
"""Initialize operations.
Includes functions for creating local configuration file and a new project.
Global variable PROJECT_STRUCTURE is a dictionary holding information about project file structur... | ALMPartners/ahjo | src/ahjo/operations/general/initialization.py | .py | 71dccfd979628e26 | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
"""Module for database drop and create.
Global variable QUERIES holds SQL select statements to
retrieve session and database ids from database."""
from os import path
from typing import Union
from lo... | ALMPartners/ahjo | src/ahjo/operations/tsql/create_db.py | .py | a466204b4f5780a3 | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
"""Operations for loading and printing database information."""
from logging import getLogger
from ahjo.context import Context
from ahjo.operation_manager import format_message
from sqlalchemy.sql im... | ALMPartners/ahjo | src/ahjo/operations/tsql/db_info.py | .py | 51be1c9db543f0cd | 7.35 | 4 |
# Ahjo - Database deployment framework
#
# Copyright 2019 - 2026 ALM Partners Oy
# SPDX-License-Identifier: Apache-2.0
"""
Operations for SET statements.
"""
from ahjo.operation_manager import OperationManager
from ahjo.database_utilities import execute_query
from sqlalchemy.engine import Engine
def xact_abort_and_... | ALMPartners/ahjo | src/ahjo/operations/tsql/set_statements.py | .py | ef894e5e2665cd59 | 7.35 | 4 |
"""Wrapper for interacting with the currencylayer API."""
import logging
from typing import Any
import httpx
from . import exceptions
_LOGGER = logging.getLogger(__name__)
_RESOURCE = "http://apilayer.net/api/live"
class CurrencyLayer(object):
"""A class for handling the data retrieval."""
def __init__(
... | home-assistant-ecosystem/aiocurrencylayer | aiocurrencylayer/__init__.py | .py | 296040c3a4cbb70b | 7.24 | 2 |
"""Test the interaction with the currencylayer API."""
import pytest
from pytest_httpx import HTTPXMock
from aiocurrencylayer import CurrencyLayer
import httpx
API_KEY = "YOUR_API_KEY"
QUOTE = "ZMW"
SOURCE = "USD"
RESPONSE_VALID = {
"success": True,
"terms": "https://currencylayer.com/terms",
"privacy":... | home-assistant-ecosystem/aiocurrencylayer | tests/test_connection.py | .py | 2a7c69014e3793c6 | 7.74 | 2 |
# Create your models here.
from copy import deepcopy
from django.db import models
from django.utils.translation import gettext_lazy as _
from audit_log.managers import AuditLogManager
from common.models import TimestampedModel, UUIDPrimaryKeyModel
class DeliveryLog(UUIDPrimaryKeyModel, TimestampedModel):
user =... | City-of-Helsinki/notification-service-api | api/models.py | .py | a7d9fc6164598885 | 7 | 0 |
from datetime import datetime
from unittest import mock
import pytest
from dateutil.relativedelta import relativedelta
from django.core.management import call_command
from django.db import IntegrityError
from freezegun import freeze_time
from api.factories import DeliveryLogFactory
from api.models import DeliveryLog
... | City-of-Helsinki/notification-service-api | api/tests/test_prune_delivery_log.py | .py | be57b15baeefaa86 | 7.5 | 0 |
import pytest
from api.utils import filter_valid_destinations, validate_send_message_payload
REGION_FI_VALID_PHONE_NUMBERS = [
"+358 40 123 4567",
"00358 40 123 4567",
"+358 50 123 4567",
"+358 5 0 1 2 3 4 5 6 7",
"+358 5 0 123 4 56 7",
"040 123 4567",
"041 123 4567",
"050 123 4567",
... | City-of-Helsinki/notification-service-api | api/tests/test_utils.py | .py | 5e3929cc6c834f9f | 7.5 | 0 |
import logging
from django.db import transaction
from django.http import HttpResponseBadRequest
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from api.models import DeliveryLog
from api.serializers... | City-of-Helsinki/notification-service-api | api/views.py | .py | cec49b4f2e79e3e4 | 7 | 0 |
import logging
from audit_log.enums import Operation
from audit_log.services import audit_log_service, create_api_commit_message_from_request
logger = logging.getLogger(__name__)
class AuditLogModelAdminMixin:
def get_changelist_instance(self, request):
"""
Override get_changelist_instance of th... | City-of-Helsinki/notification-service-api | audit_log/admin.py | .py | a42ea45c29de1e1f | 7 | 0 |
from typing import Optional, TYPE_CHECKING
from django.db import models
from django.http import HttpRequest
from audit_log.enums import Operation, Status
from audit_log.services import audit_log_service
from audit_log.types import AuditCommitMessage
from audit_log.utils import (
create_commit_message,
create_... | City-of-Helsinki/notification-service-api | audit_log/managers.py | .py | 88b939a5d611f2aa | 7 | 0 |
from audit_log.services import audit_log_service
class AuditLogMiddleware:
"""
Middleware to handle audit logging.
This middleware checks if audit logging is enabled and if the current request
should be logged. If so, it commits the audit log entry after the response is
generated.
"""
de... | City-of-Helsinki/notification-service-api | audit_log/middleware.py | .py | 16cea1b877f19225 | 7 | 0 |
from django.db import models
class DummyTestModel(models.Model):
"""
A dummy model used for testing purposes.
This model is not managed by Django's ORM (managed = False),
meaning it does not have a corresponding table in the database.
It is used solely for defining data structures in tests.
... | City-of-Helsinki/notification-service-api | audit_log/models.py | .py | 683197e4e33a7b0d | 7 | 0 |
import json
from typing import Any, Dict, List, Optional
from django.core import serializers
from django.db.models.query import QuerySet
class ObjectStateSerializer:
"""
Serializes and deserializes Django model instances, with options
for filtering fields.
ObjectStateSerializer is implemented to be ... | City-of-Helsinki/notification-service-api | audit_log/serializers.py | .py | 7ffa37b4fda8fbbe | 7 | 0 |
import logging
import re
from dataclasses import asdict
from typing import List, Optional
from django.db.models import Model, QuerySet
from django.http import HttpRequest, HttpResponse
from resilient_logger.sources import ResilientLogSource
from audit_log.enums import Operation, Status, StoreObjectState
from audit_lo... | City-of-Helsinki/notification-service-api | audit_log/services.py | .py | 0008ed373a9c08d5 | 7 | 0 |
import re
from django.conf import settings
from django.core.signals import setting_changed
from django.dispatch import receiver
from audit_log.enums import StoreObjectState
_defaults = {
"ENABLED": True,
"LOGGED_ENDPOINTS_RE": re.compile(r"^/(v1|gdpr-api)/"),
"REQUEST_AUDIT_LOG_VAR": "_audit_logged_objec... | City-of-Helsinki/notification-service-api | audit_log/settings.py | .py | 29bffff62657e2d6 | 7 | 0 |
import json
import pytest
from audit_log.models import DummyTestModel
from audit_log.serializers import ObjectStateSerializer
class TestObjectStateSerializer:
def test_serialize(self):
# Create some dummy model instances
obj1 = DummyTestModel(text_field="value1", number_field=1, boolean_field=Tr... | City-of-Helsinki/notification-service-api | audit_log/tests/test_serializers.py | .py | 27bda51ad398a09a | 7.5 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.