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 |
|---|---|---|---|---|---|---|
"""Test Project Model."""
import pytest
from pydantic import ValidationError
from tui.domain.models.project import Project
@pytest.mark.unit
class TestProject:
"""Test suite for Project model."""
def test_project_valid_creation(self):
"""Test valid project creation."""
project = Project(
... | bellanov/google | tui/tests/models/test_project.py | .py | 2e9fda5cfb0b83fd | 7.5 | 0 |
"""Parse a single SBI TT Rates PDF and return a structured dict."""
import re
import sys
import logging
import threading
from pathlib import Path
# MuPDF (underlying library) is not thread-safe — serialize all parse calls
_PARSE_LOCK = threading.Lock()
logger = logging.getLogger(__name__)
# Pairs quoted per 100 for... | anoopgarlapati/sbi-tt-rates-archive | scripts/parse_pdf.py | .py | c832f2b74f109e8d | 7.35 | 4 |
"""Permutation algebra: words of move symbols and the permutations they compose to."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from typing import Final
from spruce.algebra.permutation import get_identity
from spruce.algebra.permutation import invert
if TYPE_CHECKING:
f... | martintufte/spruce | spruce/algebra/__init__.py | .py | 6681058e29b4b0dc | 7.3 | 3 |
from __future__ import annotations
from enum import Enum
from enum import unique
from functools import cached_property
from typing import TYPE_CHECKING
import attrs
import numpy as np
from spruce.algebra.permutation import invert
from spruce.types import MoveSymbol
if TYPE_CHECKING:
from collections.abc import ... | martintufte/spruce | spruce/algebra/meta.py | .py | 57b49c46dc96b35a | 7.3 | 3 |
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from collections.abc import Sequence
from spruce.types import IndexArray
from spruce.types import PatternArray
from spruce.types import PermutationArray
def get_empty_pattern(size: int) -> Patt... | martintufte/spruce | spruce/algebra/pattern.py | .py | b29fcc165c274cc5 | 7.3 | 3 |
"""A word over a group, split into a normal and an inverse side."""
from __future__ import annotations
from typing import TYPE_CHECKING
from attrs import define
from attrs import field
from attrs import validators
from spruce.types import MoveSymbol # noqa: TC001
if TYPE_CHECKING:
from collections.abc import ... | martintufte/spruce | spruce/algebra/sequence.py | .py | d017ed16f77364c8 | 7.3 | 3 |
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from typing import Final
from typing import Literal
from typing import NoReturn
import numpy as np
from spruce.algebra.permutation import invert
from spruce.puzzle.cube.group import build_move_meta
from spruce.puzzle.cube.pieces impor... | martintufte/spruce | spruce/autotagger/subset.py | .py | b6cb97ccc8103acb | 7.3 | 3 |
from __future__ import annotations
from typing import TYPE_CHECKING
from spruce.puzzle.cube.formatting import has_valid_characters
from spruce.puzzle.cube.formatting import replace_confusing_chars
from spruce.puzzle.cube.formatting import strip_comments
from spruce.puzzle.cube.notation import parse_sequence
if TYPE_... | martintufte/spruce | spruce/parsing/__init__.py | .py | d13d0ee84a3f3742 | 7.3 | 3 |
from __future__ import annotations
from functools import lru_cache
from typing import TYPE_CHECKING
from typing import cast
import numpy as np
from spruce.algebra.permutation import get_identity
from spruce.algebra.permutation import invert
from spruce.algebra.permutation import multiply
if TYPE_CHECKING:
from ... | martintufte/spruce | spruce/puzzle/cube/geometry.py | .py | 716ba08b90b05e41 | 7.3 | 3 |
from __future__ import annotations
from typing import TYPE_CHECKING
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
if TYPE_CHECKING:
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from spruce.types import StringArray
def plot_piece(ax: Axes, x: float, y... | martintufte/spruce | spruce/puzzle/cube/graphics/horizontal.py | .py | faa73cc57c59785b | 7.3 | 3 |
"""Building the move group of a cube puzzle from its geometry and notation."""
from __future__ import annotations
import re
from functools import lru_cache
from typing import TYPE_CHECKING
from typing import Final
from spruce.algebra.meta import MoveMeta
from spruce.algebra.meta import PermutationClassification
from... | martintufte/spruce | spruce/puzzle/cube/group.py | .py | 40e30f3d20b0e515 | 7.3 | 3 |
from __future__ import annotations
import re
from enum import Enum
from enum import unique
from functools import lru_cache
from typing import TYPE_CHECKING
from spruce.puzzle.cube.notation import DOUBLE_ROTATION_SEARCH
from spruce.puzzle.cube.notation import DOUBLE_SEARCH
from spruce.puzzle.cube.notation import DOUBL... | martintufte/spruce | spruce/puzzle/cube/metrics.py | .py | d000371f5ab663c7 | 7.3 | 3 |
"""Cube move notation: the patterns, expanding compound symbols, and parsing sequences."""
from __future__ import annotations
import re
from typing import TYPE_CHECKING
from typing import Any
from typing import Final
from spruce.algebra.sequence import MoveSequence
from spruce.puzzle.cube.formatting import format_st... | martintufte/spruce | spruce/puzzle/cube/notation.py | .py | f52e8a1b99621364 | 7.3 | 3 |
from __future__ import annotations
import logging
from math import factorial
from typing import TYPE_CHECKING
from typing import Final
import numpy as np
from spruce.algebra import get_permutation
from spruce.algebra.pattern import find_orbit_labels
from spruce.algebra.sequence import MoveSequence
from spruce.puzzle... | martintufte/spruce | spruce/puzzle/cube/patterns.py | .py | d17314f52f5348b2 | 7.3 | 3 |
from __future__ import annotations
from enum import Enum
from enum import unique
from typing import TYPE_CHECKING
from typing import cast
import numpy as np
from spruce.algebra import get_permutation
from spruce.algebra.permutation import get_identity
from spruce.puzzle.cube.notation import parse_sequence
if TYPE_C... | martintufte/spruce | spruce/puzzle/cube/pieces.py | .py | aac869f6cb52dfc1 | 7.3 | 3 |
from __future__ import annotations
from enum import Enum
from typing import Final
import attrs
from spruce.types import GoalId
from spruce.types import MoveSymbol
from spruce.types import PatternArray
from spruce.types import PermutationValidator
from spruce.types import VariantId
class SearchSideChoice(Enum):
... | martintufte/spruce | spruce/search/beam/interface.py | .py | c6856a9b47e87bc9 | 7.3 | 3 |
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from typing import TypedDict
import numpy as np
import numpy.linalg as la
if TYPE_CHECKING:
from spruce.types import BoolArray
LOGGER = logging.getLogger(__name__)
class BranchingFactor(TypedDict):
average: float
expect... | martintufte/spruce | spruce/search/branching.py | .py | 43ee21f76591b8b4 | 7.3 | 3 |
from __future__ import annotations
import logging
from functools import lru_cache
import attrs
import numpy as np
from spruce.search.transform.interface import SearchProblem
from spruce.search.transform.interface import Transform
from spruce.types import BoolArray # noqa: TC001
from spruce.types import MoveSymbol ... | martintufte/spruce | spruce/search/transform/action.py | .py | 509e6e7a4f20e419 | 7.3 | 3 |
from __future__ import annotations
from typing import TYPE_CHECKING
from typing import Self
import attrs
from spruce.search.transform.interface import IndexTransform
from spruce.search.transform.interface import SearchProblem
from spruce.search.transform.interface import Transform
from spruce.types import Permutatio... | martintufte/spruce | spruce/search/transform/fused_index.py | .py | b1a0e4f37759d07a | 7.3 | 3 |
from __future__ import annotations
import attrs
import numpy as np
from spruce.algebra.pattern import find_orbit_labels
from spruce.algebra.pattern import merge_patterns
from spruce.algebra.permutation import reindex
from spruce.search.transform.interface import IndexTransform
from spruce.search.transform.interface i... | martintufte/spruce | spruce/search/transform/index.py | .py | c592e64f413aec6a | 7.3 | 3 |
from __future__ import annotations
from abc import ABC
from abc import abstractmethod
import attrs
from spruce.types import BoolArray # noqa: TC001
from spruce.types import MoveSymbol # noqa: TC001
from spruce.types import PatternArray # noqa: TC001
from spruce.types import PermutationArray # noqa: TC001
@attr... | martintufte/spruce | spruce/search/transform/interface.py | .py | b94f737bdea6e7aa | 7.3 | 3 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""The content-cache-backends-config charm."""
import logging
import ops
from errors import ConfigurationError
from state import Configuration
logger = logging.getLogger(__name__)
CACHE_CONFIG_INTEGRATION_NAME = "cac... | canonical/content-cache-operator | content-cache-backends-config/src/charm.py | .py | faa56675f7f37329 | 7 | 0 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""The charm state and configurations."""
import json
import logging
import re
import typing
import ops
import pydantic
import pydantic_core
from errors import ConfigurationError
logger = logging.getLogger(__name__)
BACKENDS_CONFIG_NAME = "... | canonical/content-cache-operator | content-cache-backends-config/src/state.py | .py | db3669fc829cb128 | 7 | 0 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Module for defining unit test fixtures."""
import pytest
from ops.testing import Harness
from charm import ContentCacheBackendsConfigCharm
@pytest.fixture(name="harness", scope="function")
def harness_fixture():
"""The ops testing har... | canonical/content-cache-operator | content-cache-backends-config/tests/unit/conftest.py | .py | 8d6df7dd799745b3 | 7.5 | 0 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Factory for mocks."""
import typing
from unittest.mock import MagicMock
import factory
from src.state import (
BACKEND_HOSTNAME_CONFIG_NAME,
BACKENDS_CONFIG_NAME,
FAIL_TIMEOUT_CONFIG_NAME,
HEALTHCHECK_INTERVAL_CONFIG_NAME,
... | canonical/content-cache-operator | content-cache-backends-config/tests/unit/factories.py | .py | a2d745cc3bb48825 | 7.5 | 0 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Replace the uid for all loki datasources in the grafana JSON model file.
For help run `python -m replace_loki_uid -h`.
"""
import argparse
from dataclasses import dataclass
import json
from pathlib import Path
@dataclass
class Arguments:
... | canonical/content-cache-operator | content-cache/scripts/replace_loki_uid.py | .py | 06c62ac14cda4da7 | 7 | 0 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Manage the TLS Certificates."""
import logging
import os
import pwd
from pathlib import Path
from charms.tls_certificates_interface.v4.tls_certificates import (
CertificateRequestAttributes,
PrivateKey,
ProviderCertificate,
... | canonical/content-cache-operator | content-cache/src/certificates.py | .py | b996fb5bbf9d4402 | 7 | 0 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""The content-cache charm."""
import json
import logging
from pathlib import Path
import ops
from charmlibs.interfaces.certificate_transfer import (
CertificateTransferRequires,
)
from charms.grafana_agent.v0.cos_a... | canonical/content-cache-operator | content-cache/src/charm.py | .py | 3658ab71cca1ea1e | 7 | 0 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""The charm state and configurations."""
import json
import logging
import re
import typing
import ops
import pydantic
from errors import ConfigurationError, IntegrationDataError
logger = logging.getLogger(__name__)
CACHE_CONFIG_INTEGRATIO... | canonical/content-cache-operator | content-cache/src/state.py | .py | f42d8ebca435f83a | 7 | 0 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Fixture for integration tests."""
import asyncio
import logging
import secrets
from typing import AsyncIterator, List
import pytest
import pytest_asyncio
from juju.application import Application
from juju.model import Model
from pytest_oper... | canonical/content-cache-operator | content-cache/tests/integration/conftest.py | .py | bdcaab99ef94bffd | 7.5 | 0 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Helper functions and classes for integration test."""
import json
import logging
import textwrap
from pathlib import Path
import requests
from juju.action import Action
from juju.application import Application
from juju.model import Model
f... | canonical/content-cache-operator | content-cache/tests/integration/helpers.py | .py | 232201d55f157758 | 7.5 | 0 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Fixtures for unit tests."""
from pathlib import Path
from typing import Iterator
from unittest.mock import MagicMock
import pytest
from ops.testing import Harness
from charm import ContentCacheCharm
from state import (
BACKENDS_FIELD_N... | canonical/content-cache-operator | content-cache/tests/unit/conftest.py | .py | e4bbf38d48a3ae06 | 7.5 | 0 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Unit tests for the ca_certs module."""
import pytest
import ca_certs
FAKE_SYSTEM_CA_CONTENT = "# fake system CA\n"
def test_write_ca_bundle_always_includes_system_cas():
"""
arrange: No operator certs.
act: Write an empty bun... | canonical/content-cache-operator | content-cache/tests/unit/test_ca_certs.py | .py | 2c987ffe6c4ea960 | 7.5 | 0 |
# Copyright 2024-2026 Simon Brunning
import logging
import sys
import time
import warnings
from contextlib import contextmanager
from typing import TYPE_CHECKING
from pythonjsonlogger.json import JsonFormatter
if TYPE_CHECKING:
from collections.abc import Callable, Generator, Sequence
LOG_LEVELS = [logging.ERROR... | brunns/rss-agg | src/rss_agg/logging_utils.py | .py | 44ce04f8f08064fd | 7 | 0 |
#!/usr/bin/env python3
"""Guard against internal-tracking-label leakage into shipped source/tests.
Planning identifiers (``Item NNN`` / ``item NNa``, ``RCN``, ``Change C``,
``Bug BNN``, ``PR #NNN``, ``review #XN``, ``consumer-gaps``, plan-phase
tags (``Phase N`` without a trailing ``:``), plan sub-item ids (``77a`` /
... | KBS-Labs/dataknobs | bin/check-internal-labels.py | .py | 8e52c22befbdcc90 | 7.3 | 3 |
#!/usr/bin/env python3
"""Compare uv.lock dependency versions against a git ref.
Shows updated, added, and removed packages between the current
working tree's uv.lock and the version at a given git ref (default: main).
Usage:
bin/dep-diff.py [ref] Compare against ref (default: main)
bin/dep-diff.py --s... | KBS-Labs/dataknobs | bin/dep-diff.py | .py | 33f69edc6359a297 | 7.3 | 3 |
#!/usr/bin/env python3
"""Find print statements in Python code using AST parsing.
This tool parses Python source files and identifies print() function calls
in executable code, ignoring comments, docstrings, and string literals.
Print statements are ignored in the following cases (considered proper usage):
- Print st... | KBS-Labs/dataknobs | bin/find_print_statements.py | .py | d082bc479491df88 | 7.3 | 3 |
#!/usr/bin/env python3
"""List packages from the registry in various formats.
Usage:
python bin/list-packages.py --format yaml # For GitHub Actions
python bin/list-packages.py --format choices # For workflow inputs
python bin/list-packages.py --format pip # For pip install commands... | KBS-Labs/dataknobs | bin/list-packages.py | .py | f986d4aef58b15e8 | 7.3 | 3 |
#!/usr/bin/env python3
r"""Project ``quality-summary.json`` into delimited lines a shell can read.
``bin/validate-quality-artifacts.sh`` is what CI runs instead of re-running the
gate, so what it can read decides what CI can see. It used to read the summary
with line-offset greps — ``grep -A2 '"unit_tests"'`` for a st... | KBS-Labs/dataknobs | bin/read-quality-summary.py | .py | 16c7d2a227a5541f | 7.3 | 3 |
#!/usr/bin/env python3
"""Validate that all packages are properly referenced across the codebase.
This script checks:
- GitHub workflows reference all packages that require docs build
- Release workflow has all packages in choices
- README.md mentions all non-deprecated packages
- pyproject.toml includes all packages
... | KBS-Labs/dataknobs | bin/validate-package-references.py | .py | 6d607839d2eb51fc | 7.3 | 3 |
"""ReAct agent example.
This example demonstrates:
- ReAct (Reasoning + Acting) strategy
- Tool definition and registration
- Multi-step problem solving
- Reasoning trace storage
- Verbose logging
Required Ollama model:
ollama pull gemma3:1b
"""
import asyncio
from typing import Any, Dict
from dataknobs_bots im... | KBS-Labs/dataknobs | packages/bots/examples/04_react_agent.py | .py | b83e340e3c897879 | 7.3 | 3 |
"""Config-based tool loading example.
This example demonstrates:
- Loading tools directly from configuration
- Using xref to reference pre-defined tool configurations
- Tool parameter customization via config
- No need to manually instantiate and register tools
Required Ollama model:
ollama pull phi3:mini
"""
im... | KBS-Labs/dataknobs | packages/bots/examples/06_config_based_tools.py | .py | 99848a28d10585e5 | 7.3 | 3 |
"""Assessment session tracking for quiz and evaluation workflows.
Models and transform functions for creating assessment sessions,
recording student responses, and calculating scores. Designed for
integration with wizard workflows and artifact registry.
Example:
>>> session = AssessmentSession(
... studen... | KBS-Labs/dataknobs | packages/bots/src/dataknobs_bots/artifacts/assessment.py | .py | d2ec8abdb2d6561b | 7.3 | 3 |
"""Artifact corpus for managing collections of related artifacts.
A corpus is a named, typed collection of artifacts (e.g., a quiz bank is a
corpus of quiz questions). It provides corpus-level operations: add items
with optional dedup, query items, get summaries, and finalize.
Example:
>>> from dataknobs_bots.art... | KBS-Labs/dataknobs | packages/bots/src/dataknobs_bots/artifacts/corpus.py | .py | 5bee74ce12280a96 | 7.3 | 3 |
"""Display helpers for rendering artifact and evaluation data as markdown.
Pure functions that format rubric evaluations, criterion details,
evaluation comparisons, and provenance chains into human-readable
markdown strings. Suitable for use in wizard templates, chat responses,
or reports.
Example:
>>> from datak... | KBS-Labs/dataknobs | packages/bots/src/dataknobs_bots/artifacts/display.py | .py | a33a77c55aa8475d | 7.3 | 3 |
"""Artifact data models for tracking work products in conversational workflows.
This module provides the core data structures for:
- Artifacts: Versioned work products with provenance tracking
- Status management: Enum-based lifecycle status
- Type definitions: Configuration-driven artifact type specifications
Exampl... | KBS-Labs/dataknobs | packages/bots/src/dataknobs_bots/artifacts/models.py | .py | d48bbfb7f1371616 | 7.3 | 3 |
"""Provenance models for tracking artifact creation and revision history.
This module provides data structures for comprehensive provenance tracking:
- Source references: Where content came from
- Tool invocations: Which tools were used during creation
- LLM invocations: When and why LLMs were consulted
- Revision rec... | KBS-Labs/dataknobs | packages/bots/src/dataknobs_bots/artifacts/provenance.py | .py | f30d36c9a590f4f1 | 7.3 | 3 |
"""Typed top-level configuration for :class:`~dataknobs_bots.bot.base.DynaBot`.
``DynaBotConfig`` is the one typed configuration snapshot for a bot. It is
a deliberately thin envelope: a handful of typed scalars plus the
documented config sections forwarded verbatim to the subsystem factories.
The polymorphic subsyst... | KBS-Labs/dataknobs | packages/bots/src/dataknobs_bots/bot/config.py | .py | cdb43596572dd943 | 7.3 | 3 |
"""Bot execution context."""
from dataclasses import dataclass, field
from typing import Any
@dataclass
class BotContext:
"""Runtime context for bot execution.
Supports dict-like access for dynamic attributes via request_metadata.
Use `context["key"]` or `context.get("key")` for dynamic data.
Attri... | KBS-Labs/dataknobs | packages/bots/src/dataknobs_bots/bot/context.py | .py | 5c848d00c1e8d7b2 | 7.3 | 3 |
"""Bot manager for multi-tenant bot instances.
.. deprecated::
This module is deprecated. Use :class:`dataknobs_bots.bot.BotRegistry` instead,
which provides the same functionality plus persistent storage backends,
environment-aware configuration resolution, and TTL-based caching.
For simple in-memory... | KBS-Labs/dataknobs | packages/bots/src/dataknobs_bots/bot/manager.py | .py | 8b6900ee8976ec72 | 7.3 | 3 |
"""Delivery seam for the shared monolithic tool-execution loop.
``DynaBot`` runs the *same* cap / wall-clock-timeout / execute / budget /
LLM-re-call / cap-warning lifecycle in two non-phased delivery modes:
buffered (``chat``) and streaming (``stream_chat``). Historically each mode
carried its own hand-written copy ... | KBS-Labs/dataknobs | packages/bots/src/dataknobs_bots/bot/tool_loop.py | .py | 8375940d420f4030 | 7.3 | 3 |
"""Per-turn pipeline state for DynaBot."""
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from enum import Enum
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from dataknobs_llm import LLMResponse, LLMStreamResponse
from dataknobs_llm.llm.model_profile imp... | KBS-Labs/dataknobs | packages/bots/src/dataknobs_bots/bot/turn.py | .py | 50af4a50c8d03273 | 7.3 | 3 |
"""Bot capability validation utilities.
Infers required LLM capabilities from bot configuration structure and
validates them against environment resources. Provides defense-in-depth:
- **Pre-deployment** (Layer 1): Warn during registration
- **Startup** (Layer 2): Reject at bot creation time
Capabilities are assigne... | KBS-Labs/dataknobs | packages/bots/src/dataknobs_bots/bot/validation.py | .py | b724131db956c4c9 | 7.3 | 3 |
"""Draft management for interactive configuration creation.
Provides file-based draft persistence during wizard-driven config building.
Drafts are saved incrementally as users progress through stages, with
automatic cleanup of stale drafts.
Example:
```python
from pathlib import Path
from dataknobs_bots.c... | KBS-Labs/dataknobs | packages/bots/src/dataknobs_bots/config/drafts.py | .py | f332d8421ddc1545 | 7.3 | 3 |
#! /usr/bin/env python
import os
import shutil
import subprocess
import tempfile
import sys
import logging
import argparse
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
DEV_DIR = os.path.join(os.getcwd(), "_d... | canonical/charmed-etcd-operator | docs/_dev/get_vale_conf.py | .py | 36cbe01b418d0837 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
from collections import namedtuple
from typing import Dict, List, Optional
from charms.data_platform_libs.v0.data_interfaces import (
EventHandlers,
ProviderData,
RequirerData,
RequirerEvent... | canonical/charmed-etcd-operator | lib/charms/data_platform_libs/v0/azure_storage.py | .py | 01e7bd61600b4e9d | 7.24 | 2 |
# Copyright 2022 Canonical Ltd.
#
# 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 by applicable law or agreed to in writing, s... | canonical/charmed-etcd-operator | lib/charms/rolling_ops/v0/rollingops.py | .py | fe23a7934cbb37bd | 7.24 | 2 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Utility functions related to certificates."""
import logging
from cryptography import x509
logger = logging.getLogger(__name__)
def leaf_certificate(certificate_chain: str) -> str:
"""Extract the leaf certificate from a certificate c... | canonical/charmed-etcd-operator | src/common/certificates.py | .py | e80d06a869cdd31c | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
"""Objects representing the state of EtcdOperatorCharm."""
import logging
from typing import TYPE_CHECKING, Dict, Set
from charmlibs.interfaces.tls_certificates import (
ProviderCertificate,
)
from data_platform_help... | canonical/charmed-etcd-operator | src/core/cluster.py | .py | ef4c1a2cf4661676 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
"""Collection of state objects for the Etcd relations, apps and units."""
import json
import logging
from dataclasses import dataclass
from typing import Any, final
from charmlibs.interfaces.tls_certificates import Priva... | canonical/charmed-etcd-operator | src/core/models.py | .py | 4ad3f002b90ca4c2 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Limited
# See LICENSE file for licensing details.
"""External clients related event handlers."""
import logging
import time
from typing import TYPE_CHECKING
from charms.certificate_transfer_interface.v1.certificate_transfer import (
CertificatesAvailableEvent,
... | canonical/charmed-etcd-operator | src/events/external_clients.py | .py | 82c479600db29996 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Handlers for in-place upgrades."""
import dataclasses
import logging
from typing import TYPE_CHECKING
import charm_refresh
from common.exceptions import EtcdUpgradeError
from literals import TLSCARotationState, TLSSt... | canonical/charmed-etcd-operator | src/events/refresh.py | .py | e5857a55a821f88e | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""TLS related event handlers."""
import logging
from typing import TYPE_CHECKING
from charmlibs.interfaces.tls_certificates import (
CertificateAvailableEvent,
CertificateRequestAttributes,
TLSCertificate... | canonical/charmed-etcd-operator | src/events/tls.py | .py | 241fc7938e0a5db8 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
"""Collection of global literals for the etcd charm."""
from dataclasses import dataclass
from enum import StrEnum
from typing import Literal
from ops.model import StatusBase
SNAP_NAME = "charmed-etcd"
SNAP_SERVICE = "e... | canonical/charmed-etcd-operator | src/literals.py | .py | fe49f8c8f58a7bfe | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Manager for all backup/restore related tasks."""
import logging
from datetime import datetime
import boto3
from azure.core.exceptions import AzureError, ResourceExistsError
from azure.storage.blob import ContainerClie... | canonical/charmed-etcd-operator | src/managers/backup.py | .py | 40354e9cb414f9c7 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
"""Manager for handling configuration building + writing."""
import logging
import re
from pathlib import Path
import yaml
from data_platform_helpers.advanced_statuses.models import StatusObject
from data_platform_helper... | canonical/charmed-etcd-operator | src/managers/config.py | .py | abe48944925ef2da | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Manager for handling external clients."""
import logging
from pathlib import Path
from charmlibs.interfaces.tls_certificates import Certificate, TLSCertificatesError
from data_platform_helpers.advanced_statuses.models... | canonical/charmed-etcd-operator | src/managers/external_clients.py | .py | 35fb1b0538cbfe7a | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Manager for computing upgrades related statuses."""
import logging
import charm_refresh
import ops
from data_platform_helpers.advanced_statuses.models import StatusObject
from data_platform_helpers.advanced_statuses.p... | canonical/charmed-etcd-operator | src/managers/upgrades.py | .py | 3a2389d141bcf4b8 | 7.24 | 2 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Statuses for the Charmed Etcd Operator.
This module defines various status enums that represent the state of the charm,
"""
from enum import Enum
from data_platform_helpers.advanced_statuses.models import StatusObject
class CharmStatuses... | canonical/charmed-etcd-operator | src/statuses.py | .py | a6e7c88085edf31e | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
"""Implementation of WorkloadBase for running on VMs."""
import logging
import shutil
import subprocess
from pathlib import Path
from platform import machine
from socket import socket
from typing import List
from charmli... | canonical/charmed-etcd-operator | src/workload.py | .py | e387d03cb479d0b3 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
from jubilant import Juju
from literals import INTERNAL_USER, PEER_RELATION
from statuses import BackupStatuses
from ..helpers import (
APP_NAME,
get_cluster_endpoints,
get_cluster_members,
... | canonical/charmed-etcd-operator | tests/integration/backup/test_restore_verification_failed.py | .py | e39c12bca2764a7a | 7.74 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
import json
import logging
from datetime import timedelta
import pytest
from charmlibs.interfaces.tls_certificates import (
Certificate,
CertificateRequestAttributes,
PrivateKey,
generate_csr,
)
from jubil... | canonical/charmed-etcd-operator | tests/integration/client_relations/test_client_relations_cross_model.py | .py | b1b62f795527f074 | 7.74 | 2 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
import json
import logging
import pathlib
import subprocess
from platform import machine
import jubilant
import pytest
from jubilant import Juju
from tenacity import Retrying, stop_after_delay, wait_fixed
MICROK8S_CLOUD_NAME = "mk8s"
CONCIERGE_... | canonical/charmed-etcd-operator | tests/integration/conftest.py | .py | 78d10a302ff7958e | 7.74 | 2 |
# Copyright (c) 2026, BuFf0k and contributors
# For license information, please see license.txt
from __future__ import annotations
import frappe
from frappe import _
from frappe.utils import today
from ir import permissions
from ir.industrial_relations.doctype.demotion_form.demotion_form import restore_employee_posi... | buff0k/ir | ir/controllers/demotion_expiry.py | .py | f57ede1ac3c82a19 | 7.35 | 4 |
# Copyright (c) 2026, BuFf0k and contributors
# For license information, please see license.txt
import frappe
from frappe.utils import getdate, nowdate
MIN_VALID_DATE = getdate("2000-01-01") # adjust if your org legitimately has earlier relieving dates
def run_daily():
"""
Daily job (SAFE VERSION):
... | buff0k/ir | ir/controllers/employee_termination_sync.py | .py | 36b5b7baae0527f4 | 7.35 | 4 |
# Copyright (c) 2026, buff0k and contributors
# For license information, please see license.txt
import frappe
from frappe.utils import get_url, getdate, today
from ir.industrial_relations.email_style import EMAIL_STYLE_BLOCK, email_header, greeting, intro, signoff
from ir.industrial_relations.utils import filter_rows... | buff0k/ir | ir/controllers/fixed_term_expiry_lapsed.py | .py | 51dcc3b281f06d4f | 7.35 | 4 |
"""Backwards-compatible shim for the original module's two functions.
The original ``langchain_helper`` could not be imported at all: line 15 read
llm = ChatGoogleGenerativeAI(model=..., google_api_key=apikey)
with ``apikey`` never defined, so ``import langchain_helper`` raised
``NameError`` before anything ran.... | HarshdipSaha/Youtube-Comment-RAG- | langchain_helper.py | .py | 12ec24318ab6dcbd | 7 | 0 |
"""Shared fixtures. Everything here is offline and deterministic."""
import pytest
from ytrag.embed import HashingEmbedder
from ytrag.models import Comment
NOW = 1_700_000_000.0
def _c(cid, text, likes, author, hours_ago, valence=0.0, emojis=""):
return Comment(
cid=cid,
text=text,
auth... | HarshdipSaha/Youtube-Comment-RAG- | tests/conftest.py | .py | 1a53399ace8fb34e | 7.5 | 0 |
"""Exact answers, computed over the whole corpus rather than retrieved from it.
Every assertion here is a number that can be checked by hand against the
fixture. That is the point: these answers are arithmetic, not inference, and
they must be right every single time rather than usually.
"""
import pytest
from ytrag.... | HarshdipSaha/Youtube-Comment-RAG- | tests/test_aggregate.py | .py | 2ec4b9db286e42f5 | 7.5 | 0 |
"""The citation guard: catching claims the evidence does not support.
RAG's characteristic failure is not inventing text out of nothing -- it is
producing a fluent, well-cited-looking answer whose *numbers* were never in the
context. Those are the claims users trust most and check least, so they are the
ones worth ver... | HarshdipSaha/Youtube-Comment-RAG- | tests/test_citations.py | .py | 71cd802f833c2328 | 7.5 | 0 |
"""The CLI seam: argument handling and exit codes.
Driven through ``main()`` with argv, so these exercise the same path a user
takes rather than calling the command functions directly.
"""
import json
import pytest
from ytrag.cli import main
from ytrag.engine import CommentRAG
from ytrag.ingest import to_csv
@pyt... | HarshdipSaha/Youtube-Comment-RAG- | tests/test_cli.py | .py | e4b70911fc9d0ad7 | 7.5 | 0 |
"""Opinion clustering and consensus weighting -- the core of the approach.
A single retrieved comment tells you someone said something. It cannot tell you
how many people agreed. These tests pin down the behaviour that difference buys.
"""
import pytest
from ytrag.cluster import (
ConsensusWeights,
cluster_o... | HarshdipSaha/Youtube-Comment-RAG- | tests/test_cluster.py | .py | 2bc64ca44ff43340 | 7.5 | 0 |
"""The benchmark itself has to be trustworthy, so it is tested too."""
import pytest
from ytrag.evaluate import (
NaiveTopKRAG,
exact_accuracy,
exact_cases,
report,
retrieval_precision,
run,
)
from ytrag.store import HybridStore
#: Hand-labelled relevance over the fixture corpus. These are th... | HarshdipSaha/Youtube-Comment-RAG- | tests/test_evaluate.py | .py | b2343705fd8089f5 | 7.5 | 0 |
"""Provider selection and the offline extractive backend.
No test here touches the network. The hosted providers are checked only for
their selection and error behaviour, which is where they actually go wrong.
"""
import pytest
from ytrag.cluster import cluster_opinions, score_evidence
from ytrag.llm import Extracti... | HarshdipSaha/Youtube-Comment-RAG- | tests/test_llm.py | .py | f2ac7dd71f1b4cad | 7.5 | 0 |
"""Figures for the comment section.
Three charts, each answering a question the numbers alone answer badly:
* **Opinion share** -- how the comment section divides, by people and by likes
side by side. These two routinely disagree, and the disagreement is the
finding: a view held by many people with few likes is a... | HarshdipSaha/Youtube-Comment-RAG- | ytrag/charts.py | .py | c6fa0171703b7a19 | 7 | 0 |
"""Verify that an answer's claims trace back to the evidence it was given.
RAG rarely fails by inventing whole sentences. It fails by producing a fluent,
plausibly-cited paragraph containing a number that was never in the context --
"73% of viewers disliked the pacing" when the context said 31 of 120. Those are
exactl... | HarshdipSaha/Youtube-Comment-RAG- | ytrag/citations.py | .py | 03c6fe7ccf4a5049 | 7 | 0 |
"""Consensus-Weighted Retrieval (CWR).
Ordinary RAG retrieves the top-k *chunks* nearest a query. Over a comment
section that is the wrong unit of evidence, for two reasons:
1. **Redundancy.** If 200 people make the same point, top-k returns five
near-identical copies of it and the remaining 195 are invisible. The... | HarshdipSaha/Youtube-Comment-RAG- | ytrag/cluster.py | .py | c2ce1ef9ff186d4c | 7 | 0 |
"""Text -> vector, behind one small interface.
The default backend is :class:`HashingEmbedder`: a deterministic, dependency-free
embedder built from hashed word and character n-grams. It exists so the whole
pipeline -- and the whole test suite -- runs with no model download and no
network. When ``sentence-transforme... | HarshdipSaha/Youtube-Comment-RAG- | ytrag/embed.py | .py | 59f65e16f63fccb8 | 7 | 0 |
"""Measure this pipeline against the design it replaces.
Two comparisons, deliberately kept separate because they answer different
questions and one of them is much weaker evidence than the other.
**Exact questions** (:func:`exact_accuracy`). Ground truth is computed by
exhaustive scan, then each system is asked the ... | HarshdipSaha/Youtube-Comment-RAG- | ytrag/evaluate.py | .py | 37e4be3d7cf72604 | 7 | 0 |
"""Getting comments in: from YouTube, from CSV, or from a list of dicts.
Three entry points, because the original project had one and it was the fragile
one. ``from_youtube`` needs the network and a working downloader;
``from_csv`` and ``from_records`` do not, which is what makes the pipeline
testable and what lets th... | HarshdipSaha/Youtube-Comment-RAG- | ytrag/ingest.py | .py | ca794bfb389c813e | 7 | 0 |
"""Answer generation, behind one interface with a working offline default.
The default backend is :class:`ExtractiveLLM`, which needs no API key and no
network. It is not a fallback stub: it composes a real proportional summary from
the evidence -- "a majority view (54.5%, 6 comments, 2,020 likes) says X, while
27.3% ... | HarshdipSaha/Youtube-Comment-RAG- | ytrag/llm.py | .py | 6a49c48ddf9d92a3 | 7 | 0 |
"""Core domain types.
The vocabulary here is the project's domain language; test names and interfaces
should use these words. A *comment* is one YouTube comment with its social
metadata. An *opinion cluster* is a group of comments that say substantially
the same thing, and it is the unit this system retrieves -- not... | HarshdipSaha/Youtube-Comment-RAG- | ytrag/models.py | .py | 3d206ddec22397c6 | 7 | 0 |
"""Turn raw downloader dictionaries into :class:`~ytrag.models.Comment` records.
Two decisions here differ from the original project and matter downstream:
1. Likes arrive as display strings (``"1.2K"``), so they are parsed to integers.
Sorting text lexicographically puts ``"9"`` above ``"1.2K"``, which is how a
... | HarshdipSaha/Youtube-Comment-RAG- | ytrag/normalize.py | .py | 48b889c4e13f1e5f | 7 | 0 |
"""清華大學公告爬蟲 - 公告內容爬蟲"""
from typing import List, Optional
from pathlib import Path
import re
import scrapy
from nthu_scraper.utils.constants import (
ANNOUNCEMENTS_FOLDER,
ANNOUNCEMENTS_JSON_PATH,
ANNOUNCEMENTS_LIST_PATH,
)
from nthu_scraper.utils.file_utils import load_json, save_json
class Announcemen... | NTHU-SA/NTHU-Data-Scraper | nthu_scraper/spiders/nthu_announcements_item.py | .py | 0f3d79c8ff7964f6 | 7.3 | 3 |
"""清華大學公告爬蟲 - 公告列表爬蟲"""
import re
from typing import Dict
import scrapy
from scrapy_playwright.page import PageMethod
from nthu_scraper.utils.constants import (
ANNOUNCEMENTS_LIST_PATH,
DIRECTORY_PATH,
LANGUAGES,
RPAGE_DOMAIN_SUFFIX,
)
from nthu_scraper.utils.file_utils import load_json, save_json
fr... | NTHU-SA/NTHU-Data-Scraper | nthu_scraper/spiders/nthu_announcements_list.py | .py | 62a31aff9a9f7d24 | 7.3 | 3 |
"""清華大學公車資訊爬蟲 - 重構版本"""
import re
import ast
from pathlib import Path
from typing import Any, Dict, List, Optional
import scrapy
from nthu_scraper.utils.constants import (
ANNOUNCEMENTS_JSON_PATH,
BUSES_FOLDER,
BUSES_JSON_PATH,
)
from nthu_scraper.utils.file_utils import load_json, save_json
# 公車路線配置
BU... | NTHU-SA/NTHU-Data-Scraper | nthu_scraper/spiders/nthu_buses.py | .py | f72055c7c2b33acd | 7.3 | 3 |
import json
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, Dict, List
import scrapy
from nthu_scraper.utils.constants import DATA_FOLDER
from nthu_scraper.utils.file_utils import save_json
# --- 全域參數設定 ---
OUTPUT_FOLDER = DATA_FOLDER / "courses"
LATEST_JSON = DATA_FOLDER /... | NTHU-SA/NTHU-Data-Scraper | nthu_scraper/spiders/nthu_courses.py | .py | 7c9bc091a2b9812b | 7.3 | 3 |
import json
import re
from typing import Any, List
import scrapy
from nthu_scraper.utils.constants import DATA_FOLDER
from nthu_scraper.utils.file_utils import save_json
# 預先編譯正規表達式(改善效能與可讀性)
DINING_REGEX = re.compile(r"const restaurantsData = (\[.*?)(?:\s+renderTabs)", re.S)
OUTPUT_PATH = DATA_FOLDER / "dining.json... | NTHU-SA/NTHU-Data-Scraper | nthu_scraper/spiders/nthu_dining.py | .py | 4e8245e112e1775e | 7.3 | 3 |
import json
from pathlib import Path
from typing import Any, Dict, List
import scrapy
from nthu_scraper.utils.constants import DATA_FOLDER
from nthu_scraper.utils.file_utils import save_json
# --- 全域參數設定 ---
COMBINED_JSON_FILE = DATA_FOLDER / "directory.json"
URL_PREFIX = "https://tel.net.nthu.edu.tw/nthusearch/"
#... | NTHU-SA/NTHU-Data-Scraper | nthu_scraper/spiders/nthu_directory.py | .py | 939ea495d714417f | 7.3 | 3 |
import json
from pathlib import Path
from typing import Dict
import scrapy
from nthu_scraper.utils.constants import DATA_FOLDER
from nthu_scraper.utils.file_utils import save_json
# --- 全域參數設定 ---
OUTPUT_PATH = DATA_FOLDER / "maps"
COMBINED_JSON_FILE = DATA_FOLDER / "maps.json"
MAP_URLS = {
"MainZH": "https://c... | NTHU-SA/NTHU-Data-Scraper | nthu_scraper/spiders/nthu_maps.py | .py | 0d56869651cc2943 | 7.3 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.