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 |
|---|---|---|---|---|---|---|
"""End-to-end intent-routing coverage for ovos-skill-application-launcher.
The skill does not register regular intents; it exposes a single fallback
handler (priority 4) that matches "open/launch/close <application>" utterances
through its own padacioso containers and then launches or closes the desktop
application.
... | OpenVoiceOS/ovos-skill-application-launcher | test/end2end/test_intents_en_us.py | .py | a5bba8ad4fbb1dc1 | 7.8 | 3 |
"""Regression tests for the launch-confirmation flow (handle_async_prompt).
Bug: answering "no" to the confirm_switch prompt made `if not switch:` treat
the non-empty string "no" as falsy-equivalent-to-truthy in a way that skipped
the confirm_launch prompt entirely, and the function unconditionally called
self.launch_... | OpenVoiceOS/ovos-skill-application-launcher | test/test_confirmation_flow.py | .py | 37347e1727e64b74 | 7.8 | 3 |
"""Unit tests for the en-US intent matching and the {application} slot-value
exclusion (application.blacklist, OVOS-INTENT-2 §4.3)."""
import importlib.util
import os
import sys
import pytest
from ovos_utils.fakebus import FakeBus
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def _load_skill_mo... | OpenVoiceOS/ovos-skill-application-launcher | test/test_intents.py | .py | 798bc3cb921368a9 | 7.8 | 3 |
"""Set up full source space so that nondeterministic ANTs registration is mocked.
Resulting source space is saved to a pickle file.
This script can be utilized in testing. Created source spaces can be compared with
`compare_source_spaces.py`. Furthermore, the final segmentation
NIfTI files can be compared with `compa... | johnsam7/ceremegbellum | dev_tools/setup_src_with_mock_registration.py | .py | 325c24af5afa9ebb | 7.15 | 1 |
import os
import os.path as op
from pathlib import Path
from unittest.mock import MagicMock
import nibabel as nib
import numpy as np
import pytest
from mne.datasets import sample
from numpy.testing import assert_allclose, assert_array_equal
from pytest import MonkeyPatch
from cmb.segmentation import get_segmentation
... | johnsam7/ceremegbellum | tests/test_segmentation.py | .py | 5baca1bda9ad4f40 | 7.65 | 1 |
import os.path as op
import pickle
import sys
from pathlib import Path
# Need this to make sure that ants.registration is available for mocking in tests
import ants.registration # ruff: ignore[F401]
import mne
import nibabel as nib
import numpy as np
import pytest
from mne.datasets import sample
from numpy.testing im... | johnsam7/ceremegbellum | tests/test_source_space.py | .py | 62362fa9de415848 | 7.65 | 1 |
import os
import tempfile as tmp
from contextlib import contextmanager
@contextmanager
def tempfile(suffix="", dir=None):
"""Context for temporary file.
Will find a free temporary filename upon entering
and will try to delete the file on leaving, even in case of an exception.
Parameters
--------... | magnickolas/tgfeed | tgfeed/utils.py | .py | 506d95acebcf7967 | 7.24 | 2 |
import asyncio
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import AsyncEngine
from alembic import context
from app.models import Base
from app.core.config import settings
# this is th... | pog7x/fastapi-arch-tmpl | migrations/env.py | .py | 5313ddef5d3dd914 | 7.15 | 1 |
"""init
Revision ID: 0001
Revises:
Create Date: 2023-01-29 19:10:02.394110
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "0001"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
... | pog7x/fastapi-arch-tmpl | migrations/versions/0001_init.py | .py | fa33be549f88f0a7 | 7.15 | 1 |
from collections.abc import Mapping
from dataclasses import dataclass
LocalizedMessage = Mapping[str, str]
"""Human readable error messages localized to various languages: the keys specify
languages and the values are the localized messages. The language codes are not well
specified. It’s suggested that services provi... | City-of-Helsinki/helsinki-profile-gdpr-api | helsinki_gdpr/types.py | .py | b2821785b121b56c | 7.24 | 2 |
import dataclasses
import logging
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import DatabaseError, transaction
from django.utils.module_loading import import_string
from helusers.oidc import ApiTokenAuthentication
from rest_frame... | City-of-Helsinki/helsinki-profile-gdpr-api | helsinki_gdpr/views.py | .py | 4711d0d366754b08 | 7.24 | 2 |
import re
import os
import json
from behave import step
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException, StaleElementReferenceException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditio... | ministryofjustice/cla-end-to-end-tests | behave/features/steps/common_steps.py | .py | 85cb04289368d802 | 7.35 | 4 |
from enum import Enum, StrEnum
UNKNOWN_STR: str = "unknown"
NOT_SET_STR: str = "not set"
DEFAULT_TEMPLATES_DIR = "templates"
DATE_FORMAT = "%Y/%m/%d %H:%M:%S %Z"
# Mailing list constants
APACHE_MAILING_LIST_BASE_URL: str = "https://lists.apache.org/api/mbox.lua"
MAIL_DATE_FORMAT = "%a, %d %b %Y %H:%M:%S %z"
MAIL_DAT... | tomncooper/ossip | ipper/common/constants.py | .py | b83447e2b99f66e4 | 7.24 | 2 |
"""Apache KEYS file parsing and committer matching functionality.
This module provides functionality to download, parse, and cache Apache KEYS files
which contain PGP keys of project committers. It enables automatic detection of
binding votes from committers even when they don't explicitly mark their vote as
"(binding... | tomncooper/ossip | ipper/common/keys.py | .py | cb2f6c6606b99024 | 7.24 | 2 |
import datetime as dt
from dateutil.relativedelta import relativedelta
def generate_month_list(now: dt.datetime, then: dt.datetime) -> list[tuple[int, int]]:
"""Generates a list of year-month strings spanning from then to now"""
month_list: list[tuple[int, int]] = []
year: int = then.year
month: in... | tomncooper/ossip | ipper/common/utils.py | .py | cc3e09d9195e9f5e | 7.24 | 2 |
"""Flink mailing list processing functionality.
This module provides Flink-specific functions for downloading, parsing, and processing
mbox archives from Apache Flink mailing lists to track FLIP mentions and votes.
"""
import logging
import re
from pathlib import Path
from pandas import DataFrame, concat
from ipper... | tomncooper/ossip | ipper/flink/mailing_list.py | .py | ee6b8c95eb373110 | 7.24 | 2 |
import datetime as dt
from pathlib import Path
from jinja2 import Environment, FileSystemLoader, Template
from pandas import DataFrame
from ipper.common.constants import DATE_FORMAT, DEFAULT_TEMPLATES_DIR
from ipper.common.mailing_list import create_vote_dict as _create_vote_dict
FLINK_MAIN_PAGE_TEMPLATE = "flink-in... | tomncooper/ossip | ipper/flink/output.py | .py | d5b87dc5af252625 | 7.24 | 2 |
"""Kafka-specific constants and configuration."""
import logging
import re
from enum import Enum
from pathlib import Path
from pandas import DataFrame, concat
from ipper.common.keys import get_committer_index
from ipper.common.mailing_list import (
get_monthly_mbox_file as generic_get_monthly_mbox_file,
)
from i... | tomncooper/ossip | ipper/kafka/mailing_list.py | .py | 5455aa059d8959c8 | 7.24 | 2 |
import logging
from argparse import ArgumentParser, Namespace
from pathlib import Path
from pandas import DataFrame, concat
from ipper.common.keys import get_committer_index
from ipper.kafka.mailing_list import (
KEYS_CACHE_PATH,
KEYS_URL,
KIP_MENTION_COLUMNS,
get_multiple_mbox,
load_mbox_cache_fi... | tomncooper/ossip | ipper/kafka/main.py | .py | ce39e44cb7fd647c | 7.24 | 2 |
import datetime as dt
import re
from enum import Enum
from pathlib import Path
from typing import cast
from jinja2 import Environment, FileSystemLoader, Template
from pandas import DataFrame, Series, Timedelta, Timestamp, to_datetime
from ipper.common.constants import DATE_FORMAT, DEFAULT_TEMPLATES_DIR, IPState
from ... | tomncooper/ossip | ipper/kafka/output.py | .py | 6617a6c124cae02e | 7.24 | 2 |
"""Tests for Apache KEYS file parsing and committer matching."""
import datetime as dt
import pytest
from ipper.common.keys import (
CommitterIndex,
CommitterInfo,
parse_email_from_header,
parse_keys_file,
)
# Sample KEYS file content (based on real Apache KEYS format)
SAMPLE_KEYS = """
This file co... | tomncooper/ossip | tests/common/test_keys.py | .py | 386c8501d4833ba3 | 7.74 | 2 |
"""Pytest configuration and shared fixtures."""
import datetime as dt
import pytest
@pytest.fixture
def sample_datetime_utc():
"""Returns a sample datetime with UTC timezone for testing."""
return dt.datetime(2026, 2, 7, 12, 0, 0, tzinfo=dt.UTC)
@pytest.fixture
def sample_email_date_strings():
"""Retu... | tomncooper/ossip | tests/conftest.py | .py | c60b2b31ea737939 | 7.74 | 2 |
"""Tests for ipper.kafka.wiki state parsing and cache update logic."""
import json
import pytest
from ipper.common.constants import NOT_SET_STR, IPState
from ipper.kafka.wiki import (
ACCEPTED_TERMS,
NOT_ACCEPTED_TERMS,
UNDER_DISCUSSION_TERMS,
enrich_kip_info,
get_current_state,
get_kip_infor... | tomncooper/ossip | tests/kafka/test_wiki.py | .py | eb22b5d8114ce9b5 | 7.74 | 2 |
import os
import ssl
import requests
from include_tgram import sendtotelegram
def fetch_url(url, verify_ssl=True):
"""Return a requests.Response object with optional SSL verification and GitHub Actions token support."""
import requests
import ssl
headers = {}
github_token = os.environ.get("GITHUB... | gioxx/SWUpdates-Alert | core/version_check.py | .py | 8bf94b0b462d4c7f | 7.15 | 1 |
"""Logging utilities for the embodyserial library."""
import logging
# Library root logger name
LIBRARY_LOGGER_NAME = "embodyserial"
def get_logger(name: str | None = None) -> logging.Logger:
"""Get a logger for the library."""
if name:
return logging.getLogger(f"{LIBRARY_LOGGER_NAME}.{name}")
... | aidee-health/embody-serial | src/embodyserial/logging.py | .py | 74fd0ec3e9babd73 | 7 | 0 |
"""Shared test fixtures and utilities."""
import threading
import time
from serial.serialutil import SerialBase
class DummySerial(SerialBase):
"""Serial port implementation for testing."""
def __init__(self, response_data: bytes | None = None) -> None:
self.__response_data_available = threading.Eve... | aidee-health/embody-serial | tests/conftest.py | .py | c918a735ab248dd5 | 7.5 | 0 |
"""Test concurrent callback processing with max_workers=3."""
import tempfile
import threading
import time
from unittest.mock import patch
import pytest
from embodycodec import codec
from embodyserial import embodyserial as serialcomm
from embodyserial.listeners import MessageListener
from embodyserial.listeners imp... | aidee-health/embody-serial | tests/test_concurrent_callbacks.py | .py | 9a89f1de1ede0d12 | 7.5 | 0 |
"""Test connection and disconnection handling."""
import pytest
from embodyserial import embodyserial as serialcomm
from tests.conftest import DummySerial
@pytest.mark.lifecycle
class TestConnectionHandling:
"""Test connection state management."""
def test_download_aborts_when_disconnected(self):
"... | aidee-health/embody-serial | tests/test_connection_handling.py | .py | 8d8c7017a6c18559 | 7.5 | 0 |
"""Make switcher.json to allow docs to switch between different versions."""
import json
import logging
from argparse import ArgumentParser
from pathlib import Path
from subprocess import CalledProcessError, check_output
def report_output(stdout: bytes, label: str) -> list[str]:
"""Print and return something rec... | DiamondLightSource/dodal | .github/pages/make_switcher.py | .py | 5aa7c282eafe157c | 7.39 | 5 |
import importlib.util
from collections.abc import Iterable, Mapping
from functools import lru_cache
from pathlib import Path
# Where beamline names (per the ${BEAMLINE} environment variable don't always
# match up, we have to map between them bidirectionally). The most common use case is
# beamlines with a "-"" in the... | DiamondLightSource/dodal | src/dodal/beamlines/__init__.py | .py | 416f03437df526d9 | 7.39 | 5 |
from functools import cache
from daq_config_server.client import ConfigClient
from dodal.common.beamlines.beamline_utils import set_beamline as set_utils_beamline
from dodal.common.beamlines.beamline_utils import set_config_client
from dodal.device_manager import DeviceManager
from dodal.devices.beamlines.i07.dcm imp... | DiamondLightSource/dodal | src/dodal/beamlines/i07.py | .py | 6de1df280d9665f7 | 7.39 | 5 |
from functools import cache
from pathlib import Path
from ophyd_async.core import PathProvider, StaticPathProvider, UUIDFilenameProvider
from ophyd_async.epics.adcore import ADWriterFactory
from dodal.common.beamlines.beamline_utils import set_beamline as set_utils_beamline
from dodal.common.beamlines.device_helpers ... | DiamondLightSource/dodal | src/dodal/beamlines/i11.py | .py | a4ea631729eb5c85 | 7.39 | 5 |
from functools import cache
from pathlib import Path
from daq_config_server.client import ConfigClient
from ophyd_async.core import PathProvider
from ophyd_async.fastcs.panda import HDFPanda
from dodal.common.beamlines.beamline_utils import set_beamline as set_utils_beamline
from dodal.common.visit import (
Local... | DiamondLightSource/dodal | src/dodal/beamlines/i18.py | .py | 90063465b8a1fb79 | 7.39 | 5 |
#
# -*- coding: utf-8 -*-
#
# Copyright 2022-2026 NETCAT (www.netcat.pl)
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | viesapi/viesapi-python-client | viesapi/accountstatus.py | .py | 1b862ec4e4ecf9cd | 7.3 | 3 |
#
# -*- coding: utf-8 -*-
#
# Copyright 2022-2026 NETCAT (www.netcat.pl)
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | viesapi/viesapi-python-client | viesapi/error.py | .py | 143e39222c086d93 | 7.3 | 3 |
#
# -*- coding: utf-8 -*-
#
# Copyright 2022-2026 NETCAT (www.netcat.pl)
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | viesapi/viesapi-python-client | viesapi/euvat.py | .py | 3ca71ea0c1315238 | 7.3 | 3 |
import random
from typing import Tuple, Dict, Any, List
def check_parity(val: float) -> Tuple[str, str]:
"""
Returns (status_type, message) based on parity of number.
status_type can be 'even', 'odd', or 'non_integer'.
"""
if val != int(val):
return "non_integer", f"{val} is not a whole int... | surupi/Number_Ninja | games_logic.py | .py | fa690a8811a1699d | 7.15 | 1 |
"""Linux system-level install components (ADR-0003 / ADR-0007).
Home Manager now owns all user-level tooling and dotfiles declaratively. What
remains here is the *system-level* software Home Manager cannot install on a
non-NixOS host — Docker's daemon, CUDA, the NVIDIA driver, LLVM's
update-alternatives, apt system pa... | HernandoR/dotfiles | platform/installers/components.py | .py | 4a31604a334ba8a7 | 7.39 | 5 |
"""Core logic for merging ROOT files in parallel with hadd."""
from __future__ import annotations
import contextlib
import logging
import math
import multiprocessing
import os
import shutil
import signal
import subprocess
import sys
import tempfile
from collections.abc import Callable, Sequence
from concurrent.future... | MohamedElashri/hadd-parallel | src/phadd/core.py | .py | ff14e4d4e21cdcc6 | 7 | 0 |
from __future__ import annotations
import os
import stat
from pathlib import Path
import pytest
FAKE_HADD = """\
#!/usr/bin/env python3
import sys
positional = [a for a in sys.argv[1:] if not a.startswith("-")]
out, inputs = positional[0], sorted(positional[1:])
names = set()
for path in inputs:
with open(path)... | MohamedElashri/hadd-parallel | tests/conftest.py | .py | ddd9b1ccf821eb06 | 7.5 | 0 |
"""Runnable entry point — ``python -m usvote.api`` serves the read-only snapshot.
Subcommand-based, consistent with the D027 ``__main__`` convention. A single ``serve``
subcommand is the default, so bare ``python -m usvote.api`` starts the local server:
- ``python -m usvote.api`` / ``python -m usvote.api serve`` — st... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/api/__main__.py | .py | 9c8ac40b68c971bd | 7.15 | 1 |
"""HTTP freshness for the ``/v1`` surface — a content-hash ETag + ``Cache-Control``.
The ETag is a **process constant**: the whole-snapshot ``snapshot_version`` (a content
hash, D028), identical for every row of an immutable snapshot. So there is no per-body
hashing — the conditional-request logic is pure string handl... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/api/cache.py | .py | 00d3b214d69bdd09 | 7.15 | 1 |
"""API-specific configuration — CORS origins, the ``/v1`` prefix, the snapshot path.
App-*level* inputs (the snapshot path, the DB) live in the source-agnostic top-level
:mod:`usvote.config`; the *API*-specific knobs (CORS allow-list, route-version prefix)
live here in the subpackage, mirroring the per-source ``mit/co... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/api/config.py | .py | 9dcb97683cc8003e | 7.15 | 1 |
"""Origin lock-down for the public deployment (E8-S7, #101 / D034).
When the deployed API is fronted by Cloudflare (D034), a bot could bypass the edge
rate-limits + WAF by hitting the raw Cloud Run ``run.app`` URL directly. To close that,
a Cloudflare Transform Rule injects a shared secret header on every proxied requ... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/api/origin_guard.py | .py | c4797cb4213f7345 | 7.15 | 1 |
"""Presentation-layer provenance lookups (E8-S4, #98): codes → public display text.
The snapshot stores only short **codes** (``source="MIT"``, ``license="CC0-1.0"``) —
that is the drift-proof source of truth (D016/D028). Turning those codes into the
public, human-facing strings the OpenAPI surface advertises (the spe... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/api/provenance.py | .py | de8741015ebec95e | 7.15 | 1 |
"""The ``/v1`` data endpoints (E8-S3, #97) — by year / state / candidate + summary.
Every handler reads **only** through :class:`~usvote.api.repository.SnapshotRepository`
(no SQL, parsing, aggregation, or computation; the roll-up and slug are precomputed
in the snapshot, #95) and returns a typed Pydantic model wrappe... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/api/routes.py | .py | c4f07157d503ca80 | 7.15 | 1 |
"""Externalized configuration — read connection + path settings from the environment.
Replaces the notebook's hardcoded config (DB params in Section 4.1, the TIGER
shapefile path in Section 1.3 that had to be hand-edited before every run) so the
pipeline runs on a fresh machine by setting environment variables, not by... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/config.py | .py | e1b2b87f775aece1 | 7.15 | 1 |
"""The ``dwh.votes`` count-status enum contract (D043 §3, D044).
A *counting* status carried by each vote row: were these electoral votes, once
cast, actually **counted** by Congress? It is deliberately a separate fact from
:data:`usvote.transform.ELECTORAL_VOTE_SHORTFALLS`, which records votes that were
**never cast*... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/count_status.py | .py | e55cdef5bba59ee7 | 7.15 | 1 |
"""Database access — the ``DBC`` psycopg2 wrapper.
Thin wrapper around psycopg2 for schema/table create + drop, DataFrame inserts
(``execute_values``), and query-to-DataFrame reads. This is the one importable
module the whole pipeline loads through.
Ported from the top-level ``db_tools.py`` in E1-S3 (#21): type hints... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/db.py | .py | 79f364fdec3ed771 | 7.15 | 1 |
"""Load stage — write the three DataFrames into the Postgres ``dwh`` schema.
Maps to notebook Section 4. Orchestrates DataFrame -> Postgres via the ``DBC``
wrapper in :mod:`usvote.db`, creating the loose star schema (``state`` and
``candidate`` dimensions, ``votes`` fact) in FK-dependency order
(state -> candidate -> ... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/load.py | .py | bec7a81655de007c | 7.15 | 1 |
"""Runnable entry point — ``python -m usvote.mit`` loads the MIT popular-vote data.
Added in #84b to give MIT a symmetric ``__main__`` (before, ``run_mit_pipeline`` was
driven only by the integration test). A single subcommand, ``load``, is the default, so
bare ``python -m usvote.mit`` runs the pipeline:
- ``python -... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/mit/__main__.py | .py | 9354ba011c9a564b | 7.15 | 1 |
"""Top-level MIT orchestration — read -> transform -> reconcile -> load.
The MIT analogue of :mod:`usvote.pipeline`'s :func:`run_ec_pipeline`, wiring the four
MIT stages into one runnable path. Each PV source owns its own pipeline (the EC
``pipeline.py`` docstring's design), so this lives under ``usvote/mit/`` and loa... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/mit/pipeline.py | .py | f97387572d5c80da | 7.15 | 1 |
"""Read stage — load the MIT Election Lab president CSV into a DataFrame.
The ingest seam of the MIT pipeline, and the MIT analogue of the EC
:mod:`usvote.scrape` stage. It is deliberately **not** named ``scrape.py``: MIT
ships a single clean local CSV already at the (year, state, candidate) fact grain
(4,822 rows, 13... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/mit/read.py | .py | c005b0f163ac0246 | 7.15 | 1 |
"""Reconcile stage — map MIT-native ``state``/``candidate`` onto the canonical keys.
The MIT ``reconcile`` seam, sibling to :mod:`usvote.mit.read` and
:mod:`usvote.mit.transform` (source-namespacing convention, D015). It takes the
D018 shared-PV frame :func:`usvote.mit.transform.transform_mit` emits — whose
``state``/... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/mit/reconcile.py | .py | 368c259a7f3769fd | 7.15 | 1 |
"""MIT year-coverage invariants — the guard for a year that silently disappears (#177).
MIT's own shelf for invariants over the **set of election years the file covers**,
kept apart from :mod:`usvote.mit.transform` (which validates the *shape and
arithmetic* of the rows) for the reason :mod:`usvote.pv.validate` is kep... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/mit/validate.py | .py | 24013fec15178bc9 | 7.15 | 1 |
"""Top-level orchestration — scrape -> parse -> transform -> load.
Wires the four stage modules into a single end-to-end Electoral College
ingestion entry point (:func:`run_ec_pipeline`), so the pipeline runs from the
package instead of by executing notebook cells top-to-bottom.
Assembled in E2-S5 (#28). Configuratio... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/pipeline.py | .py | 0d946f7034773bd5 | 7.15 | 1 |
"""Load stage — write the shared-shape PV frames into their ``dwh`` tables.
The source-neutral PV analogue of the EC :func:`usvote.load.load_dataframes`. Every
PV source (MIT #66, later UCSB #37) loads through this one seam: hand it a frame on
the D018 shared shape (:data:`usvote.pv.schema.SHARED_PV_COLUMNS`, already ... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/pv/load.py | .py | 9053597ab4e7a5cc | 7.15 | 1 |
"""Shared PV record shape + target-table DDL + boundary shape guard (D018).
The source-neutral SSOT for the popular-vote contract. :data:`SHARED_PV_COLUMNS`
fixes the D018 long-format record shape — one row per ``(source, year, state,
candidate)`` — that *every* PV source's transform emits and the shared PV target
tab... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/pv/schema.py | .py | a93f65337e404627 | 7.15 | 1 |
"""The ``pv_source`` reference table — the SSOT for per-source PV attributes (D017).
The union of the two PV sources keeps **both** rows for every overlapping
``(year, state, candidate)`` (D017 §1, encoded in :mod:`usvote.pv.schema` by putting
``source`` in the natural key). Which source *wins* where both exist, wheth... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/pv/source.py | .py | 7617c1e78cba7812 | 7.15 | 1 |
"""Shared PV frame invariants both sources check — grain + totals (#82).
The third sibling of :mod:`usvote.pv.schema` and :mod:`usvote.pv.status`, and
source-neutral for the same reason: MIT and UCSB each assert *one row per*
``(year, state, candidate)`` and *candidate votes never exceed the state total*, and
sibling ... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/pv/validate.py | .py | fcec227fe0135145 | 7.15 | 1 |
"""The three D017 resolution views over the raw PV union, plus pure frame oracles.
The raw PV union already exists physically: both sources load into one
``dwh.pv_votes`` through :func:`usvote.pv.load.load_pv_records`, tagged by ``source``,
with ``source`` in the natural key so the overlap keeps **both** rows (D017 §1... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/pv/views.py | .py | 4e3eabe1fee88770 | 7.15 | 1 |
"""EC-spine readers — the DB seam a PV source uses to derive facts from the spine.
Two ``SELECT``s of the loaded EC star schema (``dwh.votes``/``dwh.candidate``), each
returning the exact frame a UCSB stage expects across its dependency-injection seam:
- :func:`read_ec_participation` — the ``dwh.votes`` participation... | frederick-douglas-pearce/us-presidential-vote-analysis | src/usvote/spine.py | .py | 57554af62bed6b75 | 7.15 | 1 |
from dataclasses import dataclass, field
from pathlib import Path
from . import filters
from ..objects.base import GWDCObjectBase
from ..utils import remove_path_anchor, TypedList
@dataclass
class FileReference:
"""Object used to facilitate simpler downloading of files."""
path: str
file_size: int = fiel... | gravitationalwavedc/gwdc_python | gwdc_python/files/file_reference.py | .py | d5ba90674a32debf | 7 | 0 |
from functools import partial, reduce
from .identifiers import match_file_dir, match_file_stem, match_file_suffix
def filter_file_list(identifier, file_list):
"""Takes an identifier and used it to filter an input FileReferenceList
Parameters
----------
identifier : function
Function that take... | gravitationalwavedc/gwdc_python | gwdc_python/files/filters.py | .py | 1869ab45e8718567 | 7 | 0 |
from dataclasses import dataclass
from enum import Enum
@dataclass
class JobStatus:
"""Contains the status of a job in a more readable format."""
status: str
date: str
class TimeRange(Enum):
"""Enum to help with the time range field in the public job search."""
ANY = "all"
DAY = "1d"
W... | gravitationalwavedc/gwdc_python | gwdc_python/helpers.py | .py | 8b5511663858891b | 7 | 0 |
from humps import decamelize
from .meta import GWDCObjectMeta
from ..files.constants import GWDCObjectType
class GWDCObjectBase(metaclass=GWDCObjectMeta):
"""Base class from which GWDC objects will inherit. Provides a basic initialisation method,
an equality check, a neat string representation and a method w... | gravitationalwavedc/gwdc_python | gwdc_python/objects/base.py | .py | fedfa9b352e34e8e | 7 | 0 |
class GWDCObjectMeta(type):
"""Metaclass for GWDC objects, which is used to dynamically add methods based on file list filters"""
def __new__(cls, classname, bases, attrs):
new_class = super().__new__(cls, classname, bases, attrs)
for name, func in attrs.get("FILE_LIST_FILTERS", {}).items():
... | gravitationalwavedc/gwdc_python | gwdc_python/objects/meta.py | .py | 14c6d489757702d6 | 7 | 0 |
import io
import os
def split_variables_dict(variables):
"""Recursively travel through a dict, replacing any instances of a file-like object with None and moving the
file-like objects to a separate dict
Parameters
----------
variables : dict
Dictionary of variables for a graphql query
... | gravitationalwavedc/gwdc_python | gwdc_python/utils/utils.py | .py | bfc812d1d9cb4645 | 7 | 0 |
"""Module for working with vectors over GF(2)."""
class Vector():
"""Binary vector abstraction."""
def __init__(self, value=None, length=None):
"""Create new vector of size.
:param: int `value` - integer representation of bit vector
:param: int `length` - length of the vector
... | VoMaKu/Adamar_attack_on_tenzor_product | blincodes/vector.py | .py | cc806a7dcdb6901c | 7 | 0 |
"""Unit tests for RM code module."""
import unittest
from blincodes.matrix import Matrix
from blincodes.codes import rm
class RMCodesTestCase(unittest.TestCase):
"""Test to working with Reed--Muller codes."""
def test_rm_generator(self):
"""Test evaluation of Reed--Muller codes generator matrix."""
... | VoMaKu/Adamar_attack_on_tenzor_product | tests/test_codes_rm.py | .py | 8ffc5e7a52e10b43 | 7.5 | 0 |
"""Unit Tests for module vector."""
import unittest
from blincodes import vector
class InitVectorTestCase(unittest.TestCase):
"""Testing initialisation of Vector object."""
def test_get_int_value_default(self):
"""Test to get value and represent as integer of default Vector."""
vec = vector.V... | VoMaKu/Adamar_attack_on_tenzor_product | tests/test_vector.py | .py | 4d38a0fa34086503 | 7.5 | 0 |
from rest_framework.permissions import IsAuthenticated
class AbstractPermission(IsAuthenticated):
def has_object_permission(self, request, view, obj):
"""
Users can only RETRIEVE or UPDATE their abstract.
DELETE is not allowed at API level.
"""
if request.method == "DELETE"... | eillarra/evan | evan/api/permissions/abstracts.py | .py | e75061cc5f654785 | 7 | 0 |
from rest_framework.renderers import BrowsableAPIRenderer
class NoFormBrowsableAPIRenderer(BrowsableAPIRenderer):
"""
We don't want the HTML forms and filters to be rendered in the browsable API.
It can be very slow when there are lots of entries in related fiels.
The browsable API is only used in DEB... | eillarra/evan | evan/api/renderers.py | .py | 6fc0f049fb5ab9bd | 7 | 0 |
from rest_framework.routers import DefaultRouter
from rest_framework.viewsets import ViewSet
from rest_framework_extensions.routers import NestedRouterMixin
from evan.api import views
class DummyViewSet(ViewSet):
"""Dummy viewset to register nested routes."""
pass
class Router(NestedRouterMixin, DefaultRo... | eillarra/evan | evan/api/routers.py | .py | 1f6854530e329854 | 7 | 0 |
from rest_framework import serializers
from evan.models import Album
from .rel.files import FileSerializer, FilesMixin
class PhotoPairSerializer(serializers.Serializer):
"""Serializer for original + thumbnail photo pairs."""
original = FileSerializer(read_only=True)
thumbnail = FileSerializer(read_only... | eillarra/evan | evan/api/serializers/albums.py | .py | 7abff84a9dc3576c | 7 | 0 |
from rest_framework import serializers
class TagsMixin:
"""Tags mixin."""
tags = serializers.JSONField()
class NestedHyperlinkField(serializers.HyperlinkedIdentityField):
"""A field that returns the absolute URL to an API endpoint.
Normally we should use HyperlinkedIdentityField, but it doesn't su... | eillarra/evan | evan/api/serializers/base.py | .py | 7f798ae1c475b76a | 7 | 0 |
from rest_framework import serializers
from evan.models.emails import EmailLog, EmailPlan
from evan.services.mailer.emailplans import resolve_recipients
class EmailListSerializer(serializers.ModelSerializer):
self = serializers.HyperlinkedIdentityField(view_name="v1:email-detail")
class Meta: # noqa: D106
... | eillarra/evan | evan/api/serializers/emails.py | .py | 1bd00129b47fe591 | 7 | 0 |
from django_countries.serializer_fields import CountryField
from rest_framework import serializers
from rest_framework.reverse import reverse
from evan.models import Event, Fee, validate_event_dates
from .rel.files import FilesMixin
from .sponsors import SponsorReadOnlySerializer, SponsorSerializer
from .topics impor... | eillarra/evan | evan/api/serializers/events.py | .py | 880c900353c49dba | 7 | 0 |
from rest_framework import serializers
from evan.models import Keynote
from .rel.files import FilesMixin
class KeynoteReadOnlySerializer(serializers.ModelSerializer):
class Meta:
model = Keynote
fields = ["id", "code", "title", "speaker", "bio", "abstract"]
class KeynoteSerializer(FilesMixin, ... | eillarra/evan | evan/api/serializers/keynotes.py | .py | 1373e1a02d0af018 | 7 | 0 |
from rest_framework import serializers
from evan.models import Coupon, Registration
from .events import EventListSerializer
from .rel.remarks import RemarksMixin
from .users import UserSerializer
class CouponSerializer(serializers.ModelSerializer):
"""Serializer for coupons."""
self = serializers.Hyperlink... | eillarra/evan | evan/api/serializers/registrations.py | .py | 56f54296b504c1ef | 7 | 0 |
from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from ..base import NestedHyperlinkField
class RelHyperlinkedField(serializers.HyperlinkedIdentityField):
"""Hyperlinked field for related objects."""
def get_url(self, obj, view_name, request, format):
... | eillarra/evan | evan/api/serializers/rel/base.py | .py | e49008fe2137884c | 7 | 0 |
import os
from rest_framework import serializers
from evan.models.documents.files import BaseFileUploaderConfig
from evan.models.rel.files import File
from evan.services.image_processor import ImageProcessor
from ..base import TagsMixin
from .base import NestedRelHyperlinkField, RelHyperlinkedField
class FileSeria... | eillarra/evan | evan/api/serializers/rel/files.py | .py | f33f2acbe1065b16 | 7 | 0 |
from rest_framework import serializers
from evan.models.rel.remarks import Remark
from ..base import TagsMixin
from ..users import UserTinySerializer
from .base import NestedRelHyperlinkField, RelHyperlinkedField
class RemarkSerializer(TagsMixin, serializers.ModelSerializer):
"""Remark serializer."""
self ... | eillarra/evan | evan/api/serializers/rel/remarks.py | .py | 8b4c9315aac158c8 | 7 | 0 |
from django.core.exceptions import ValidationError
from rest_framework import serializers
from evan.models import Session, Subsession, validate_datetime
from .rel.files import FilesMixin
class SubsessionReadOnlySerializer(serializers.ModelSerializer):
self = serializers.HyperlinkedIdentityField(view_name="v1:su... | eillarra/evan | evan/api/serializers/subsessions.py | .py | 343ab50cbf75a174 | 7 | 0 |
import asyncio
import logging.config
import os
from pathlib import Path
import arrow
from quart import Quart, abort, jsonify, render_template, request, url_for
from talk_to.availability import TalkTo
from talk_to.booking import (
BookingDisabledError,
BookingManager,
DeliveryError,
RateLimitedError,
... | mpcabd/talk-to | talk_to/app.py | .py | 308f303482bbc8a3 | 7.3 | 3 |
from __future__ import annotations
import asyncio
import datetime
import hashlib
import heapq
import logging
import time
from typing import NamedTuple
from urllib.parse import urlsplit
import aiohttp
import arrow
import icalendar
import recurring_ical_events
from talk_to.config import Config
logger = logging.getLog... | mpcabd/talk-to | talk_to/availability.py | .py | 66cae2ad0c04c3e8 | 7.3 | 3 |
from __future__ import annotations
import json
import os
from dataclasses import dataclass
from pathlib import Path
class ConfigError(Exception):
"""Raised when config.json is missing, malformed, or invalid."""
@dataclass(frozen=True)
class Link:
href: str
icon: str
text: str
@dataclass(frozen=Tr... | mpcabd/talk-to | talk_to/config.py | .py | 6d38fb84472247af | 7.3 | 3 |
"""Shared test data builders."""
import copy
import json
from pathlib import Path
DEFAULT_CONFIG = {
"calendars": [],
"name": "Test User",
"email": "test@example.com",
"links": [
{"href": "https://example.com", "icon": "link", "text": "example"},
],
"refresh_delay": 600,
"timezone"... | mpcabd/talk-to | tests/helpers.py | .py | 65553ccc2da80e79 | 7.8 | 3 |
import calendar
from datetime import datetime
from dateutil import tz
def findDay(date):
born = datetime.strptime(date, '%d %m %Y').weekday()
return calendar.day_name[born]
def date_du_jour():
"""Renvoie la date du jour.
Returns
-------
_currentDay_ `str`
_currentMonth_ `str`
... | Tomlora/MarinSlash | fonctions/date.py | .py | 2311b45aea1502ce | 7 | 0 |
import pandas as pd
from sqlalchemy import *
import uuid
import os
DB = os.environ.get('API_SQL')
engine = create_engine(DB, echo=False)
def upsert_df(df: pd.DataFrame, table_name: str):
"""Implements the equivalent of pd.DataFrame.to_sql(..., if_exists='update')
(which does not exist). Creates or updates ... | Tomlora/MarinSlash | fonctions/gestion_bdd.py | .py | 5a2aead134725345 | 7 | 0 |
"""
YouTube Downloader Script
This script allows users to download YouTube videos and organize them by moving associated thumbnails.
Requirements:
- Python 3.11 or later
- yt_dlp library (install using: pip install yt-dlp)
Usage:
1. Run the script.
2. Enter a valid YouTube video URL.
3. Specify the file location to ... | RhaZenZ0/YouTube- | YouMain.py | .py | 7551469177578d15 | 7 | 0 |
import csv
from datetime import datetime
import json
from os.path import exists
import re
import sys
from bs4 import BeautifulSoup
import requests
import pandas as pd
wishlist_url = "https://www.amazon.co.uk/hz/wishlist/ls/2F7TLWIU7S1IG/"
added_list = []
item_list = []
price_list = []
id_list = []
counter = 0
seen ... | rvaughan/amazon_wishlist | main.py | .py | 9b10c8bd25b8197b | 7.15 | 1 |
"""Demo download strategy class for file."""
from __future__ import annotations
from typing import Annotated
from oteapi.datacache import DataCache
from oteapi.models import AttrDict, DataCacheConfig, ResourceConfig
from oteapi.utils.paths import uri_to_path
from pydantic import Field, FileUrl, field_validator
from ... | EMMC-ASBL/oteapi-plugin-template | {{ cookiecutter.project_slug }}/{{ cookiecutter.package_name }}/strategies/download.py | .py | a9198f1c1de5a846 | 7.15 | 1 |
"""Demo filter strategy."""
from __future__ import annotations
from typing import Annotated, Literal
from oteapi.datacache import DataCache
from oteapi.models import AttrDict, DataCacheConfig, FilterConfig
from pydantic import Field
from pydantic.dataclasses import dataclass
class DemoDataModel(AttrDict):
"""D... | EMMC-ASBL/oteapi-plugin-template | {{ cookiecutter.project_slug }}/{{ cookiecutter.package_name }}/strategies/filter.py | .py | e2bb159037bc6e30 | 7.15 | 1 |
"""Demo strategy class for text/json."""
from __future__ import annotations
import json
from typing import Annotated, Literal
from oteapi.datacache import DataCache
from oteapi.models import (
AttrDict,
DataCacheConfig,
HostlessAnyUrl,
ParserConfig,
ResourceConfig,
)
from oteapi.plugins import cr... | EMMC-ASBL/oteapi-plugin-template | {{ cookiecutter.project_slug }}/{{ cookiecutter.package_name }}/strategies/parse.py | .py | 271afef6204f6cd0 | 7.15 | 1 |
"""Demo transformation strategy class."""
from __future__ import annotations
import datetime
import sys
from typing import Annotated
from oteapi.models import AttrDict, TransformationConfig, TransformationStatus
from pydantic import Field
from pydantic.dataclasses import dataclass
class DummyTransformationContent(... | EMMC-ASBL/oteapi-plugin-template | {{ cookiecutter.project_slug }}/{{ cookiecutter.package_name }}/strategies/transformation.py | .py | 461224fd08fd6792 | 7.15 | 1 |
"""Module to handle the ArchivePodcast object."""
import asyncio
import contextlib
import datetime
import time
import xml.etree.ElementTree as ET
from typing import TYPE_CHECKING
import aiohttp
from pydantic import BaseModel
from archivepodcast.constants import XML_ENCODING
from archivepodcast.downloader import Podc... | kism/archivepodcast | src/archivepodcast/archiver/podcast_archiver.py | .py | b6ac16888e8256fc | 7.15 | 1 |
"""Module to render static webpages for ArchivePodcast."""
import json
import mimetypes
import time
from pathlib import Path
from typing import TYPE_CHECKING
import markdown
from anyio import Path as AsyncPath
from jinja2 import Environment, FileSystemLoader
from archivepodcast.constants import APP_DIRECTORY, JSON_I... | kism/archivepodcast | src/archivepodcast/archiver/webpage_renderer.py | .py | 1c1261a284fddccf | 7.15 | 1 |
"""Webpage caching and management."""
from typing import ClassVar
from archivepodcast.instances.health import health
class Webpage:
"""Represents a cached webpage with its metadata."""
def __init__(self, path: str, mime: str, content: str | bytes) -> None:
"""Initialise the Webpages object."""
... | kism/archivepodcast | src/archivepodcast/archiver/webpages.py | .py | 7b6a239982b38578 | 7.15 | 1 |
"""Configuration management for archivepodcast."""
import json
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Literal, Self
from pydantic import AliasChoices, BaseModel, Field, HttpUrl, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from .constants import JSON_IN... | kism/archivepodcast | src/archivepodcast/config.py | .py | 22d639f0c577e0e7 | 7.15 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.