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 2026 Canonical Ltd. # See LICENSE file for licensing details. """Charm library for the temporal-worker-info Juju relation. `temporal-worker-info` parallels `temporal-host-info`: the worker charm **provides** the namespace and task queue it serves so downstream charms know where to run workflows. * Import...
canonical/maas-site-manager-k8s-operator
lib/charms/temporal_worker_k8s/v0/temporal_worker_info.py
.py
b5901cf37fe83333
7.24
2
"""MAAS Site Manager API client.""" import logging import requests logger = logging.getLogger(__name__) class AuthError(Exception): """Failed to authenticate with the API.""" class ApiError(Exception): """API client error.""" class SiteManagerClient: """Site Manager API client.""" def __init__...
canonical/maas-site-manager-k8s-operator
src/api.py
.py
da96d5950a8bb318
7.24
2
import os from .solver import solve import config def clear_console() -> None: """ Clear the console. :return: None """ os.system('cls' if os.name == 'nt' else 'clear') def prompt_user( min_letters: int = config.MIN_LENGTH, max_letters: int = config.DFLT_MAX_LETTERS, dst_dir: str = c...
arvinduh/anagram_solver
solver/console.py
.py
8dd23625bea21a26
7
0
import os import config def is_anagram( word: str, letters: str ) -> bool: """ Check if a word is an anagram of the given letters. :param word: The word to check. :param letters: The letters to check against. :return: True if the word is an anagram of the letters, False otherwise...
arvinduh/anagram_solver
solver/solver.py
.py
313c42bc69b844de
7
0
""" Module to access functions for Dijkstra's Algorithm. """ from dsa.heap import PriorityQueue from dsa.graph import Graph def dijkstra_tables(graph: Graph, start: str, end: str, debug: bool = False) -> tuple: """ Helper function that returns a weight table and a predecessor table using Dijkstra's Algorithm....
ucxinstructor/dsa_package
src/dsa/dijkstra.py
.py
fded833821fa0e24
7.35
4
""" Module to access functions for a clearer visual representation of certain data structures. """ import math def heap_print(heap): """ Print a heap from root to leaves. Args: heap: The heap object to print. """ if not heap or heap.count() == 0: return _array_print(heap.count...
ucxinstructor/dsa_package
src/dsa/pretty_print.py
.py
a880556d8a201c6a
7.35
4
""" Module to access functions for Prim's Algorithm. """ from dsa.graph import Graph from dsa.heap import PriorityQueue def prim(graph: Graph, start: str, debug: bool = False) -> tuple: """ Helper function that returns a weight table and a predecessor table for Prim's Algorithm. Args: graph (Grap...
ucxinstructor/dsa_package
src/dsa/prim.py
.py
51cfa071c6ec5376
7.35
4
import unittest from dsa.array import Array, DynamicArray, CircularArray class TestArray(unittest.TestCase): def setUp(self): """Set up common test objects.""" self.array = Array(capacity=5) self.array_with_elements = Array([1, 2, 3], capacity=5) self.dynarray = DynamicArray(capac...
ucxinstructor/dsa_package
tests/test_array.py
.py
dc16c81fae4ee08a
7.85
4
import unittest from dsa.doublylinkedlist import DoublyLinkedList, Node class TestDoublyLinkedList(unittest.TestCase): # --- Helper Method --- def verify_integrity(self, dll): """Custom helper to ensure all next/prev links and head/tail are consistent.""" if dll.count == 0: self.as...
ucxinstructor/dsa_package
tests/test_doublylinkedlist.py
.py
a9495e5ba20d6188
7.85
4
import unittest from dsa.singlylinkedlist import LinkedList, Node class TestLinkedList(unittest.TestCase): # --- Initialization & Conversion --- def test_initialization(self): """Test empty init and manual node linking.""" ll = LinkedList() self.assertEqual(ll.count, 0) self.as...
ucxinstructor/dsa_package
tests/test_singlylinkedlist.py
.py
dc895276a881a013
7.85
4
from datasets import load_dataset # helpful-base サブセットをロード dataset = load_dataset("Anthropic/hh-rlhf", data_dir="helpful-base") # または helpful-base / helpful-online なども使えます # dataset = load_dataset("Anthropic/hh-rlhf", data_dir="helpful-base") import re def split_dialogue(text): """ "Human: ...\nAssistant: .....
Shinichi0713/LLM-fundamental-study
RLHF/src/dpo_demo/src/collect_dataset.py
.py
f32448943219da48
7.3
3
# Copyright 2020-2026 The HuggingFace Team. All 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 by appl...
Shinichi0713/LLM-fundamental-study
RLHF/src/eval_sentiment/trainer.py
.py
77250f0dd1594148
7.3
3
import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer # ============================ # 1. モデルとトークナイザの準備 # ============================ model_name = "mistralai/Mistral-7B-v0.1" # 例:軽量モデルを想定 model = AutoModelForCausalLM.from_pret...
Shinichi0713/LLM-fundamental-study
RLHF/src/ipo_trial/reference/model.py
.py
083a761c42b9c972
7.3
3
""" TROLL目的関数 vs PPOクリップ目的関数 の比較。 論文の主張: 「PPOクリップはクリップ範囲外で勾配を完全に打ち切るが、 TROLLは射影を通して常に微分可能で勾配が流れ続ける」 これを有限差分 (finite difference) で数値的に検証する。 (このマシンにはPyTorchをインストールできない [ネットワーク制限] ため、 NumPyの数値微分でアルゴリズムの性質そのものを検証する。 実運用版の自動微分コードは troll_torch.py を参照。) """ import numpy as np from troll_numpy_core import sparsify, p...
Shinichi0713/LLM-fundamental-study
RLHF/src/troll/troll_loss_compare.py
.py
01645e829f2d5c93
7.3
3
""" TROLL (Trust Regions improve Reinforcement Learning for Large Language Models) のコアアルゴリズムを NumPy で実装した検証用コード。 論文: Becker, Freymuth, Thilges, Otto, Neumann (ICLR 2026, Oral) https://arxiv.org/abs/2510.03817 公式実装: https://github.com/niklasfreymuth/TROLL (verl フレームワーク + 依存ライブラリ pbecker93/discrete_trpl ...
Shinichi0713/LLM-fundamental-study
RLHF/src/troll/troll_numpy_core.py
.py
9f3cc82832fcba54
7.3
3
""" TROLL (Trust Regions improve Reinforcement Learning for Large Language Models) の PyTorch (autograd 対応) 実装。 論文: https://arxiv.org/abs/2510.03817 (ICLR 2026, Oral) 公式実装: https://github.com/niklasfreymuth/TROLL NOTE: このコードは troll_numpy_core.py / troll_loss_compare.py / troll_gradient_sweep.py で検証したアルゴリズムをそのまま PyTor...
Shinichi0713/LLM-fundamental-study
RLHF/src/troll/troll_torch.py
.py
77126a48b7fa23aa
7.3
3
import torch import torch.nn as nn import torch.nn.functional as F class SimplePPOTrainer: def __init__(self, model, optimizer, eps_clip=0.2, gamma=0.99): self.model = model self.optimizer = optimizer self.eps_clip = eps_clip # 更新の制限幅 self.gamma = gamma # 割引率(将来の報酬の重視度) ...
Shinichi0713/LLM-fundamental-study
adaptive_learning/RLHF/src/reference/ppo_trainer_simple.py
.py
13eb30f08fdb09fa
7.3
3
import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple class MultiQueryAttention(nn.Module): """ Multi-Query Attention (MQA) の実装 - Queryは複数ヘッド、Key/Valueは1ヘッド(全Queryで共有) """ def __init__( self, embed_dim: int, num_heads: int, ...
Shinichi0713/LLM-fundamental-study
attention/MQA/mqa_v1.py
.py
8424232c3ce9a918
7.3
3
import torch import torch.nn as nn import torch.nn.functional as F class GatedSDPA(nn.Module): def __init__(self, d_model, num_heads): super().__init__() self.num_heads = num_heads self.d_head = d_model // num_heads # ゲート用の学習パラメータ (W_theta) # 各ヘッドが独自のゲート値を持てるように、ヘッド...
Shinichi0713/LLM-fundamental-study
attention/gated_attention/src/gated_attention.py
.py
37cf1e387bf49176
7.3
3
import torch import torch.nn as nn import torch.nn.functional as F import math class MultiHeadAttention(nn.Module): """ シンプルなマルチヘッドself-attention(デコーダ用) KVキャッシュを保持・更新する """ def __init__(self, d_model=512, n_heads=8): super().__init__() self.d_model = d_model self.n_heads = n...
Shinichi0713/LLM-fundamental-study
attention/kv_cache/src/kv_cache_v2.py
.py
b5d8a64d459e8d1b
7.3
3
from typing import Any, Dict, Optional class SimpleKVCache: """ 単純なキー・バリューキャッシュ(辞書ベース) """ def __init__(self) -> None: self._store: Dict[str, Any] = {} def put(self, key: str, value: Any) -> None: """キーと値を保存""" self._store[key] = value def get(self, key: str) -> Optio...
Shinichi0713/LLM-fundamental-study
attention/kv_cache/src/kv_cache_v3.py
.py
08047f7dd8a9e146
7.3
3
import torch from typing import Dict, List, Optional, Tuple class KVCache: """ Transformer推論用のKVキャッシュ(PyTorchテンソル版) - バッチ・シーケンス長・ヘッド数・ヘッド次元に対応 - 各レイヤ・各ヘッドごとにKey/Valueテンソルを保持 - 逐次推論時に過去のKVを蓄積し、自己注意で再利用 """ def __init__(self) -> None: # 構造: {layer_idx: {"k": Tensor, "v": Tensor}} ...
Shinichi0713/LLM-fundamental-study
attention/kv_cache/src/kv_cache_v4.py
.py
58602d6f07027299
7.3
3
import torch import torch.nn as nn import torch.nn.functional as F class MultiHeadAttention(nn.Module): def __init__(self, d_model, n_heads, max_seq_len=1024): super().__init__() self.d_model = d_model self.n_heads = n_heads self.head_dim = d_model // n_heads self.q_proj =...
Shinichi0713/LLM-fundamental-study
attention/kv_cache/src/kv_core.py
.py
4f23b1dc576cced6
7.3
3
import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple class AdvancedMultiHeadAttention(nn.Module): """ 高度なKVキャッシュ付きMultiHeadAttention - バッチ対応のKVキャッシュ - 因果マスク+パディングマスク - スライディングウィンドウ - 事前割り当て(preallocated cache) """ def __init__( ...
Shinichi0713/LLM-fundamental-study
attention/kv_cache/src/model.py
.py
e7f6c5be0a0f41ef
7.3
3
import torch from typing import Optional, Tuple class SimpleKVCache: """ 簡単なKVキャッシュ(PyTorchテンソル版) - バッチ1, ヘッド1, 可変シーケンス長, 固定ヘッド次元 - 過去のKey/Valueを蓄積し、自己注意で再利用 """ def __init__(self) -> None: self.k_cache: Optional[torch.Tensor] = None # [1, 1, seq_len, head_dim] self.v_cache: O...
Shinichi0713/LLM-fundamental-study
attention/kv_cache/src/simples.py
.py
28c15633dc5771bf
7.3
3
import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat class MambaBlock(nn.Module): def __init__(self, d_model, d_state=16, d_conv=4, expand=2): super().__init__() self.d_model = d_model self.d_state = d_state self.d_conv = d_conv ...
Shinichi0713/LLM-fundamental-study
attention/mamba_attention/src/reference/mamaba_block.py
.py
d630b4c4497b0a24
7.3
3
import torch import torch.nn as nn import matplotlib.pyplot as plt import numpy as np from mamba_ssm import Mamba def mamba_internal_attention_visualization(): """ Mambaの内部アテンション(selective SSMの選択パターン)を可視化する """ # 設定 batch_size = 1 seq_len = 16 d_model = 16 d_state = 16 d_conv = 4 ...
Shinichi0713/LLM-fundamental-study
attention/mamba_attention/src/show_attn_v3.py
.py
b1bfff531fc7b23f
7.3
3
import os from .solver import Solver import config def clear_console() -> None: """ Clear the console. :return: None """ os.system('cls' if os.name == 'nt' else 'clear') def get_word(word_length: int = config.WORD_LENGTH) -> str: """ Prompt the user for word that the user inputted :r...
arvinduh/wordle_solver
solver/console.py
.py
e38aad9094477a7d
7
0
import config from .word_info import WordInfo, State from copy import deepcopy class Solver: """ Solves Wordle Puzzles based on Given Information :var remaining: The remaining words to consider :var word_info: The WordInfo object containing information about the word :var words: The words that have...
arvinduh/wordle_solver
solver/solver.py
.py
efb31ad21ca3894c
7
0
from enum import Enum import config class State(Enum): """ Enum for the state of a position in a wordle game """ c = 1 i = 2 n = 3 class PositionInfo: """ Stores information of a position in a wordle game :var found: whether the letter has been found :var correct: the correct...
arvinduh/wordle_solver
solver/word_info.py
.py
2088ed5475224faa
7
0
import sys, re, os, optparse VALIDATION_ERROR_CODE = 99 OUTPUT_FILE_NAME = "formatted_gene_list.txt" MAX_ALLOWED_GENES = 1000000 MAX_ID_LENGTH = 80 VALID_DELIM = r"[\s,;]+" VALID_GENE_ID = r"[a-zA-Z0-9\(\)\.\:_-]*$" class ValidationException(BaseException): """ A validation error. """ pass def execut...
VEuPathDB/vdi-plugin-genelist
lib/python/eupath/GeneListDatasetImporter.py
.py
bff70b01c04c9c65
7
0
"""Console script for openapi2callables.""" import click import requests from .parse import get_spec, parse_spec from .server import app @click.group() def cli(): ... @cli.command() @click.argument("schema_url") def parse(schema_url): """Parse an OpenAPI schema from a remote URL.""" try: spec = ge...
andrewbolster/openapi2callables
openapi2callables/cli.py
.py
bb158cddbc801a3b
7.35
4
"""Main module.""" from datetime import date, datetime from enum import Enum from importlib.metadata import version from typing import Dict, List, Optional, Union import uvicorn from fastapi import Body, Cookie, FastAPI, Header, HTTPException, Path, Query, status from pydantic import BaseModel, EmailStr, Field app =...
andrewbolster/openapi2callables
openapi2callables/server.py
.py
53648dd85becae3c
7.35
4
import abc import json import logging import time from dataclasses import dataclass, field from typing import Any, Callable, Dict, Set import requests @dataclass class Tool(abc.ABC): """ Abstract Base Class for Tool Calling """ operationId: str description: str parameters: Dict[str, Any] = f...
andrewbolster/openapi2callables
openapi2callables/tools.py
.py
73ca400902d1c6ea
7.35
4
"""Bench for AdvancedTokenizer.tokenize()'s morpheme-length cap fix (2026-07-21 audit round 2, HIGH). tokenize() used to enumerate EVERY substring of every word with no length cap: O(word_len**2) substrings, each up to O(word_len) to slice/hash -> O(word_len**3) total per pathological word (a long URL, a base64/JS blo...
fingoldo/pyutilz
_benchmarks/bench_morpheme_tokenize.py
.py
780a36829daf146d
7.24
2
""" Performance benchmarks for pandaslib.py optimizations. Run with: python -m _benchmarks.bench_pandaslib This verifies that refactored code is actually faster than the original. Standalone, deliberately-non-pytest script (no `test_` prefix, lives outside `tests/`) alongside bench_classify_column_types.py / bench_ge...
fingoldo/pyutilz
_benchmarks/bench_pandaslib.py
.py
ace6966fb5516dd7
7.24
2
""" Automated refactoring script for pyutilz library. Fixes: 1. Wildcard imports from typing 2. Mutable default arguments 3. Other common anti-patterns Run with: python scripts/auto_refactor.py """ import os import re from pathlib import Path from typing import List, Tuple # Root directory of pyutilz PYUTILZ_ROOT =...
fingoldo/pyutilz
scripts/auto_refactor.py
.py
bb769c20f5018561
7.24
2
"""PyUtilz - Comprehensive Python utilities.""" from .version import __version__ import sys import types from importlib import import_module __all__ = ["__version__", "core", "data", "database", "web", "cloud", "text", "system", "dev", "llm"] # Module aliases for backward compatibility # NOTE: Don't create aliases ...
fingoldo/pyutilz
src/pyutilz/__init__.py
.py
ec62fd95cce74b0a
7.24
2
"""Content-addressable disk cache for repeated heavy computations. Fits a specific niche: a deterministic transform of (large numpy/pandas inputs, params) whose cost dominates a single call, invoked repeatedly across hyperparam sweeps / ablations / incremental data updates where the inputs recur exactly or near-exactl...
fingoldo/pyutilz
src/pyutilz/core/disk_cache.py
.py
27377fb752d87028
7.24
2
"""Token-counting helpers for OpenAI-family chat models. Thin wrappers over tiktoken. ``num_tokens_from_string`` delegates single-string counting to :func:`pyutilz.llm.token_counter.count_tokens` (the canonical, tiktoken-backed, len//4-fallback implementation) when the requested encoding is the default cl100k_base, av...
fingoldo/pyutilz
src/pyutilz/core/openai.py
.py
a012edd65a9e80fd
7.24
2
"""Centralised sha256-sidecar verification + safe pickle helpers, shared across projects. Originally built inside mlframe (four separate pickle entry points had converged on the same sidecar pattern independently -- an attacker who could plant a file in a cache directory would be deserialised on the next load without ...
fingoldo/pyutilz
src/pyutilz/core/safe_pickle.py
.py
f0972d4cc6bc0ba1
7.24
2
"""A git-tracked gzip backup for a machine-local cache, with auto-restore when the local copy is missing or empty. Ported from a downstream project's own LLM-cache durability fix (`autopsia`, 2026-08-13): a multi-hour paid LLM classification run's verdict cache lived only under ``~/.cache`` with zero backup anywhere, ...
fingoldo/pyutilz
src/pyutilz/data/git_checkpoint_cache.py
.py
5a884b86589f25ed
7.24
2
"""Dataframe IO helpers: load/read, concat-and-flush, multi-file merging and pyarrow parquet reads. Split out of the historical flat ``pyutilz.data.pandaslib`` module; re-exported from the package ``__init__`` to preserve the public import surface. """ from ._common import ( gc, os, pd, glob, join...
fingoldo/pyutilz
src/pyutilz/data/pandaslib/io_ops.py
.py
d85af1d0d5a0ebac
7.24
2
"""Helpers for safely reading/writing Delta Lake tables, including local-path detection and file-locked writes.""" import os import tempfile import hashlib import logging from typing import Any from urllib.parse import urlparse FileLock: Any Timeout: Any try: from filelock import FileLock, Timeout # type: ignore...
fingoldo/pyutilz
src/pyutilz/database/deltalakes.py
.py
a381a23c89920a2b
7.24
2
"""Typed exceptions for the database domain, mirroring pyutilz.llm.exceptions's pattern. Lets callers discriminate error conditions via ``except SpecificError`` instead of string-matching a generic ``RuntimeError``/``ValueError`` message (which breaks silently the moment the message wording changes). Not a full hierar...
fingoldo/pyutilz
src/pyutilz/database/exceptions.py
.py
0b45813619201c0f
7.24
2
"""Thread-safe psycopg2 connection pool with retry, staleness-tolerant health-checking, and context-manager helpers. Complements ``pyutilz.database.db`` (a single global connection, retried on connect) with a real ``psycopg2.pool.ThreadedConnectionPool`` -- ``ThreadedConnectionPool`` is thread-safe internally, so conc...
fingoldo/pyutilz
src/pyutilz/database/psycopg2_pool.py
.py
b3fb593988c5c2c2
7.24
2
"""Aggregate FAILED/ERROR lines and pytest warning summaries across every job of a GitHub Actions run, so a 66-shard matrix can be triaged from one consolidated report instead of opening each job's log by hand. Shells out to the ``gh`` CLI (reuses the caller's existing auth) rather than talking to the GitHub API direc...
fingoldo/pyutilz
src/pyutilz/dev/ci_log_analyzer.py
.py
dd4cfcadb6a3f678
7.24
2
"""(internal) part of pyutilz.dev.code_audit; see package __init__ for docs.""" from __future__ import annotations import ast from pathlib import Path from ._base import Finding, _DEFAULT_EXCLUDE_DIRS, _iter_py_files, _line_text, _safe_parse def _is_data_sweep(node: ast.expr) -> bool: """Whether the loop itera...
fingoldo/pyutilz
src/pyutilz/dev/code_audit/assert_in_loop.py
.py
48ed4302b1da063d
7.24
2
"""(internal) part of pyutilz.dev.code_audit; see package __init__ for docs.""" from __future__ import annotations import ast from pathlib import Path from ._base import Finding, _DEFAULT_EXCLUDE_DIRS, _iter_py_files, _safe_parse, _line_text # Context-manager call names that guard a multi-statement/server-side-curso...
fingoldo/pyutilz
src/pyutilz/dev/code_audit/asymmetric_resource_guard.py
.py
4bf24ff798f06a7f
7.24
2
"""(internal) part of pyutilz.dev.code_audit; see package __init__ for docs.""" from __future__ import annotations import ast from pathlib import Path from ._base import Finding, _DEFAULT_EXCLUDE_DIRS, _iter_py_files, _safe_parse, _line_text # asyncio coordination primitives whose whole purpose is being SHARED acros...
fingoldo/pyutilz
src/pyutilz/dev/code_audit/async_primitive_reinit.py
.py
4054e5a32a86849c
7.24
2
"""(internal) part of pyutilz.dev.code_audit; see package __init__ for docs.""" from __future__ import annotations import ast from pathlib import Path from ._base import Finding, _DEFAULT_EXCLUDE_DIRS, _iter_py_files, _safe_parse, _line_text # --- bare `except:` / `except BaseException:` ----------------------------...
fingoldo/pyutilz
src/pyutilz/dev/code_audit/bare_except.py
.py
c31590c046a4a0e0
7.24
2
"""Configure reviewed Claude Code preferences and native plugins.""" import json import shlex from pathlib import Path from typing import NotRequired, TypedDict, cast from pydantic import BaseModel, ConfigDict, Field, ValidationError from ballen_config.assistants.desired_state import PluginCatalogProjection from bal...
blallen/ballen-config
src/ballen_config/assistants/claude.py
.py
641638859a2b76c8
7.15
1
"""Configure portable Codex settings, instructions, and native plugins.""" import json import tomllib from pathlib import Path from typing import TypedDict, cast import tomlkit from pydantic import BaseModel, ConfigDict, ValidationError from ballen_config.assistants.desired_state import PluginCatalogProjection from ...
blallen/ballen-config
src/ballen_config/assistants/codex.py
.py
60d950afb11a2018
7.15
1
"""Manage reviewed Cursor settings and curated extensions.""" import json from pathlib import Path from typing import TypedDict, cast from pydantic import BaseModel, ConfigDict from ballen_config.assistants.cursor_mcp import is_approved_atlassian_mcp from ballen_config.assistants.json import StrictJsonError, strict_...
blallen/ballen-config
src/ballen_config/assistants/cursor.py
.py
5c8ecfe6efddfdc4
7.15
1
"""Validate the single approved Cursor Atlassian MCP workaround.""" import json from pathlib import PurePath from typing import Final, Literal, TypedDict from ballen_config.assistants.json import StrictJsonError, strict_json_loads class AtlassianMcpServer(TypedDict): """Exact fields for the OAuth-backed Atlassi...
blallen/ballen-config
src/ballen_config/assistants/cursor_mcp.py
.py
d2d1fa30b10f3ab6
7.15
1
"""Plan safe, native Cursor marketplace and reviewed local plugins.""" import os import stat from pathlib import Path, PurePosixPath from typing import Final from pydantic import BaseModel, ConfigDict, Field, ValidationError from ballen_config.assistants.json import StrictJsonError, strict_json_loads from ballen_con...
blallen/ballen-config
src/ballen_config/assistants/cursor_plugins.py
.py
51e7bd7f3b9c6375
7.15
1
"""Project shared assistant declarations into one native target's state.""" from dataclasses import dataclass from pathlib import Path from typing import Final import yaml from pydantic import ValidationError from ballen_config.assistants.cursor_plugins import ( ValidatedCursorLocalPlugin, validate_cursor_lo...
blallen/ballen-config
src/ballen_config/assistants/desired_state.py
.py
132ffc6700fa1ab4
7.15
1
"""Translate one reviewed RTK hook into agent-native registrations.""" import json import shlex from pathlib import Path from typing import Literal, TypedDict from ballen_config.assistants.json import strict_json_loads from ballen_config.configure import ( ApplyMethod, ConfigurationContribution, ManagedFi...
blallen/ballen-config
src/ballen_config/assistants/hooks.py
.py
4c27bccd80b81380
7.15
1
"""Load and resolve reviewed coding-agent inventory declarations.""" from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path, PurePosixPath from types import MappingProxyType from typing import Final import yaml from ballen_config.assistants.models import ( AgentName, A...
blallen/ballen-config
src/ballen_config/assistants/inventory.py
.py
a241cfe915ac1360
7.15
1
"""Strict JSON decoding for reviewed and native agent data.""" import json from typing import Never type JsonObject = dict[str, object] class StrictJsonError(ValueError): """JSON uses an ambiguous or non-standard construct.""" def _unique_object(pairs: list[tuple[str, object]]) -> JsonObject: result: Json...
blallen/ballen-config
src/ballen_config/assistants/json.py
.py
1e4cf55a519010d6
7.15
1
"""Strict models for portable coding-agent inventory declarations.""" import re from enum import StrEnum from pathlib import PurePosixPath from typing import Annotated, Final, Literal, Self from pydantic import AfterValidator, BaseModel, ConfigDict, Field, model_validator class AgentName(StrEnum): """Coding age...
blallen/ballen-config
src/ballen_config/assistants/models.py
.py
0bfde7228ae8c101
7.15
1
"""Compose native coding-agent adapters from one desired-state preflight.""" from dataclasses import replace from typing import Literal from ballen_config.assistants.checks import assistant_checks from ballen_config.assistants.claude import ( ClaudePluginInspectionError, claude_configuration, plan_claude_...
blallen/ballen-config
src/ballen_config/assistants/orchestrator.py
.py
58818db5728a8b00
7.15
1
"""Normalized, non-mutating bootstrap readiness checks.""" import os import stat from collections.abc import Callable, Sequence from enum import StrEnum from pathlib import Path from pydantic import BaseModel, ConfigDict, field_validator from ballen_config.configure import ConfigurationEngine, ManagedSpec from balle...
blallen/ballen-config
src/ballen_config/doctor.py
.py
9f245e0ba6d56140
7.15
1
from pathlib import Path from typing import Any, Self import yaml from ballen_config.models import ( Component, ComponentFile, Profile, ResolutionRequest, ResolvedSetup, ) def _yaml(path: Path) -> Any: """Load one YAML document at the external data boundary.""" with path.open(encoding="u...
blallen/ballen-config
src/ballen_config/manifests.py
.py
4d122fdcddfa2e67
7.15
1
from enum import StrEnum from pathlib import Path from typing import Self from pydantic import BaseModel, ConfigDict, Field, model_validator class Manager(StrEnum): """Supported installation mechanisms.""" BREW_FORMULA = "brew_formula" BREW_CASK = "brew_cask" GIT = "git" UV_TOOL = "uv_tool" cl...
blallen/ballen-config
src/ballen_config/models.py
.py
1fc04c3de57f3e1f
7.15
1
"""Filesystem containment and symlink-safety helpers.""" import os import stat from pathlib import Path def assert_contained(path: Path, root: Path) -> Path: """Return an absolute lexical path only when it is beneath ``root``.""" normalized_root = root.resolve() normalized_path = Path(os.path.abspath(pat...
blallen/ballen-config
src/ballen_config/paths.py
.py
40cb0d3ff711b4d4
7.15
1
from collections.abc import Sequence from enum import StrEnum from pathlib import Path from typing import Literal, Protocol from pydantic import BaseModel, ConfigDict from ballen_config.manifests import ManifestRepository from ballen_config.models import ResolutionRequest, ResolvedSetup class ComponentState(StrEnum...
blallen/ballen-config
src/ballen_config/planning.py
.py
2800f2f41fa6b113
7.15
1
"""Enforce security and portability policy across the tracked repository tree.""" import os import re import stat import subprocess from collections.abc import Sequence from pathlib import Path, PurePath from typing import Final import yaml from pydantic import BaseModel, ConfigDict, ValidationError from yaml import ...
blallen/ballen-config
src/ballen_config/policy.py
.py
ecf81799021c8430
7.15
1
"""Shared predicates and presence rules over native command output. These helpers isolate assumptions about the output format of external tools so that a format change only needs updating in one place, and so that the match rule cannot silently drift between the install, doctor, and CLI dispatch sites that all need it...
blallen/ballen-config
src/ballen_config/probes.py
.py
2b3433a4a7a427a3
7.15
1
import subprocess from collections.abc import Sequence from typing import Protocol, TypedDict class CommandResult(TypedDict): """Captured subprocess result.""" returncode: int stdout: str stderr: str class Runner(Protocol): """Subprocess boundary used by installers and diagnostics.""" def ...
blallen/ballen-config
src/ballen_config/runner.py
.py
45022fb5312ea533
7.15
1
from pathlib import Path from typing import Self from pydantic import BaseModel, ConfigDict class RuntimePaths(BaseModel): """Approved roots injected into every filesystem operation.""" model_config = ConfigDict(frozen=True) repo_root: Path home: Path state_root: Path backup_root: Path ...
blallen/ballen-config
src/ballen_config/runtime.py
.py
4fb09692a8095c08
7.15
1
"""Private, versioned state for bootstrap ownership and outcomes.""" import errno import fcntl import os import stat import tempfile import threading from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path from typing import Literal from pydantic import BaseModel, ConfigDic...
blallen/ballen-config
src/ballen_config/state.py
.py
4809ab3f95518271
7.15
1
"""Fixtures for coding-agent portability tests.""" import shutil from collections.abc import Callable, Iterator from dataclasses import dataclass from pathlib import Path import pytest import yaml from ballen_config.assistants.desired_state import ( PluginCatalogProjection, project_plugin_catalog, ) from bal...
blallen/ballen-config
tests/assistants/conftest.py
.py
264c9aa533c346d3
7.65
1
"""Stateful external-boundary fakes for coding-agent tests.""" import json from collections.abc import Sequence from pathlib import Path from typing import cast from ballen_config.runner import CommandResult class StatefulAssistantFake: """Stateful runner and downloader for assistant integration tests.""" ...
blallen/ballen-config
tests/assistants/fakes.py
.py
c686ec471a350db4
7.65
1
"""Tests for canonical shared coding-agent instructions.""" from pathlib import Path import pytest from ballen_config.assistants.instructions import render_native_instructions from ballen_config.assistants.inventory import load_inventory from ballen_config.assistants.models import ( CatalogResource, FileReso...
blallen/ballen-config
tests/assistants/test_instructions.py
.py
ee2799be927c2dae
7.65
1
"""Tests for passive repository-rule starter templates.""" import re from pathlib import Path ENTRY_FILES = { "README.md", "AGENTS.md", "CLAUDE.md", } ROUTE = ( "If `docs/engineering-standards/` exists, read the applicable topic " "documents before relevant implementation or review work." ) TOPICS...
blallen/ballen-config
tests/assistants/test_repository_rules.py
.py
3db2e8432737020a
7.65
1
import re import logging import time import json import os import base64 from typing import Optional, Dict from fastapi import APIRouter, HTTPException, Query from fastapi.responses import RedirectResponse from aiohttp import ClientSession from playwright.async_api import async_playwright router = APIRouter() logger =...
franlerma/localstreams
app/handlers/globalmest.py
.py
1387a4de1ca92fc9
7.15
1
""" Persistente Vergabe von eindeutigen Eltern-IDs. Schild liefert pro Erzieher keine schul-/personeneindeutige ID — bei Geschwister- Konstellationen hat dasselbe Elternteil bei jedem Kind einen separaten Datensatz. WebUntis kann (optional) eine schulweit eindeutige Eltern-ID als Matching-Key auswerten, damit derselbe...
CmoneBK/Schild-WebUntis-Tool
Schild_WebUntis_Tool/eltern_id_manager.py
.py
92bfff9e14077b9f
7.15
1
""" Foto-Verwaltung: Schüler-Fotos aus Schild (benannt nach Interner ID) verwalten. - Fotos liegen im konfigurierten foto_directory, Dateiname = Interne ID (z.B. 12345.jpg) - Anzeige einzelner Fotos (Dashboard) - ZIP-Export für WebUntis (Auswahl nach Schild-Status) - Verwaiste Fotos (Schüler nicht mehr im Import) in e...
CmoneBK/Schild-WebUntis-Tool
Schild_WebUntis_Tool/foto_manager.py
.py
d55d62e6a6135ee7
7.15
1
"""Kleiner Helfer fuer at-rest verschluesselte Geheimnisse in settings.ini. Aktuell wird das nur fuer das Passwort der verschluesselten Sonderpaedagogen- Arbeitsdatei (Nachteilsausgleich) genutzt. Die Idee ist bewusst minimal: * Windows: Per DPAPI (CryptProtectData) — gebunden an den aktuellen Windows- Benutzer, ke...
CmoneBK/Schild-WebUntis-Tool
Schild_WebUntis_Tool/secret_store.py
.py
094614e5f06e4eb7
7.15
1
import os import configparser def safe_read_config(config_obj, filename): """ Versucht eine Konfigurationsdatei mit utf-8-sig zu laden, fällt bei Fehlern auf latin-1 zurück. """ if not os.path.exists(filename): return False # Erst mit utf-8-sig versuchen try: with open...
CmoneBK/Schild-WebUntis-Tool
Schild_WebUntis_Tool/utils.py
.py
d7d514bbc3341279
7.15
1
"""Lesen/Schreiben verschluesselter (passwortgeschuetzter) xlsx-Dateien. Wird fuer die Sonderpaedagogen-Arbeitsdatei (Nachteilsausgleich) genutzt: die Datei liegt typischerweise auf einem Netzlaufwerk, auf das mehrere Personen Zugriff haben. Excel-Passwortschutz haelt zusaetzliche Augen draussen, ohne dass es eine zen...
CmoneBK/Schild-WebUntis-Tool
Schild_WebUntis_Tool/xlsx_crypto.py
.py
056e80f58cb2c948
7.15
1
import argparse import logging import subprocess import time from datetime import datetime from pathlib import Path import cv2 from pystory.capture import take_screenshot, take_webcam_picture, detect_face from pystory.config import Config from pystory.obsbot import disable_tracking, enable_tracking from pystory.prese...
asetapen/pystory
src/pystory/main.py
.py
0f5bb9f7d66b6a94
7
0
import logging import subprocess from pystory.config import Config log = logging.getLogger("pystory.obsbot") # obsbot-cli's interactive mode (-i) reads commands from stdin, one per line. # 'i' prompts for an AI mode number on a second line; 'I' disables AI mode # outright. See obsbot-camera-control's src/cli/meet2_t...
asetapen/pystory
src/pystory/obsbot.py
.py
4fb1db4e92c9120b
7
0
from dataclasses import dataclass, field @dataclass class PresenceTracker: """Debounces face-recognition results across ticks. A single bad frame (glare, brief look-away, misfire) shouldn't flip the lock state. Require `confirm_ticks` consecutive same-direction results before reporting a decision. ...
asetapen/pystory
src/pystory/presence.py
.py
30b8c740e72dc550
7
0
import json import logging from pathlib import Path import face_recognition import numpy as np from pystory.config import Config log = logging.getLogger("pystory.recognition") ENCODINGS_FILE = "face_encodings.json" def encodings_path(config: Config) -> Path: return config.storage_dir / ENCODINGS_FILE def lo...
asetapen/pystory
src/pystory/recognition.py
.py
d428a75f2765f72e
7
0
from pathlib import Path from pystory.config import Config def get_storage_size_mb(config: Config) -> float: total = sum(f.stat().st_size for f in config.storage_dir.glob("*.jpg") if f.is_file()) return total / (1024 * 1024) def prune_old_files(config: Config) -> int: """Delete oldest files until stora...
asetapen/pystory
src/pystory/storage.py
.py
1c1b40fba1fc7274
7
0
"""The camera-failure flags must reach Config, not just parse. `parse_args` builds a Config from argparse results by hand, one `if` per flag, so a flag can be declared and documented while never touching the field it names. That failure mode is invisible from the CLI: the flag is accepted, the help text lists it, and ...
asetapen/pystory
tests/test_main_args.py
.py
38b4ac017d6ccedf
7.5
0
"""Numeric CLI flags must not silently swallow a value (issue st-dqfz5j). Four numeric flags were gated with `if args.x:`, a TRUTHINESS test, so `0` took the same branch as omitting the flag entirely and the hardcoded default was applied instead. The flag was accepted, `--help` listed it, nothing was logged, and the o...
asetapen/pystory
tests/test_main_args_zero.py
.py
c46e3a15cf554c30
7.5
0
"""`--interval 0` must not park the debug UI forever (issue st-dqfz5j). `cv2.waitKey`'s documented contract is that a delay <= 0 waits INFINITELY, so `main()`'s debug-UI branch passing `interval_seconds * 1000` straight through means `--interval 0` says "as fast as possible" on the `time.sleep` path and "wait until a ...
asetapen/pystory
tests/test_main_debug_ui_interval.py
.py
8935680d67955258
7.5
0
"""`--output` must not be silently dropped on the default `--type both` (issue st-8gpxr8, D2), and `--fps` must not reach 0 (D1's other trigger). `main.py` line 73 read `if args.output and args.type != "both"`, and `--type` defaults to `"both"`, so `pystory-timelapse --output x.mp4` -- the plainest possible use of the...
asetapen/pystory
tests/test_timelapse_args.py
.py
81683ea5be1f3d43
7.5
0
import functools from clld import RESOURCES, Resource from clld.interfaces import IDomainElement, ILanguage, IMapMarker, IValue, IValueSet from clld.web.adapters import register_resource_adapters from clld.web.app import menu_item from clld.web.icon import PREFERED_COLORS, SECONDARY_COLORS, SHAPES, MapMarker from clld...
fijigis/fijian100wl
fijian100wl/fijian100wl/__init__.py
.py
d3877184207adb73
7
0
from clld.web.datatables.base import Col, DataTable, IntegerIdCol, LinkCol, LinkToMapCol from clld.web.util.helpers import map_marker_img from clld.web.util.htmllib import HTML from sqlalchemy.orm import joinedload from fijian100wl import models class VillageCol(LinkCol): def format(self, item): return H...
fijigis/fijian100wl
fijian100wl/fijian100wl/datatables.py
.py
b1cae6a218b25304
7
0
from __future__ import annotations import time from redis import Redis from .exceptions import FsaRateLimitedError class RedisRateLimiter: """Global leaky-bucket pacing shared across processes via Redis. Every caller atomically reserves the next free slot spaced `interval_ms` apart from the previous o...
pychik/Markineris2.0.r
app/fsa/rate_limiter.py
.py
ae18a2a2514e9c17
7
0
"""Exchange Basic-packet ping/pong messages between two SPIRIT1 devices. Run this on two hosts with matching radio settings and swapped addresses:: python examples/ping_pong.py ping --local-address 1 --peer-address 2 python examples/ping_pong.py pong --local-address 2 --peer-address 1 Basic packets carry onl...
zathras777/py-spirit1
examples/ping_pong.py
.py
e4174c00eaa1d4cd
7.15
1
"""SPIRIT1 basic-packet configuration, decoding, and streaming.""" from __future__ import annotations import time from collections.abc import AsyncIterator from dataclasses import dataclass, field from .device import Spirit1Device from .enums import CrcMode from .irq import IRQ, SpiritIrq from .packet_config import ...
zathras777/py-spirit1
src/spirit1/basic_packet.py
.py
9c12c6c31627c29c
7.15
1
from __future__ import annotations import logging import time from typing import AnyStr, Union from .enums import Spirit1Commands, Spirit1State from .gpio import ShutdownPin from .registers import Spirit1Registers from .spi import SpiDevice from .status import Spirit1Status logger = logging.getLogger(__name__) # Ke...
zathras777/py-spirit1
src/spirit1/device.py
.py
757e0af4205c6650
7.15
1
"""Human-readable and structured representations of received packets.""" from typing import Any from .basic_packet import BasicPacketMessage def basic_packet_to_dict(message: BasicPacketMessage) -> dict[str, Any]: """Return a JSON-friendly representation of a basic packet message.""" return { "desti...
zathras777/py-spirit1
src/spirit1/formatting.py
.py
b077a88a1943e810
7.15
1
from __future__ import annotations from enum import IntEnum class FrequencyBand(IntEnum): HIGH_BAND = 0x00 # High_Band selected: from 779 MHz to 915 MHz MIDDLE_BAND = 0x01 # Middle Band selected: from 387 MHz to 470 MHz LOW_BAND = 0x02 # Low Band selected: from 300 MHz to 348 MHz VERY_LOW_BAND = 0...
zathras777/py-spirit1
src/spirit1/frequency.py
.py
a77d0141f6a9bb58
7.15
1
"""Optional GPIO adapters for hardware signals outside the SPI bus.""" from __future__ import annotations from typing import Protocol class ShutdownPin(Protocol): """Active-high SPIRIT1 SDN control pin.""" def get_value(self) -> bool | None: """Return ``True`` when SDN is high and the radio is shut...
zathras777/py-spirit1
src/spirit1/gpio.py
.py
3da7abfbcc98149d
7.15
1