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 |
|---|---|---|---|---|---|---|
# Copyright 2018 AT&T Intellectual Property. All other rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | airshipit/pegleg | pegleg/engine/util/pegleg_secret_management.py | .py | b44168ff48532511 | 7.52 | 10 |
# Copyright 2018 AT&T Intellectual Property. All other rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | airshipit/pegleg | pegleg/engine/util/shipyard_helper.py | .py | 1b03de9d9af5ad7b | 7.52 | 10 |
# Copyright 2019 AT&T Intellectual Property. All other rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | airshipit/pegleg | tests/unit/engine/catalog/test_pki_generator.py | .py | bcc238bf38ccfec1 | 8.02 | 10 |
"""nox build configuration for Safir."""
import shutil
import sys
from pathlib import Path
import nox
from nox.command import CommandFailed
from nox_uv import session
# Default sessions
nox.options.sessions = ["lint", "typing", "test", "docs", "docs-linkcheck"]
# Other nox defaults
nox.options.default_venv_backend ... | lsst-sqre/safir | noxfile.py | .py | 0a6d247d8dadef21 | 7.6 | 15 |
"""Configuration for arq_ clients and workers."""
from collections.abc import Sequence
from dataclasses import dataclass
from arq.connections import RedisSettings
from arq.constants import default_queue_name as arq_default_queue_name
from arq.cron import CronJob
from arq.typing import SecondsTimedelta, StartupShutdow... | lsst-sqre/safir | safir-arq/src/safir/arq/_config.py | .py | 722f1a656fad0356 | 7.6 | 15 |
"""Exceptions for the arq_ client."""
__all__ = [
"ArqJobError",
"JobNotFound",
"JobNotQueued",
"JobResultUnavailable",
]
class ArqJobError(Exception):
"""A base class for errors related to arq jobs."""
def __init__(self, message: str, job_id: str | None) -> None:
super().__init__(me... | lsst-sqre/safir | safir-arq/src/safir/arq/_exceptions.py | .py | 3375c7b29a11c569 | 7.6 | 15 |
"""Models used by the arq_ client."""
from dataclasses import dataclass
from datetime import datetime
from enum import StrEnum
from typing import Any, Self, override
from arq.jobs import Job, JobStatus
from ._exceptions import JobNotFound, JobResultUnavailable
__all__ = [
"ArqMode",
"JobMetadata",
"JobR... | lsst-sqre/safir | safir-arq/src/safir/arq/_models.py | .py | b88ded5b3bcdeee9 | 7.6 | 15 |
"""Construction of UWS backend workers."""
import asyncio
import os
import signal
import uuid
from collections.abc import Callable
from concurrent.futures import ProcessPoolExecutor
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from enum import Enum
from traceback import format_except... | lsst-sqre/safir | safir-arq/src/safir/arq/uws.py | .py | 45a6b9056be10cd4 | 7.6 | 15 |
"""Models for structlog-based logging."""
from enum import Enum
from typing import Any, Self, override
__all__ = [
"LogLevel",
"Profile",
]
class Profile(Enum):
"""Logging profile for the application."""
production = "production"
"""Log messages in JSON."""
development = "development"
... | lsst-sqre/safir | safir-logging/src/safir/logging/_models.py | .py | 9b3080446d6a4617 | 7.6 | 15 |
"""Utilities for configuring structlog-based logging."""
import logging
import logging.config
import sys
from typing import Any
import structlog
from structlog.stdlib import add_log_level
from structlog.types import EventDict
try:
from safir.dependencies import logger as logger_dependency
_UPDATE_DEPENDENCY... | lsst-sqre/safir | safir-logging/src/safir/logging/_structlog.py | .py | 2518ced1f530189f | 7.6 | 15 |
"""Helper functions for testing logging."""
import json
from collections.abc import Iterable
from datetime import UTC, datetime, timedelta
from logging import getLevelName
from typing import Any
__all__ = ["parse_log_tuples"]
def _assert_timestamp_recent(isotimestamp: str, now: datetime) -> None:
"""Assert if a... | lsst-sqre/safir | safir-logging/src/safir/testing/logging/_parse.py | .py | 7660e41a6c08385d | 8.1 | 15 |
"""A decorator to run a function under `asyncio.run`."""
import asyncio
from collections.abc import Callable, Coroutine
from functools import wraps
__all__ = ["run_with_asyncio"]
def run_with_asyncio[**P, F](
f: Callable[P, Coroutine[None, None, F]],
) -> Callable[P, F]:
"""Run the decorated function with `... | lsst-sqre/safir | src/safir/asyncio/_run.py | .py | b5c6d57c19b88730 | 7.6 | 15 |
"""Alembic support using an async database backend."""
import asyncio
from contextlib import suppress
from pathlib import Path
try:
import alembic
from alembic import context
from alembic.config import Config
from alembic.runtime.migration import MigrationContext
from alembic.script import ScriptD... | lsst-sqre/safir | src/safir/database/_alembic.py | .py | db74c4a2aa91bfa0 | 7.6 | 15 |
"""Managing database engines and sessions."""
import asyncio
from typing import Any
from urllib.parse import quote, urlparse
from pydantic import SecretStr
from pydantic_core import Url
try:
from sqlalchemy.exc import OperationalError
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSes... | lsst-sqre/safir | src/safir/database/_connection.py | .py | bce241eeae3b18d3 | 7.6 | 15 |
"""Database initialization."""
import asyncio
try:
from sqlalchemy.exc import OperationalError
from sqlalchemy.ext.asyncio import AsyncEngine
from sqlalchemy.schema import CreateSchema
from sqlalchemy.sql.schema import MetaData
except ImportError as e:
raise ImportError(
"The safir.databas... | lsst-sqre/safir | src/safir/database/_initialize.py | .py | ce1ad3e356a14655 | 7.6 | 15 |
"""Functions to format dates and times."""
from datetime import datetime, timedelta
from typing import overload
__all__ = [
"format_datetime_for_logging",
"isodatetime",
]
@overload
def format_datetime_for_logging(timestamp: datetime) -> str: ...
@overload
def format_datetime_for_logging(timestamp: None) ... | lsst-sqre/safir | src/safir/datetime/_format.py | .py | e98ea59be1a70741 | 7.6 | 15 |
"""Functions to parse dates and times."""
import re
from datetime import datetime, timedelta
_IVOA_TIMESTAMP_PATTERN = re.compile(
r"(?P<timestamp>\d{4}-\d\d-\d\d(?P<time>T\d\d:\d\d:\d\d(\.\d\d\d)?)?)Z?$"
)
"""Regular expression matching an IVOA DALI timestamp."""
_TIMEDELTA_PATTERN = re.compile(
r"((?P<week... | lsst-sqre/safir | src/safir/datetime/_parse.py | .py | 40b8d2ae159ed819 | 7.6 | 15 |
"""A FastAPI dependency that supplies a Redis connection for arq_."""
from arq.connections import RedisSettings
from safir.arq import ArqMode, ArqQueue, MockArqQueue, RedisArqQueue
__all__ = ["ArqDependency", "arq_dependency"]
class ArqDependency:
"""A FastAPI dependency that maintains a Redis client for enque... | lsst-sqre/safir | src/safir/dependencies/arq.py | .py | 171d5425bdafa886 | 7.6 | 15 |
"""Manage an async database session."""
from collections.abc import AsyncGenerator
from typing import Any
from pydantic import SecretStr
from pydantic_core import Url
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
async_sessionmaker,
)
from safir.database import create_database_engine
_... | lsst-sqre/safir | src/safir/dependencies/db_session.py | .py | c8276eb10562ea25 | 7.6 | 15 |
"""HTTP client dependency for FastAPI."""
import httpx
__all__ = [
"DEFAULT_HTTP_TIMEOUT",
"HTTPClientDependency",
"http_client_dependency",
]
DEFAULT_HTTP_TIMEOUT = 20.0
"""Default timeout (in seconds) for outbound HTTP requests.
The default HTTPX timeout has proven too short in practice for calls to, ... | lsst-sqre/safir | src/safir/dependencies/http_client.py | .py | 26ed92a6b3e9bf25 | 7.6 | 15 |
"""Logger dependency for FastAPI.
Provides a `structlog` logger as a FastAPI dependency. The logger will
incorporate information from the request in its bound context.
"""
import uuid
import structlog
from fastapi import Request
from structlog.stdlib import BoundLogger
_logger_name: str | None = None
"""Name of th... | lsst-sqre/safir | src/safir/dependencies/logger.py | .py | 664d62fefb4b830f | 7.6 | 15 |
"""Dependencies for metrics functionality."""
from abc import ABC, abstractmethod
from safir.metrics import EventManager
__all__ = [
"EventDependency",
"EventMaker",
]
class EventMaker(ABC):
"""A blueprint for an event publisher container class."""
@abstractmethod
async def initialize(self, ma... | lsst-sqre/safir | src/safir/dependencies/metrics.py | .py | f8e33a91bef5e318 | 7.6 | 15 |
"""Error handling support for FastAPI."""
from typing import ClassVar
from fastapi import Request
from fastapi.responses import JSONResponse
from safir.models import ErrorLocation
from safir.slack.webhook import SlackIgnoredException
__all__ = [
"ClientRequestError",
"client_request_error_handler",
]
clas... | lsst-sqre/safir | src/safir/fastapi/_errors.py | .py | fc450f2427ebbea8 | 7.6 | 15 |
import gidgethub.apps
import httpx
from gidgethub.httpx import GitHubAPI
class GitHubAppClientFactory:
"""Factory for creating GitHub App clients authenticated either as an app
or as an installation of that app.
Parameters
----------
id
The GitHub App ID.
key
The GitHub App pr... | lsst-sqre/safir | src/safir/github/_client.py | .py | 67bbe62b370a2525 | 7.6 | 15 |
"""Parse HTTP ``Link`` headers."""
import re
from dataclasses import dataclass
from typing import Self
_LINK_REGEX = re.compile(r'\s*<(?P<target>[^>]+)>;\s*rel="(?P<type>[^"]+)"')
"""Matches a component of a valid ``Link`` header with a quoted type."""
_LINK_TOKEN_REGEX = re.compile(
r"\s*<(?P<target>[^>]+)>;\s*... | lsst-sqre/safir | src/safir/http/_link.py | .py | 0878871e29c5ad7e | 7.6 | 15 |
"""Schema manager exceptions."""
from typing import override
from pydantic import SecretStr
from structlog.stdlib import BoundLogger
from ..sentry import report_exception
from ..slack.webhook import SlackWebhookClient
try:
from dataclasses_avroschema.pydantic import AvroBaseModel
from faststream import Exce... | lsst-sqre/safir | src/safir/kafka/_exceptions.py | .py | 38bfef69289115e7 | 7.6 | 15 |
#!/usr/bin/env python3
"""
Version bumping script for ASymCat.
This script updates the version in both pyproject.toml and asymcat/__init__.py
to ensure consistency across the project.
"""
import argparse
import re
import sys
from pathlib import Path
try:
import tomllib
except ImportError:
import toml as toml... | tresoldi/asymcat | scripts/bump_version.py | .py | 99d56cfe91e7a925 | 7.42 | 6 |
"""
Pytest configuration for ASymCat test suite.
Provides shared fixtures, markers, and configuration for the modernized test structure.
"""
import time
import warnings
from pathlib import Path
from typing import Any
import pytest
def pytest_configure(config):
"""Configure pytest with custom markers and settin... | tresoldi/asymcat | tests/conftest.py | .py | 8b7ba9c211092d9e | 7.92 | 6 |
"""
Test data fixtures for ASymCat tests.
This module provides standardized test datasets used across the test suite,
demonstrating different types of categorical data and expected behaviors.
"""
from pathlib import Path
# Test data directory
RESOURCE_DIR = Path(__file__).parent.parent.parent / "resources"
# Small... | tresoldi/asymcat | tests/fixtures/data.py | .py | 9b1da5690b8e8086 | 7.92 | 6 |
"""
End-to-end integration tests for complete ASymCat workflows.
Tests complete pipelines from data loading to final scoring results.
"""
import time
import numpy as np
import pytest
import asymcat
from ..fixtures.assertions import (
assert_performance_acceptable,
assert_valid_cooccurrences,
assert_val... | tresoldi/asymcat | tests/integration/test_end_to_end_workflows.py | .py | a061d5d87f71c20a | 7.92 | 6 |
"""
Performance benchmarks for the :class:`asymcat.scorer.CatScorer` measures.
These benchmarks use ``pytest-benchmark`` to record the wall-clock cost of the
main scoring measures on a realistic (phoneme-level) dataset. They are intended
to:
* validate the "scalable" claim by giving concrete, reproducible numbers;
* ... | tresoldi/asymcat | tests/performance/test_scorer_benchmarks.py | .py | 4c1e4e17bdf2e7a5 | 7.92 | 6 |
"""
Tests for the bootstrap confidence-interval scorer.
``CatScorer.bootstrap_ci`` quantifies the sampling uncertainty around an
association score by resampling the co-occurrences with replacement and taking
the percentile interval of the recomputed measure, per pair and direction.
These tests cover reproducibility, t... | tresoldi/asymcat | tests/unit/test_bootstrap.py | .py | b57b672f6bf696f1 | 7.92 | 6 |
"""
Tests for input validation and error handling in :mod:`asymcat.common`.
These tests exercise the defensive validation paths of the data-loading and
pre-computation helpers, ensuring that malformed input raises clear, typed
errors rather than failing obscurely deeper in the call stack.
"""
import pytest
from asym... | tresoldi/asymcat | tests/unit/test_common_validation.py | .py | 2fe1989820dfd356 | 7.92 | 6 |
"""
Tests for the :mod:`asymcat.correlation` convenience wrappers.
These functions operate on two aligned series and return a single summary
statistic, delegating the actual computation to :mod:`asymcat.scorer`. The
tests here validate that each wrapper computes the intended measure (in
particular guarding against a r... | tresoldi/asymcat | tests/unit/test_correlation.py | .py | b23d934ba66fbbac | 7.92 | 6 |
"""
Tests for data loading and preprocessing functionality.
Demonstrates how to load different types of categorical data into ASymCat.
"""
import pytest
import asymcat
from ..fixtures.assertions import assert_valid_cooccurrences
from ..fixtures.data import RESOURCE_DIR
class TestSequenceReading:
"""Test readi... | tresoldi/asymcat | tests/unit/test_data_loading.py | .py | 4129e24752da3381 | 7.92 | 6 |
"""
Tests for legacy compatibility and validation against known values.
This ensures that the modernized test suite maintains compatibility
with the original test results and expected behaviors.
"""
import numpy as np
import pytest
import asymcat
from ..fixtures.assertions import (
assert_valid_cooccurrences,
... | tresoldi/asymcat | tests/unit/test_legacy_compatibility.py | .py | 7ddcf7828b00e261 | 7.92 | 6 |
"""
Tests for the permutation-based significance scorer.
``CatScorer.permutation_pvalue`` builds a null distribution for any association
measure by repeatedly shuffling the pairing between the ``x`` and ``y`` elements
of the co-occurrences (preserving both marginals). These tests cover
reproducibility, the value range... | tresoldi/asymcat | tests/unit/test_permutation.py | .py | 1d15c6a3f75d9e03 | 7.92 | 6 |
"""
Tests for score transformation and manipulation functions.
Demonstrates how to scale, normalize, and manipulate scoring results.
"""
import numpy as np
import pytest
import asymcat
from asymcat.scorer import CatScorer, invert_scorer, scale_scorer, scorer2matrices
from ..fixtures.assertions import (
assert_m... | tresoldi/asymcat | tests/unit/test_score_transformations.py | .py | 989c0c0bbe66bb5c | 7.92 | 6 |
"""
Tests for the statistical-significance (p-value) scorers.
``chi2_pvalue``, ``fisher_pvalue`` and ``log_likelihood_ratio_pvalue`` are the
significance counterparts to the ``chi2``, ``fisher`` and
``log_likelihood_ratio`` statistics. They return the same
``{(x, y): (p, p)}`` mapping shape as the other scorers, with ... | tresoldi/asymcat | tests/unit/test_significance.py | .py | a997f97d7b9e3787 | 7.92 | 6 |
"""
Regression tests for the vectorized ``CatScorer`` measures.
``theil_u``, ``cond_entropy``, ``mutual_information``,
``normalized_mutual_information`` and ``goodman_kruskal_lambda`` are all
computed with vectorized formulations that evaluate every symbol pair at once
from the global joint-count matrix. These tests p... | tresoldi/asymcat | tests/unit/test_vectorized_scorers.py | .py | a469abdc9a3e6213 | 7.92 | 6 |
import glob
import numpy as np
import os
import random
import tqdm
def load_dataset(enc, path, combine):
paths = []
if os.path.isfile(path):
# Simple file
paths.append(path)
elif os.path.isdir(path):
# Directory
for (dirpath, _, fnames) in os.walk(path):
for fna... | rdcolema/gpt2-slackbot | gpt2/load_dataset.py | .py | cacf7b46dd0ce7c5 | 7.5 | 9 |
import numpy as np
import tensorflow as tf
from tensorflow.contrib.training import HParams
def default_hparams():
return HParams(
n_vocab=0,
n_ctx=1024,
n_embd=768,
n_head=12,
n_layer=12,
)
def shape_list(x):
"""Deal with dynamic shape in tensorflow cleanly."""
... | rdcolema/gpt2-slackbot | gpt2/model.py | .py | 0d6248f972e8840b | 7.5 | 9 |
import os
import numpy as np
import glob
import tqdm
import random
import json
import regex as re
import tensorflow as tf
from tensorflow.contrib.training import HParams
from functools import lru_cache
# TODO: this script reuses a lot of code from sample.py and generate_sample.py -- refactor so that
# these functi... | rdcolema/gpt2-slackbot | gpt2_bot.py | .py | fc18741223cfeebe | 7.5 | 9 |
from gpt2_bot import generate_samples
def trump(command):
"""Uses GPT-2 model trained on Trump speeches to generate text sample"""
command = command.split("trump")[1]
return generate_samples("trump", sample_len=100, prime_text=command)
def okcupid(command):
"""Uses GPT-2 model trained on okcupid dat... | rdcolema/gpt2-slackbot | responses.py | .py | f7e74bb7216a3cc4 | 7.5 | 9 |
import abc
import copy
from typing import Any, List
import numpy as np
class BatchGenerator(abc.ABC):
def __init__(self, data: List[Any], batch_size: int, use_not_caught_elements_as_last_batch: bool):
"""
Base generator class for data.
Argument use_not_caught_elements_as_last... | epoch8/cv-pipeliner | cv_pipeliner/core/batch_generator.py | .py | fbd6e578f791c58d | 7.45 | 7 |
import json
import tempfile
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
import fsspec
import numpy as np
from cv_pipeliner.inferencers.backends.preprocess import get_preprocess_input_from_script_file
from cv_pipeliner.inferencers.detection.core import (
Dete... | epoch8/cv-pipeliner | cv_pipeliner/inferencers/detection/yolov8.py | .py | 63554febb9b0a1ce | 7.45 | 7 |
from dataclasses import dataclass
from typing import List, Literal
import numpy as np
from cv_pipeliner.core.data import BboxData, ImageData
def intersection_over_union(bbox_data1: BboxData, bbox_data2: BboxData) -> float:
if bbox_data1 is None or bbox_data2 is None:
return None
xmins = np.max([bbox... | epoch8/cv-pipeliner | cv_pipeliner/metrics/image_data_matching.py | .py | 9f2a9668e4cef3ed | 7.45 | 7 |
"""DWD WFS API - Utility module to update biocells.md."""
from __future__ import annotations
import json
import requests
def fetch_json() -> dict:
"""Fetch data via json."""
url = (
"https://maps.dwd.de/geoserver/dwd/ows?service=WFS"
+ "&version=2.0.0&request=GetFeature&typeName="
+... | stephan192/dwdwfsapi | docs/update_biocell_list.py | .py | f2f873b1f1bb2286 | 7.52 | 10 |
"""DWD WFS API - Utility module to update pollencells.md."""
from __future__ import annotations
import json
import requests
def fetch_json() -> dict:
"""Fetch data via json."""
url = (
"https://maps.dwd.de/geoserver/dwd/ows?service=WFS"
+ "&version=2.0.0&request=GetFeature&typeName="
... | stephan192/dwdwfsapi | docs/update_pollencell_list.py | .py | 5c61bee966434ab2 | 7.52 | 10 |
"""DWD WFS API - Utility module to update warncells.md."""
from __future__ import annotations
import json
import urllib.parse
import requests
AREAS = {
"Gemeinden": "dwd:Warngebiete_Gemeinden",
"Landkreise": "dwd:Warngebiete_Kreise",
"Binnenseen": "dwd:Warngebiete_Binnenseen",
"Küste": "dwd:Warngebi... | stephan192/dwdwfsapi | docs/update_warncell_list.py | .py | 6d2ab294656d1b3a | 7.52 | 10 |
"""Python client to retrieve bio weather forecast from DWD."""
from datetime import UTC, datetime
from .core import query_dwd
def convert_forecast_data(data_in):
"""Convert the data received from DWD."""
try:
data_out = {}
data_out["start_time"] = datetime.fromisoformat(data_in["FORECAST_DAT... | stephan192/dwdwfsapi | src/dwdwfsapi/bioweather.py | .py | 7778c303c4b4d5c5 | 7.52 | 10 |
"""Python client to retrieve pollen flight forecast from DWD."""
from datetime import UTC, datetime
from .core import query_dwd
def convert_forecast_data(data_in):
"""Convert the data received from DWD."""
try:
data_out = {}
data_out["start_time"] = datetime.fromisoformat(data_in["FORECAST_D... | stephan192/dwdwfsapi | src/dwdwfsapi/pollenflight.py | .py | 5047b5d3d1d54681 | 7.52 | 10 |
"""Python client to retrieve weather warnings from DWD."""
from datetime import UTC, datetime
from .core import query_dwd
def convert_warning_data(data_in):
"""Convert the data received from DWD."""
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
weather_severity_mapping =... | stephan192/dwdwfsapi | src/dwdwfsapi/weatherwarnings.py | .py | a5129d0b74be16a8 | 7.52 | 10 |
"""Tests for dwdwfsapi bioweather module."""
from datetime import UTC, datetime, timedelta
import pytest
from dwdwfsapi import DwdBioWeatherAPI
MIN_LEVEL = 0 # 0 = positive impact
MAX_LEVEL = 3 # 3 = high risk
TIME_TOLERANCE = 15 # seconds
FORECAST_TYPES = 6 # Number of different forecast types
FORECAST_COUNT =... | stephan192/dwdwfsapi | tests/test_bioweather.py | .py | 5385a45e0092d83d | 8.02 | 10 |
"""Tests for dwdwfsapi pollenflight module."""
from datetime import UTC, datetime, timedelta
import pytest
from dwdwfsapi import DwdPollenFlightAPI
MIN_LEVEL = 0 # 0 = none
MAX_LEVEL = 6 # 3 = high
TIME_TOLERANCE = 15 # seconds
FORECAST_TYPES = 8 # Number of different forecast types
FORECAST_COUNT = 3 # Number... | stephan192/dwdwfsapi | tests/test_pollenflight.py | .py | f7b38735b2d53e8c | 8.02 | 10 |
"""Tests for dwdwfsapi weatherwarnings module."""
from datetime import UTC, datetime, timedelta
import pytest
from dwdwfsapi import DwdWeatherWarningsAPI
MIN_WARNING_LEVEL = 0 # 0 = no warning
MAX_WARNING_LEVEL = 4 # 4 = extreme weather
TIME_TOLERANCE = 15 # seconds
testdata_ident = [
(808436003, "Gemeinde ... | stephan192/dwdwfsapi | tests/test_weatherwarnings.py | .py | 36a68039fbd37d6f | 7.02 | 10 |
"""Callback mixin for hub entities."""
from __future__ import annotations
import asyncio
import functools
import inspect
import logging
from collections.abc import Callable
from typing import Any
_LOGGER = logging.getLogger(__name__)
class CallbackMixin:
"""Mixin for entities that support update callbacks."""
... | atmurray/aiopulse | aiopulse/callbacks.py | .py | 9bea1a412f0b5f6b | 7.5 | 9 |
"""Acmeda Pulse Hub constants."""
from enum import Enum, IntEnum
class UpdateType(Enum):
"""Types of hub updates."""
info = "info"
rollers = "rollers"
rooms = "rooms"
scenes = "scenes"
timers = "timers"
class MessageType(IntEnum):
"""Protocol message types for incoming messages."""
H... | atmurray/aiopulse | aiopulse/const.py | .py | ca67ec7945db7ecc | 7.5 | 9 |
"""Base class for hub entities."""
from __future__ import annotations
from typing import TYPE_CHECKING
from aiopulse.callbacks import CallbackMixin
if TYPE_CHECKING:
from aiopulse.hub import Hub
class HubEntity(CallbackMixin):
"""Base class for entities managed by a hub."""
def __init__(self, hub: Hub... | atmurray/aiopulse | aiopulse/entities.py | .py | 426bc5e5be440e0a | 7.5 | 9 |
"""Roller blind entity that hangs off the hub."""
from __future__ import annotations
import asyncio
import logging
from typing import TYPE_CHECKING
import aiopulse.utils as utils
from aiopulse.const import CommandType
from aiopulse.entities import HubEntity
if TYPE_CHECKING:
from aiopulse.hub import Hub
fro... | atmurray/aiopulse | aiopulse/roller.py | .py | edb42ad5a77c61d3 | 7.5 | 9 |
"""Scene entity that hangs off the hub."""
from __future__ import annotations
from typing import TYPE_CHECKING
from aiopulse.entities import HubEntity
if TYPE_CHECKING:
from aiopulse.hub import Hub
class Scene(HubEntity):
"""Representation of a Scene."""
def __init__(self, hub: Hub, scene_id: bytes) -... | atmurray/aiopulse | aiopulse/scene.py | .py | a0580b11a02196c7 | 7.5 | 9 |
"""Timer entity that hangs off the hub."""
from __future__ import annotations
from typing import TYPE_CHECKING
from aiopulse.entities import HubEntity
if TYPE_CHECKING:
from aiopulse.hub import Hub
class Timer(HubEntity):
"""Representation of a Timer."""
def __init__(self, hub: Hub, timer_id: bytes) -... | atmurray/aiopulse | aiopulse/timer.py | .py | 8bd490a2e4e37cd6 | 7.5 | 9 |
"""Network transport abstraction for hub."""
import asyncio
import logging
import socket
# psutil does not provide type stubs in this project; ignore typing for import
import psutil # type: ignore
from aiopulse.errors import NotConnectedException
_LOGGER = logging.getLogger(__name__)
class HubTransportBase(async... | atmurray/aiopulse | aiopulse/transport.py | .py | a792d78a5ba5eda8 | 7.5 | 9 |
"""Demo."""
import asyncio
import cmd
import functools
import inspect
import logging
from collections.abc import Callable, Coroutine
from typing import Any
import aiopulse
logging.basicConfig()
_LOGGER = logging.getLogger("aiopulse.hub")
async def discover(prompt: "HubPrompt") -> None:
"""Task to discover all ... | atmurray/aiopulse | demo.py | .py | 21773c036c409caa | 7.5 | 9 |
# SPDX-FileCopyrightText: 2019, 2022 Esteban J. Garcia Gabancho.
# SPDX-License-Identifier: MIT
"""Invenio module that provides SAML integration."""
import json
from collections.abc import Mapping
from functools import wraps
from flask import url_for
from onelogin.saml2.idp_metadata_parser import OneLogin_Saml2_IdPM... | inveniosoftware/invenio-saml | invenio_saml/ext.py | .py | b57294361e33cde9 | 7.42 | 6 |
# SPDX-FileCopyrightText: 2019 Esteban J. Garcia Gabancho.
# SPDX-FileCopyrightText: 2019-2021 CERN.
# SPDX-FileCopyrightText: 2021-2022 Graz University of Technology.
# SPDX-License-Identifier: MIT
"""Temporary file for, IMHO, Invenio-Accounts code."""
from __future__ import absolute_import, print_function
from fla... | inveniosoftware/invenio-saml | invenio_saml/invenio_accounts/utils.py | .py | 41fd05189cce5ca8 | 7.42 | 6 |
# SPDX-FileCopyrightText: 2022 Esteban J. G. Gabancho.
# SPDX-License-Identifier: MIT
"""Utility functions."""
from functools import wraps
from urllib.parse import urlparse
from flask import request
from onelogin.saml2.auth import OneLogin_Saml2_Auth
from invenio_saml.proxies import current_sso_saml
def prepare_fl... | inveniosoftware/invenio-saml | invenio_saml/utils.py | .py | 4ea619c637f4c07c | 7.42 | 6 |
# SPDX-FileCopyrightText: 2019, 2022 Esteban J. Garcia Gabancho.
# SPDX-License-Identifier: MIT
"""Pytest configuration.
See https://pytest-invenio.readthedocs.io/ for documentation on which test
fixtures are available.
"""
import base64
from urllib.parse import urlencode
import importlib_resources as resources
imp... | inveniosoftware/invenio-saml | tests/conftest.py | .py | cf08c9b2ba6f9972 | 7.92 | 6 |
# SPDX-FileCopyrightText: 2019-2024 Esteban J. Garcia Gabancho.
# SPDX-License-Identifier: MIT
"""Module tests."""
import importlib_resources as resources
import pytest
from flask import Flask
from mock import patch
from invenio_saml import InvenioSSOSAML
from invenio_saml.errors import IdentityProviderNotFound
from... | inveniosoftware/invenio-saml | tests/test_invenio_saml.py | .py | f3659d8796c7acbe | 7.92 | 6 |
# SPDX-FileCopyrightText: 2022-2024 Esteban J. G. Gabancho.
# SPDX-License-Identifier: MIT
"""Views tests."""
import pytest
from flask import url_for
from flask_security import url_for_security
from mock import patch
def test_wrong_idp(appctx, base_client):
"""Test wrong Identity Provider name."""
client = b... | inveniosoftware/invenio-saml | tests/test_views.py | .py | be4673ddc7989933 | 7.92 | 6 |
import logging
from datetime import datetime
from typing import (
List,
Dict,
Any,
Callable,
Tuple,
Optional,
Union,
TypedDict,
Literal,
NamedTuple,
)
import google.auth
from google.oauth2 import service_account
from googleapiclient import discovery
from pytz import utc
class ... | b4tman/sync_ics2gcal | sync_ics2gcal/gcal.py | .py | 7919d19123537105 | 7.63 | 17 |
import datetime
import logging
from typing import Union, Dict, Callable, Optional, Mapping, TypedDict, cast
from icalendar import Calendar, Event
from pytz import utc
from .gcal import (
EventData,
EventList,
EventDateOrDateTime,
EventDateTime,
EventDate,
EventDataKey,
)
DateDateTime = Union[... | b4tman/sync_ics2gcal | sync_ics2gcal/ical.py | .py | 7a4f2a69ea4f2203 | 7.63 | 17 |
import logging.config
from typing import Optional, Dict, Any, List
import fire
import yaml
from . import GoogleCalendar, GoogleCalendarService
def load_config(filename: str) -> Optional[Dict[str, Any]]:
result: Optional[Dict[str, Any]] = None
try:
with open(filename, "r", encoding="utf-8") as f:
... | b4tman/sync_ics2gcal | sync_ics2gcal/manage_calendars.py | .py | 90bf0793ae1892d0 | 7.63 | 17 |
import datetime
import logging
import operator
from typing import List, Dict, Set, Tuple, Union, Callable, NamedTuple
import dateutil.parser
from pytz import utc
from .gcal import (
GoogleCalendar,
EventData,
EventList,
EventTuple,
EventDataKey,
EventDateOrDateTime,
EventDate,
)
from .ical... | b4tman/sync_ics2gcal | sync_ics2gcal/sync.py | .py | 1fb021a62773004d | 7.63 | 17 |
"""Helpers shared by endpoint modules."""
from __future__ import annotations
import re
from typing import List, Optional
from lxml import html as lxml_html
from pymetal.locators import RE_TRAILING_ID
from pymetal.models import Audit
def parse_html(content: bytes):
return lxml_html.fromstring(content)
def dl_... | LeMetadatarr/pymetal | pymetal/endpoints/_common.py | .py | d86148ecb6eef145 | 7.56 | 12 |
"""Browse endpoints — full alphabetical / country / genre listings.
These are MA's `browse/ajax-*` JSON endpoints. They return the entire
catalog for a slice (every band in a country, every band in a genre,
every band starting with a letter) rather than paged search results,
so they're the right tool for enumerate-eve... | LeMetadatarr/pymetal | pymetal/endpoints/browse.py | .py | ae5dc9045de836b3 | 7.56 | 12 |
"""Lyrics endpoint."""
from __future__ import annotations
from typing import Iterator, Optional, Sequence, Union
from pymetal.endpoints.search import search_songs
from pymetal.http import Client, default_client
from pymetal.locators import LYRICS_NOT_AVAILABLE, RE_TAGS, URL_LYRICS
from pymetal.models import ReleaseTy... | LeMetadatarr/pymetal | pymetal/endpoints/lyrics.py | .py | 5ca29245973a774d | 7.56 | 12 |
"""HTTP layer: curl_cffi (TLS fingerprint bypass) + small in-process cache.
`requests_cache` doesn't wrap curl_cffi sessions, so we keep a tiny LRU-ish
dict keyed on (method, url, sorted-params). Good enough for a scraper —
metal-archives is mostly idempotent and we want to avoid hammering it from
tests and notebooks.... | LeMetadatarr/pymetal | pymetal/http.py | .py | f3f2bc5a3bc6e886 | 7.56 | 12 |
from random_user_agent.user_agent import UserAgent
from random_user_agent.params import SoftwareName, OperatingSystem
def get_random_user_agent():
# Returning a fixed modern chrome user agent that matches our impersonation target
return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, lik... | LeMetadatarr/pymetal | pymetal/util.py | .py | 6f5dee6e96c7c216 | 7.56 | 12 |
"""Shared fixtures: a fake `Client` that serves captured HTML/JSON.
Lets endpoint tests run offline without monkey-patching the network.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Dict, Optional
import pytest
FIXTURES = Path(__file__).parent / "fixtures" / "html"
... | LeMetadatarr/pymetal | test/conftest.py | .py | c491e52e92784a1d | 8.06 | 12 |
"""Re-capture HTML/JSON fixtures from metal-archives.
Run from repo root: `python test/fixtures/_capture.py`. Requires network.
Fixtures are anchored on stable, well-known MA records:
- Carcass band id 14 (formed 1986, multiple lineup eras)
- Heartwork album id 451600 (full-length)
- Napalm Death / S.O.B. split... | LeMetadatarr/pymetal | test/fixtures/_capture.py | .py | 3cc0ac257a216181 | 7.06 | 12 |
"""Unit tests for endpoint helpers — no network."""
from lxml import html as lxml_html
from pymetal.endpoints._common import (
collect_stats,
dl_pairs,
extract_audit,
first,
ma_id_from_url,
parse_int,
split_csv,
)
from pymetal.endpoints.bands import _parse_role_dates
from pymetal.endpoints.... | LeMetadatarr/pymetal | test/test_endpoints_unit.py | .py | ebb0c9c98ba64e9d | 8.06 | 12 |
"""Row-schema equivalence tests for the metal_archives bulk harvester.
These lock the exact flat-row shape emitted by MetalArchivesSource against a
realistic upstream sample — moved verbatim (schema unchanged) from
metadatarr's test_scrapers_batch2.py when the scraper was ported onto the
shared harvestkit engine.
"""
... | LeMetadatarr/pymetal | test/test_harvest_metal_archives.py | .py | 131239b05e8b76da | 8.06 | 12 |
"""Model-level tests — no network. Covers the three semantics that the
old flat (track, band, album) model could not represent.
"""
from __future__ import annotations
import pytest
from pymetal.models import (
Band,
LineupMember,
LineupStatus,
Release,
ReleaseLineup,
ReleaseType,
Song,
... | LeMetadatarr/pymetal | test/test_models.py | .py | 353445d00b07b4c6 | 8.06 | 12 |
"""Alembic environment configuration for async migrations."""
import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
from core.config import settings as app_setti... | kernelcoffee/SteamSelfGifter | backend/src/alembic/env.py | .py | e11802884bc136a0 | 7.56 | 12 |
"""initial_schema
Revision ID: 93fe35470006
Revises:
Create Date: 2026-01-15 15:24:14.050777
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = '93fe35470006'
down_revision: str | Sequence[str] | None = None
branch_label... | kernelcoffee/SteamSelfGifter | backend/src/alembic/versions/93fe35470006_initial_schema.py | .py | e574f9c4d8bd105e | 7.56 | 12 |
"""Add settings.log_retention_days for activity-log pruning
Activity logs previously grew forever (only manual Clear All). The
automation cycle now prunes rows older than this many days; 0 disables
pruning.
Revision ID: a7d4e8f2c6b1
Revises: f1b8c5d3a9e2
Create Date: 2026-07-21
"""
from collections.abc import Sequen... | kernelcoffee/SteamSelfGifter | backend/src/alembic/versions/a7d4e8f2c6b1_add_log_retention_days_setting.py | .py | 3e562b23d411993b | 7.56 | 12 |
"""add giveaway eligibility diagnostics
Adds eligibility_reason and eligibility_checked_at to the giveaways table so the
autojoin decision (and its reason) is recorded per giveaway.
Revision ID: b1f4c0a9d2e7
Revises: 93fe35470006
Create Date: 2026-06-17 15:30:00.000000
"""
from collections.abc import Sequence
impor... | kernelcoffee/SteamSelfGifter | backend/src/alembic/versions/b1f4c0a9d2e7_add_giveaway_eligibility_reason.py | .py | a9438e312676dbfd | 7.56 | 12 |
"""add wishlist priority toggle to settings
Adds wishlist_priority_enabled: when on (default), wishlist giveaways bypass
the autojoin quality filters and are entered before everything else.
Revision ID: c8d2e5f1a3b9
Revises: b1f4c0a9d2e7
Create Date: 2026-07-18 14:30:00.000000
"""
from collections.abc import Sequenc... | kernelcoffee/SteamSelfGifter | backend/src/alembic/versions/c8d2e5f1a3b9_add_wishlist_priority_setting.py | .py | 13436a88f70e3c0c | 7.56 | 12 |
"""add entries count to giveaways
The scraper has always parsed the entry count from listing pages; store it so
the UI can show and filter by chance-to-win (copies / entries).
Revision ID: d4e7f2a8b1c5
Revises: c8d2e5f1a3b9
Create Date: 2026-07-18 17:00:00.000000
"""
from collections.abc import Sequence
import sqla... | kernelcoffee/SteamSelfGifter | backend/src/alembic/versions/d4e7f2a8b1c5_add_giveaway_entries_count.py | .py | 98e5ddac750a9a44 | 7.56 | 12 |
"""Add giveaways.safety_checked_at for safety verdict freshness
Revision ID: f1b8c5d3a9e2
Revises: e9a3b6c4d2f7
Create Date: 2026-07-21
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "f1b8c5d3a9e2"
down_revision: str ... | kernelcoffee/SteamSelfGifter | backend/src/alembic/versions/f1b8c5d3a9e2_add_giveaway_safety_checked_at.py | .py | c5d79344fab2e133 | 7.56 | 12 |
import os
from typing import Literal
from pydantic_settings import BaseSettings, SettingsConfigDict
def get_data_dir() -> str:
"""Get data directory - /config in Docker, ./data locally"""
if os.path.exists("/config"):
return "/config"
return "./data"
class Settings(BaseSettings):
"""Applica... | kernelcoffee/SteamSelfGifter | backend/src/core/config.py | .py | c53fe562592b52e0 | 7.56 | 12 |
"""WebSocket event manager for real-time client notifications.
This module provides the EventManager class for broadcasting events to
connected WebSocket clients, enabling real-time updates in the web UI.
"""
from typing import Any
from fastapi import WebSocket
from core.time import utcnow
class EventManager:
... | kernelcoffee/SteamSelfGifter | backend/src/core/events.py | .py | 46eef998d34f8f4c | 7.56 | 12 |
"""Time helpers.
The database stores naive UTC datetimes (SQLite has no timezone support), so
every "now" in the codebase must be naive UTC. ``datetime.utcnow()`` is
deprecated since Python 3.12; this helper is the single sanctioned replacement.
"""
from datetime import UTC, datetime
def utcnow() -> datetime:
"... | kernelcoffee/SteamSelfGifter | backend/src/core/time.py | .py | 0b19a1392eb6c60f | 7.56 | 12 |
"""Database session management for async SQLAlchemy with SQLite."""
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from core.config import settings
# Create async engine for SQLite
engine = create_async_engine(
... | kernelcoffee/SteamSelfGifter | backend/src/db/session.py | .py | 027c6439ed87f766 | 7.56 | 12 |
"""Activity and event logging model."""
from datetime import datetime
from sqlalchemy import DateTime, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from core.time import utcnow
from models.base import Base
class ActivityLog(Base):
"""
Application activity and event logging for UI ... | kernelcoffee/SteamSelfGifter | backend/src/models/activity_log.py | .py | 069ad0882db43c54 | 7.56 | 12 |
"""Base classes and mixins for database models."""
from datetime import datetime
from sqlalchemy import DateTime, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
"""
Base class for all database models.
This is the declarative base that all SQLAlchemy ... | kernelcoffee/SteamSelfGifter | backend/src/models/base.py | .py | 9071c2a87506f71b | 7.56 | 12 |
"""Giveaway entry tracking model."""
from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from core.time import utcnow
from models.base import Base, TimestampMixin
class Entry(Base, TimestampMixin):
"""
Giveaway en... | kernelcoffee/SteamSelfGifter | backend/src/models/entry.py | .py | b46043e86d5262d6 | 7.56 | 12 |
"""Steam game/DLC/bundle data model."""
from datetime import datetime
from sqlalchemy import JSON, Boolean, DateTime, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from core.time import utcnow
from models.base import Base, TimestampMixin
class Game(Base, TimestampMixin):
"""
Steam ... | kernelcoffee/SteamSelfGifter | backend/src/models/game.py | .py | 36a491c0997a87c7 | 7.56 | 12 |
"""SteamGifts giveaway data model."""
from datetime import datetime
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String
from sqlalchemy.orm import Mapped, mapped_column
from core.time import utcnow
from models.base import Base, TimestampMixin
class Giveaway(Base, TimestampMixin):
"""
Stea... | kernelcoffee/SteamSelfGifter | backend/src/models/giveaway.py | .py | 65ca33251d76ab5c | 7.56 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.