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
# SPDX-License-Identifier: MIT """Write Bench2Drive-eval-compatible artifacts from inside the RL training loop. Mirrors what ``leaderboard_evaluator.py`` produces during Bench2Drive's standard eval scripts so that the same downstream tools (``Bench2Drive/tools/merge_route_json.py``, ``efficiency_smoothness_benchmark.p...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/envs/eval_writer.py
.py
eccbf6a88e901704
7
0
# SPDX-License-Identifier: MIT from dataclasses import dataclass import cv2 import numpy as np # Comfort thresholds (from Alpamayo comfort_reward.py) COMFORT_MAX_ABS_MAG_JERK = 8.37 # [m/s^3] COMFORT_MAX_ABS_LAT_ACCEL = 4.89 # [m/s^2] COMFORT_MAX_LON_ACCEL = 2.40 # [m/s^2] COMFORT_MIN_LON_ACCEL = -4.05 # [m/s^2] ...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/envs/vehicle_graph.py
.py
3bf8f40b3b4c708a
7
0
# SPDX-License-Identifier: MIT import torch class StatisticalMetricsComputer: """ Class for computing statistical metrics on a sufficient number of samples. Given neural network features with 2D shape (batch_size, feature_dim), for example when computing Stable rank using singular value decomposition,...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/metrics/statistical_metrics_computer.py
.py
0c0aa031da0fff68
7
0
# SPDX-License-Identifier: MIT """The Animal-AI Olympics winning network, ported from ``~/work/rl_animal``. A visual trunk -- the original Fixup residual tower with channel attention, or any of the pretrained encoders in ``networks/modules/image_processor.py``, which is where both now live -- a small dense branch for ...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/networks/animal_ppo.py
.py
8f4ccf3496e80d40
7
0
# SPDX-License-Identifier: MIT """The Animal-AI PPO network with WCM's world-critic head, ported from ``~/work/WCM``. WCM (arXiv 2607.29613) trains a critic whose shared representation has to support two objectives: an action-free value estimate over the history, and an action-conditioned prediction of the next latent...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/networks/animal_world_critic.py
.py
24a6b6785d52660a
7
0
# SPDX-License-Identifier: MIT """Shared network interface: structured result types and the abstract base class. Every policy/value network exposes exactly three public methods — ``infer``, ``compute_loss`` and ``infer_and_compute_loss`` — returning the structured types defined here. ``NetworkInterface`` makes that co...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/networks/interface.py
.py
4b9bcc55cc940a99
7
0
# SPDX-License-Identifier: MIT import numpy as np class ActionTokenizer: """Maps continuous actions in [-1, 1] to discrete token IDs at the end of the vocabulary.""" def __init__(self, vocab_size: int) -> None: self.n_bins = 128 self.bins = np.linspace(-1.0, 1.0, self.n_bins + 1) self...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/networks/modules/action_tokenizer.py
.py
f4ee055819f7eef8
7
0
# SPDX-License-Identifier: MIT import torch from torch import nn from .image_processor import ImageProcessor from .reward_processor import RewardProcessor from .self_attention import get_fourier_embeds_from_coordinates from .spatial_temporal_transformer import SpatialTemporalTransformer def init_weights(m: nn.Module...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/networks/modules/backbone.py
.py
3c09d49426635c44
7
0
# SPDX-License-Identifier: MIT import math import torch import torch.nn as nn import torch.nn.functional as F class NormedLinear(nn.Module): """Linear layer with weight projected onto the unit hypersphere in forward. Weights are L2-normalized along the input dimension at each forward call, so the stored...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/networks/modules/blocks.py
.py
abe56c9190be299d
7
0
# SPDX-License-Identifier: MIT import torch import torch.nn.functional as F from diffusers import AutoencoderTiny from torch import nn from transformers import AutoModel, AutoModelForImageTextToText, AutoProcessor from vla_streaming_rl.networks.modules.qwen_vision import ( interpolated_pos_embed, rotary_pos_em...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/networks/modules/image_processor.py
.py
5e6b46db28571bab
7
0
# SPDX-License-Identifier: MIT import torch import torch.nn as nn import torch.nn.functional as F from .flux_dit import FluxDiT from .image_processor import ImageProcessor from .reward_processor import RewardProcessor class StatePredictionHead(nn.Module): def __init__( self, image_processor: Imag...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/networks/modules/prediction_head.py
.py
c0c74fa57d9df573
7
0
# SPDX-License-Identifier: MIT """The two vision-tower helpers this repo needs, on the API that replaced them. ``fast_pos_embed_interpolate`` and ``rot_pos_emb`` on Qwen's vision tower are deprecated. Both encoders here drive the tower block by block rather than calling its ``forward``, so they need exactly what those...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/networks/modules/qwen_vision.py
.py
cb04430f4a61bcf5
7
0
# SPDX-License-Identifier: MIT import torch import torch.nn as nn import torch.nn.functional as F from transformers.models.llama.configuration_llama import LlamaConfig from transformers.models.llama.modeling_llama import LlamaRotaryEmbedding, apply_rotary_pos_emb def get_fourier_embeds_from_coordinates(embed_dim: int...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/networks/modules/self_attention.py
.py
af0bb9050f407b6f
7
0
# SPDX-License-Identifier: MIT """ Sparse network utilities for implementing one-shot random pruning based on "Network Sparsity Unlocks the Scaling Potential of Deep Reinforcement Learning" """ import torch import torch.nn as nn def create_random_mask(shape: tuple, sparsity: float, device: torch.device) -> torch.Ten...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/networks/modules/sparse_utils.py
.py
04a013e363bded90
7
0
# ref. https://github.com/Kevin-thu/Epona/blob/main/models/stt.py import torch import torch.nn as nn from einops import rearrange from .self_attention import SpatialTransformerBlock from .temporal_block import CausalTransformerBlock, GdnBlock, GRUBlock, IdentityBlock, MambaBlock class SpatialTemporalBlock(nn.Module...
SakodaShintaro/vla_streaming_rl
src/vla_streaming_rl/networks/modules/spatial_temporal_transformer.py
.py
e39558e0240abda9
7
0
""" Bot mock state shared by conftest.py and test modules. Imported as `mock_helpers` — never as `conftest` — so the root conftest.py (pytest guard) cannot shadow this module. """ import sys, os # Ensure the integration_tests dir is in sys.path (conftest.py also does this, # but this module may be imported before con...
amitvmane/RollCall
integration_tests/mock_helpers.py
.py
a8ebda5565093b2e
7.74
2
""" Integration tests for REST API authentication, scopes, and rate limiting. Drives the real FastAPI app via TestClient. Mints / revokes tokens via db helpers. Verifies: - Missing header → 401 - Bad / unknown token → 401 - Revoked token → 401 - Expired token → 401 - Token with wrong scope → 403 - Token bo...
amitvmane/RollCall
integration_tests/test_api_auth.py
.py
dbe5da12dd952338
7.74
2
""" Real-SQLite tests for DB scalability Phase 2: WAL mode + get_connection()'s per-worker-thread connection branch, and the two call sites now offloaded through db._stats_executor (services/stats.py:bot_stats, db.get_idle_chats). Uses unittest.IsolatedAsyncioTestCase (matching integration_tests/helpers.py's Integrati...
amitvmane/RollCall
integration_tests/test_db_thread_safety.py
.py
6bf23accf7fd151a
7.74
2
""" Regression tests for _ensure_aware's DST cutover handling. The bot defaults to Asia/Kolkata where DST has never been observed (India dropped DST in 1945), so these edge cases don't fire for the primary user base. But chats can /timezone to anywhere, and the previous code silently fired ambiguous times at the LATER...
amitvmane/RollCall
integration_tests/test_dst_cutover.py
.py
a36736b3ea257880
7.74
2
""" Dues-v2 integration: dues epoch, /new_season reset, collector UPI memory — real handlers, real database. """ from unittest.mock import AsyncMock, patch import db from services import dues as dues_svc from helpers import IntegrationBase, CHAT_ID, ADMIN_USER, USERS from mock_helpers import get_mock_bot def _enabl...
amitvmane/RollCall
integration_tests/test_dues_season.py
.py
59fcc79b1f91ffef
7.74
2
""" Integration regressions for the panel end-rollcall confirmation flow. Production bugs being prevented: 1. After pressing the inline ✅ Yes button on the "Are you sure?" prompt, the prompt stayed on screen with the buttons still attached. The bot sent the finish list (or tried to — see #2) as a NEW messa...
amitvmane/RollCall
integration_tests/test_end_confirm_regressions.py
.py
80d08ac738d8f72a
7.74
2
""" Integration regressions for the COMMANDS-driven /help refactor. Covers: - /help <name> → detail card with args + example - /help <alias> → resolves via alias lookup - /help <typo> → fuzzy "did you mean…?" suggestion - /help <gibberish> → graceful no-match message - /help ...
amitvmane/RollCall
integration_tests/test_help_detail.py
.py
12967a8578e86fef
7.74
2
""" Integration tests for the Mini App cross-group picker flow: GET /portal/groups (existing, reused) POST /auth/telegram/miniapp/group (new) Real DB, real services, FastAPI TestClient. Exercises the actual scenario this feature exists for: the Mini App's only working entry point toda...
amitvmane/RollCall
integration_tests/test_miniapp_group_picker.py
.py
08e7a3fb741951d5
7.74
2
""" Regression: services.rollcalls._push_rollcall_started / _push_rollcall_ended resolve the group's web-push token via manager.get_chat(chat_id) -- the same 6-field-subset cache dict that already caused /auto_buzz to silently never fire (see test_reminder_dms_and_export.py). group_web_token isn't one of the 6 cached f...
amitvmane/RollCall
integration_tests/test_push_notifications.py
.py
cac296178eabc8bd
7.74
2
""" Real-DB integration tests for the repeat= shortcut (/start_roll_call, /repeat) and /calendar — see rollCall/handlers/lifecycle.py, rollCall/services/templates.py, rollCall/handlers/templates.py. """ import pytz from datetime import datetime, timedelta import db from helpers import IntegrationBase, ADMIN_USER, USER...
amitvmane/RollCall
integration_tests/test_repeat_and_calendar.py
.py
5fc05da8f91371ff
7.74
2
""" Restart-recovery tests — simulate a bot restart by clearing in-memory state and verifying the bot picks up where it left off from the database. These don't actually fork the process; they reset the manager cache, in-memory dicts, and any module-level state, then call recovery functions (resume_reminder_loops, _loa...
amitvmane/RollCall
integration_tests/test_restart_recovery.py
.py
7c25866f4e00dfce
7.74
2
""" Unit tests for the scheduled-template catch-up window in rollCall/check_reminders.py::_is_due_now. Production bug being prevented: Sunday 9am scheduled template silently skipped its weekly run. Root cause: the old loop used exact-minute string equality (now.strftime('%H:%M') == schedule_time). Any iteration ...
amitvmane/RollCall
integration_tests/test_scheduler_catchup.py
.py
b4e5ca427762b681
7.74
2
""" Regression: the schema reconciler backfills columns missing on databases created by older builds (e.g. rollcalls.absent_marked, which had no migration and caused "no such column: absent_marked" at runtime). Runs against the real db module (integration conftest wires a real SQLite DB), calling db._reconcile_columns...
amitvmane/RollCall
integration_tests/test_schema_reconcile.py
.py
f9b66737c65f6b94
7.74
2
""" Regression tests for the Asia/Calcutta → Asia/Kolkata default migration. Context: pytz 2026.2 still treats Asia/Calcutta as a valid timezone (it's a deprecated IANA alias for Asia/Kolkata), but the alias may be dropped in a future pytz release. We migrated all default-fallback sites to the modern Asia/Kolkata name...
amitvmane/RollCall
integration_tests/test_timezone_migration.py
.py
7616ac6937cb05ef
7.74
2
""" Integration regression tests for the v7.8 bug fixes. Each test corresponds to a real production bug we shipped (and in some cases re-shipped). Keep these — they're the closest thing we have to a staging environment for catching regressions of these specific behaviors. Coverage: - Ghost decrement on confirmed atte...
amitvmane/RollCall
integration_tests/test_v78_regressions.py
.py
17da14c9d3be99a2
7.74
2
#!/usr/bin/env python3 """Check that every version declaration in this repository agrees. Compared sources: * pyproject.toml ``[project].version`` — maturin stamps the wheel/sdist with this * src/rdetoolkit/__init__.py ``__version__`` * (optional) a git tag passed via ``--tag``, e.g. ``--tag v2.0.0a1`` Every...
nims-mdpf/rdetoolkit
scripts/check_version_consistency.py
.py
365aebfaaf572178
7.3
3
from __future__ import annotations import os import re from pathlib import Path from string import Template from typing import Literal from rdetoolkit.interfaces.report import ICodeScanner, IReportGenerator from rdetoolkit.models.reports import CodeSnippet, ReportItem from rdetoolkit.rdelogger import get_logger logg...
nims-mdpf/rdetoolkit
src/rdetoolkit/artifact/report.py
.py
a9db181e009a9146
7.3
3
"""CLI command for generating invoice.json from schema. This module provides the GenerateInvoiceCommand class which implements the CLI functionality for the 'rdetoolkit gen-invoice' command. It handles user input, calls the invoice generator service, and manages output formatting. """ from __future__ import annotatio...
nims-mdpf/rdetoolkit
src/rdetoolkit/cmd/gen_invoice.py
.py
b80c720d3551df34
7.3
3
from __future__ import annotations import os from pathlib import Path from typing import Any, Final import yaml from pydantic import ValidationError from tomlkit.exceptions import TOMLKitError from tomlkit.toml_file import TOMLFile from yaml import YAMLError from rdetoolkit.exceptions import ConfigError from rdetool...
nims-mdpf/rdetoolkit
src/rdetoolkit/config.py
.py
ca499582c876ed1d
7.3
3
from __future__ import annotations import json from functools import lru_cache from pathlib import Path from typing import Any from rdetoolkit.exceptions import StructuredError @lru_cache(maxsize=1) def _get_logger() -> Any: from rdetoolkit.rdelogger import get_logger return get_logger(__name__) def detec...
nims-mdpf/rdetoolkit
src/rdetoolkit/fileops.py
.py
a9737252455361b7
7.3
3
from __future__ import annotations class GraphPlottingError(Exception): """Base exception for graph plotting errors.""" class ColumnNotFoundError(GraphPlottingError): """Raised when a specified column is not found in the DataFrame. Args: column_name: Name of the column that was not found. ...
nims-mdpf/rdetoolkit
src/rdetoolkit/graph/exceptions.py
.py
d969b5c777fe3129
7.3
3
"""The hx3 integration.""" from __future__ import annotations import asyncio from datetime import timedelta from homeassistant.const import CONF_EMAIL, CONF_TOKEN, CONF_ACCESS_TOKEN, CONF_TTL from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.util import Throttle from hx3 import api from .co...
jaredhobbs/home-assistant-hx3
custom_components/hx3/__init__.py
.py
674cf0e41bbf0c58
7.24
2
"""Support for Johnson Controls Hx 3 Thermostat""" from __future__ import annotations from typing import Any import voluptuous as vol from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity, HVACMode, HVACAction, ClimateEntityFeature from homeassistant.const import UnitOfTemperature from homeas...
jaredhobbs/home-assistant-hx3
custom_components/hx3/climate.py
.py
59ac641733fbdee0
7.24
2
"""Config flow for hx3 integration.""" from __future__ import annotations from typing import Any import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_EMAIL, CONF_TOKEN, CONF_ACCESS_TOKEN, CONF_TTL from homeassistant.data_entry_flow import FlowResult from . import ge...
jaredhobbs/home-assistant-hx3
custom_components/hx3/config_flow.py
.py
6114280c059b8c63
7.24
2
"""Support for Johnson Controls Hx 3 Thermostat humidity sensor""" from __future__ import annotations from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, ) from homeassistant.const import PERCENTAGE from .const import DOMAIN async def async_setup_entry(hass,...
jaredhobbs/home-assistant-hx3
custom_components/hx3/sensor.py
.py
777dd311095d063c
7.24
2
"""Support for Johnson Controls Hx 3 Thermostat emergency heat switch""" from __future__ import annotations from homeassistant.components.switch import SwitchEntity from hx3 import api from .const import DOMAIN async def async_setup_entry(hass, config, async_add_entities): """Set up the Hx 3 emergency heat sw...
jaredhobbs/home-assistant-hx3
custom_components/hx3/switch.py
.py
004844fdb47756f5
7.24
2
from enum import Enum from random import choice class Generator: class Type (Enum): """ :*: Type """ BINARY, OCTAL, DECIMAL, HEXADECIMAL = [2, 8, 10, 16] def generate (self, length: int, kind: Type = Type.DECIMAL) -> str: """ :type length: int :type kind: Type = Type....
hsbmaulana/hsbmaulana
Hsbmaulana/lib/Generator.py
.py
13252e472ca6702a
7.15
1
from typing import Union, List from os.path import dirname, realpath, abspath from re import sub class IO: def replace (self, path: str, *args: List[Union[int, str]]) -> None: """ :type path: str :type *args: List[Union[int, str]] :rtype: None """ try: ...
hsbmaulana/hsbmaulana
Hsbmaulana/lib/IO.py
.py
5679b3902afbdf26
7.15
1
from .Contracts.Stringable import Stringable from ..lib.Generator import Generator from os import environ from datetime import datetime class Clock (Stringable): def __str__ (self) -> str: """ :rtype: str """ date = int (environ.get ("BECODER_SINCE_DATE")) month = int (envi...
hsbmaulana/hsbmaulana
Hsbmaulana/src/Clock.py
.py
1b0cd2e67f6c565b
7.15
1
from .Contracts.Stringable import Stringable from ..lib.Generator import Generator class Emoji (Stringable): def __init__ (self) -> None: """ :rtype: None """ """ :__smiles: List[str] """ self.__smiles = [ "60", "61", "62", "63", "64", "91", "92", ...
hsbmaulana/hsbmaulana
Hsbmaulana/src/Emoji.py
.py
420df7f628fefaf6
7.15
1
"""census の参照を族分類に当てて、族の内側と族またぎへ機械的に振り分ける。 族分類の草案が持つ散文リストは手で数えたもので、見つけた分しか載らない。 canonical は cross-reference-census.json 側に置き、族への振り分けはここで生成する。 使い方 (引数は省略可、既定はこのファイルと同じディレクトリ): python3 classify-crossrefs.py [family-classification.md] [cross-reference-census.json] """ import json import re import sys from pathlib i...
hidari/dotfiles
docs/issues/closed/24_CLAUDE.md の MUST GLOBAL を族でまとめて読む単位を減らす/notes/classify-crossrefs.py
.py
c85da7e0578ee235
7
0
#!/usr/bin/env python3 """apm の書き込みを伴うサブコマンドを、ツリーが汚れているときだけ止める PreToolUse フック。 apm install は deploy 先を rsync --delete 相当で書き換え、git tracked かつ手書きのファイルも 黙って上書きし、パッケージに含まれないファイルを削除する。しかもログには (files unchanged) と 表示されるため差分に気づけない。 目的は破壊の防止ではなく復旧可能性の確保である。ツリーが clean なら apm が何を壊しても git から 戻せるが、汚れていれば未コミットの作業が復旧不能に消える。この整理から検査...
hidari/dotfiles
home/.claude/hooks/apm-install-guard.py
.py
040a43ba55236e3d
7
0
#!/usr/bin/env python3 """Claude Code hook: セッション引き継ぎ検知器 (handoff-sentinel)。 第1引数で分岐する: posttool (コンテキスト使用率の監視) / stop (ツール呼び出し破損の 通算検知) / session (.cache/handoff.md の自動注入) / record (skill からの provenance 記録)。 しきい値等の canonical はこのファイルの定数であり、HANDOFF_* 環境変数で上書きできる。 検知機構の故障で作業を止めないため、全経路 fail-safe (無出力 + exit 0)。 仕様: docs...
hidari/dotfiles
home/.claude/hooks/handoff-sentinel.py
.py
635322282f221518
7
0
#!/usr/bin/env python3 """Claude Code hook: 指示ファイルのロードを観測して JSONL へ記録する。 InstructionsLoaded イベント (Claude Code 2.1.233 で確認) を受け取り、どの指示ファイルが いつ何故ロードされたかを追記する。イベントの schema はバイナリの zod 定義が canonical で、 このファイルは値を再掲せず受け取ったフィールドをそのまま通す。 このフックは observability-only で blocking をサポートしないため、常に exit 0 で返す。 観測器の故障で作業を止めない。 """ from ...
hidari/dotfiles
home/.claude/hooks/instructions-loaded-log.py
.py
0fe7f387d6a50761
7
0
"""PreToolUse フックの入力解釈と判定出力を共有する。 tirith-check.py と apm-install-guard.py が同じプロトコルを写経しており、片方だけ直したときに 沈黙した差 (ensure_ascii が 1 つだけ違う等) が実際に生まれていたため切り出した。 共有するのは純関数だけで、fail ポリシーは共有しない。tirith は環境変数の逃げ道を持つ fail-closed、apm は無条件 deny で、同じ関数へ潰すと security guard の倒れ方が静かに変わる。 異常は problem 付きの例外で返し、各フックが自分のポリシーで捌く。 print と sys.ex...
hidari/dotfiles
home/.claude/hooks/pretooluse.py
.py
a7c23d2ec6399e05
7
0
#!/usr/bin/env python3 """Claude Code の PreToolUse フック — Bash ツール呼び出しを tirith で検査する。 stdin から hook JSON(Claude Code hook プロトコル)を読み、command を取り出して `tirith check --json` に委譲しセキュリティ解析する。 Exit code: 0 — フックは正常終了(判定は stdout の JSON に入る) 非 0 — フックエラー(既定は fail-closed。TIRITH_FAIL_OPEN=1 で fail-open) 出力(stdout): de...
hidari/dotfiles
home/.claude/hooks/tirith-check.py
.py
0077c6bbbd034842
7
0
"""ディスク容量計算と測定。 純粋関数 (required_total_kb / check_capacity) と 副作用境界 (measure_source_size_kb / measure_dest_total_kb) を分離する。 issue #3 で修正した「総容量ベース判定」のロジックを踏襲する。 """ from __future__ import annotations import subprocess from dataclasses import dataclass from pathlib import Path _GB_TO_KB = 1024 * 1024 @dataclass(froze...
hidari/dotfiles
scripts/backup-tool/src/backup_tool/disk.py
.py
77c61b9a6bec9286
7
0
"""ログ出力のセットアップとローテーション。 text / json 2 系列のフォーマッタと、旧 backup.sh:319-339 の cleanup_old_logs 相当のロジックを提供する。 """ from __future__ import annotations import json import logging import time from datetime import UTC, datetime from enum import StrEnum from pathlib import Path _LOG_PREFIX = "backup_" _LOG_SUFFIX = ".log" # logg...
hidari/dotfiles
scripts/backup-tool/src/backup_tool/logging_setup.py
.py
9cb311a3241bc706
7
0
"""パス種別判定とマウント確認。 純粋関数 (classify / extract_volume_path) と 副作用境界 (is_mounted / check_readable / check_writable) を分離する。 """ from __future__ import annotations import os import re import subprocess from pathlib import Path from typing import Literal PathKind = Literal["volume", "directory", "local"] # /Volumes/<name>...
hidari/dotfiles
scripts/backup-tool/src/backup_tool/paths.py
.py
b00f9ff70d961320
7
0
"""rsync 起動・オプション構築・出力フィルタリング。 純粋関数 (build_options / is_suppressible_error / summarize_filtered_errors) と 副作用境界 (run) を明示的に分けている。 """ from __future__ import annotations import re import subprocess from collections.abc import Callable, Iterable, Sequence from dataclasses import dataclass from pathlib import Path # b...
hidari/dotfiles
scripts/backup-tool/src/backup_tool/rsync.py
.py
30daf8ccaa56f4e6
7
0
"""disk モジュールの純粋関数に対するテスト。 実際に du / df を呼ぶ副作用レイヤーは結合レベルで検証する。 """ from __future__ import annotations import pytest from backup_tool.disk import check_capacity, required_total_kb class TestRequiredTotalKb: def test_adds_source_and_margin(self) -> None: # 1GB source + 100GB margin = 101 GB 相当の KB ...
hidari/dotfiles
scripts/backup-tool/tests/test_disk.py
.py
73aa1608a4169abb
7.5
0
"""paths モジュールの純粋関数に対するテスト。""" from __future__ import annotations from backup_tool.paths import classify, extract_volume_path class TestClassify: def test_volume_root(self) -> None: assert classify("/Volumes/Primary") == "volume" def test_volume_with_trailing_slash(self) -> None: # ボリューム直下に...
hidari/dotfiles
scripts/backup-tool/tests/test_paths.py
.py
39ec3b954264eca0
7.5
0
"""runner モジュールの純粋ヘルパーに対するテスト。 _execute_pair / _verify_path / _verify_capacity は副作用が重いので 統合テストで扱い、ここでは終了コード集約と excludes 合成のみを検証する。 """ from __future__ import annotations from backup_tool.config import BackupPair, Config from backup_tool.runner import ExitCode, _build_excludes, _determine_exit_code def _make_config...
hidari/dotfiles
scripts/backup-tool/tests/test_runner.py
.py
455b89d02f668d94
7.5
0
"""instructions-loaded-log hook の黒箱テスト。 hook 本体をサブプロセス起動し、stdin に InstructionsLoaded の JSON を流して JSONL へ書かれた 内容を検証する。モックは使わず、書き込み先は tmp_path 配下へ向ける。 """ from __future__ import annotations import json import os import subprocess import sys from datetime import datetime, timedelta from pathlib import Path from typing ...
hidari/dotfiles
scripts/claude-hooks/tests/test_instructions_loaded_log.py
.py
f5fe8b82221eea82
7.5
0
"""apm が deploy する成果物が全て gitignore されているか検査する。 apm.lock.yaml の deployed_files は「apm が展開する再生成物」の canonical な一覧。 install-at-bootstrap では deploy 先を gitignore して bootstrap で再生成する前提なので、 deployed_files は全て home/.gitignore で ignore されねばならない。 ignore はディレクトリ単位なのでパッケージ追加では追記が要らない。この検査が捕まえるのは apm が新しい deploy root を作った場合で、そのとき成果...
hidari/dotfiles
scripts/config-guard/src/config_guard/apm_gitignore.py
.py
afdfbdc004b344a4
7
0
"""apm.yml の依存 pin が commit SHA で固定され、群としても実配置とも揃っていることを検査する。 home/apm.yml は 1 リポジトリから複数のパッケージを取るため、同じ commit hash が 複数行に literal で並ぶ。更新は全行を揃えて動かす前提だが、1 行だけ更新し忘れても apm install は成功し、そのパッケージだけ古い版が静かに配られる。エラーにならず 「短い正常な結果」として返るので、install ログを見ても気づけない。 この guard が見るのは 4 つ。 - ref が commit SHA で固定されているか (README が宣言する再現性の担保。...
hidari/dotfiles
scripts/config-guard/src/config_guard/apm_pins.py
.py
17825e9fce94aff3
7
0
"""常時ロード層の予算定数が baseline から無音で増えていないことの検査。 `instruction_budget` の予算は上限を名乗るが、超えたときに上限のほうを書き換えれば 全緑で通る。実際に 1 セッションで 2 度上げている。追記が止まらないという起票理由 (実測値は `instruction_budget` の docstring) を防ぐ力が無いのはこの経路のためで、 爪の無い歯車になっていた。 上げること自体は禁じない。禁じるのは無音で上げることで、引き上げには `BUDGET_RAISES` への記録 (日付・引き上げ後の値・理由) を要求する。据え置きと 引き下げは無条件に通す。 baseline...
hidari/dotfiles
scripts/config-guard/src/config_guard/budget_ratchet.py
.py
f940016fd001b6a1
7
0
"""リポジトリをスキャンして構造逸脱を検出する。 stale なツール名参照 / committed settings.json の不変条件 / 追跡ファイルに変更を隠す index の bit が立っていないか / apm.lock.yaml の deployed_files が gitignore されているか(新しい deploy root の検出) / mise の global ツール pin が exact か / apm.yml の依存 pin が commit SHA で固定され 宣言どうしと実配置で揃っているか / herdr keybinding の方向整合と chord 重複 / 追跡下の Markdown...
hidari/dotfiles
scripts/config-guard/src/config_guard/cli.py
.py
f177a7a4b7edb86c
7
0
"""検査対象からツール名トークンを抽出する。 SKILL.md は frontmatter の allowed-tools リスト(フラットなリスト)を標準ライブラリ だけで抽出する(YAML パーサ依存を避ける)。settings.json は dict から permissions を 取り出す。 """ from __future__ import annotations import re from typing import Any _FRONTMATTER_DELIM = re.compile(r"^---\s*$") _ALLOWED_TOOLS_KEY = re.compile(r"^allowed-too...
hidari/dotfiles
scripts/config-guard/src/config_guard/extractors.py
.py
39dd36f689639dfa
7
0
"""git をロケーション系 GIT_* の継承から隔離して起動するヘルパ。 pre-commit / git hook 経由で実行されると git は GIT_DIR / GIT_WORK_TREE / GIT_INDEX_FILE 等を子プロセスへ渡す。これらを継承すると `git -C <repo>` の repo 探索が hook 側の repo に上書きされ、別の index / worktree を読んでしまう(worktree からの コミットで実際に踏んだ)。repo 指定を -C に一本化するため、ロケーション系 GIT_* を 除いた環境で git を起動する。 """ from __future__ im...
hidari/dotfiles
scripts/config-guard/src/config_guard/git_run.py
.py
7ec3e5c298243b01
7
0
"""herdr の keybinding 設定 (config.toml) の不変条件を検査する。 herdr の previous_* / next_* は対で使われ、chord の最終キーが向きを表す (left/up/[/h/k = 前へ、right/down/]/j/l = 次へ)。この対応が逆転していても herdr は 警告なく起動するため、実際に指で押すまで誰も気づかない。実例として previous_workspace に "ctrl+shift+alt+]" が、next_workspace に "ctrl+shift+alt+[" が割り当たっており、同じ config 内の cycle_pane_* とは逆...
hidari/dotfiles
scripts/config-guard/src/config_guard/herdr_keys.py
.py
2967a8f423f38691
7
0
"""追跡ファイルに変更を隠す index の bit が立っていないか検査する。 skip-worktree と assume-unchanged は working tree の変更を git から隠す。 `home/.claude/settings.json` はこの skip-worktree で live と committed を分けて運用して いたが、分ける理由 (ローカル絶対パスを持つ directory source の marketplace 宣言と、そこから 来る plugin エントリ) が apm 配布への移行で消えたため解除した。bit が復活すると、live 側の 変更が git diff にも CI...
hidari/dotfiles
scripts/config-guard/src/config_guard/index_flags.py
.py
fd95838989f8b1c1
7
0
"""常時ロードされる指示ファイルの総バイト数を予算内に保つ検査。 CLAUDE.md は追記で膨らみ続ける (実測: 2026-08-12 の 36,599B から 9 日で 52,766B)。 一回きりの削減は数週間で食われるため、削減量ではなく上限を検査で固定する。 「常時ロード」の判定は Claude Code の実測仕様に従う。 - User スコープの CLAUDE.md は session_start で必ずロードされる - `~/.claude/rules/*.md` は paths frontmatter が無いときだけ session_start でロードされる - paths を持つ rules は該当パ...
hidari/dotfiles
scripts/config-guard/src/config_guard/instruction_budget.py
.py
a628086683dd16d2
7
0
"""指示ファイルどうしの参照が実在するかを検査する。 参照は 2 種類ある。どちらも壊れ方が「探すと 0 件」の沈黙で、改名や移動をしても 誰も赤くならない。 - パス参照: `~/.claude/<path>` が repo の `home/.claude/<path>` に実在するか - 見出し参照: `~/.claude/<file>` の「<name>」 の <name> が <file> の見出しに実在するか `markdown_links` はインラインコードを除去してからリンクを探すので、この 2 種はどちらも 1 件も見えない。捨てている領域がこちらの検査対象そのものなので、隣に別モジュールを置く。 参照先...
hidari/dotfiles
scripts/config-guard/src/config_guard/instruction_refs.py
.py
babb6b14725c225b
7
0
"""追跡下の Markdown の相対リンクが実在するかを検査する。 Issue を docs/issues/closed/ へ移すたびに、その Issue を指す相対リンクと、その Issue から 出ているリンクの両方が切れる。`../10_...` と `../closed/10_...` の書き分けが両端の open / closed 状態に依存するためで、close する側とは別のファイルへ波及編集が要り、 壊れたリンクが検出されないまま main に残った実績がある。 扱うのはインラインリンク `[text](target)` のみ。参照リンク定義・HTML タグ・自動リンクは リポジトリに 1 件も無いため対象外...
hidari/dotfiles
scripts/config-guard/src/config_guard/markdown_links.py
.py
bf25e536d333c334
7
0
"""mise の global ツール pin が exact 指定であることを検査する。 home/.config/mise/config.toml は「exact 指定で全マシンを完全再現する」規約を持つが、 規約はコメントにしか書かれておらず何も強制していなかったため、`just = "latest"` が 素通りした実績がある。浮動 pin はマシンごとに解決版が変わり、config を symlink して いても再現性が崩れる(しかも壊れるまで気づけない)ので、ここで機械的に弾く。 この guard は「exact であることの証明」ではなく「明らかな浮動形の排除」である。mise は exact 一致しない sp...
hidari/dotfiles
scripts/config-guard/src/config_guard/mise_pins.py
.py
a68ff50780a0fb06
7
0
"""`## 関連` 節の Issue 参照が識別子だけで書かれ、その識別子が実在するかの検査。 Issue をクローズすると `docs/issues/closed/` へ移り、パスの深さが 1 段変わる。相対リンクは この深さに依存するので、移動のたびに両方向の書き換えが要る。リンクを張らなければ移動を 残したまま書き換えが 0 になる (設計は Issue 43 の spec が canonical)。 `markdown_links` との違いは見る対象。あちらはリンク先のパスを見て、こちらは識別子を見る。 リンクを外した後に残るのは識別子だけなので、あちらの検査は届かなくなる。 ## 他リポジトリ参照 前置の無い識...
hidari/dotfiles
scripts/config-guard/src/config_guard/related_refs.py
.py
4a683a11453688b2
7
0
import json import time from typing import Dict, List import requests import utils ENTERGY_ENDPOINTS = { "county": "https://entergy.datacapable.com/datacapable/v1/entergy/EntergyLouisiana/county", "zipcode": "https://entergy.datacapable.com/datacapable/v1/entergy/EntergyLouisiana/zip", } REQUIRED_COUNTY_FIEL...
patricktrainer/entergy-outages
entergy_outages/main.py
.py
9e115d0362d562e0
7.39
5
#!/usr/bin/env python3 """Claude Code の PreToolUse フック: 権限設定 (autoMode) の書き換えを人間に返す。 `autoMode` はこのマシンで「何を確認なしに実行してよいか」を決める節で、緩めることは エージェントが自分に権限を与えることそのものにあたる。`hard_deny` の "Auto-Mode Self-Authorization" がそれを "Block unconditionally" と宣言しているが、 実際には Edit ツール経由の書き換えが素通しになった (setup#85)。ルール本文は `jq` / `sed` / heredoc / `gi...
shinyaoguri/setup
claude/automode-guard.py
.py
04e921dc071605c4
7
0
#!/usr/bin/env python3 """claude/provisioning-preflight.sh のテスト。 実物の ansible を回すと遅く、結果がマシンの状態に依存してしまうので、PATH の先頭に 偽の `ansible-playbook` を置いて出力を固定する。検証したいのは「予告をどう読んで どう判断するか」であって ansible の挙動ではない。 python3 claude/tests/provisioning_preflight_test.py """ import json import os import stat import subprocess import tem...
shinyaoguri/setup
claude/tests/provisioning_preflight_test.py
.py
1bf8b014f15741c4
7.5
0
#!/usr/bin/env python3 """claude/repo-standards.json のテスト。 repo-standards.json はリポジトリ標準チェックリストの正本で、消費者は claude-plugins の repo-standards プラグイン (同梱スクリプトが jq でパースする)。 ここではスキーマの整合 (enum・必須フィールド・参照解決) を検証し、 消費側が黙って項目を読み飛ばす事故を防ぐ。 python3 claude/tests/repo_standards_test.py """ import json import unittest from pathlib ...
shinyaoguri/setup
claude/tests/repo_standards_test.py
.py
88d37ab3b279add2
7.5
0
#!/usr/bin/env python3 """bin/secret-read のテスト。 本物の op を呼ぶと 1Password の承認プロンプトが出てしまい、本物の security を呼ぶと 実際の Keychain を汚す。どちらも PATH の先頭に偽物を置いて差し替える (provisioning preflight のテストと同じ型)。検証したいのは「どの参照をキャッシュしてよいと判断し、 いつ op を呼ばずに済ませるか」であって、op や security の挙動ではない。 このスクリプトの肝は **op を呼ばずに値が返せること** (= 1Password がロックされていても 無人セッションが止ま...
shinyaoguri/setup
claude/tests/secret_read_test.py
.py
f51fad8e42801a1c
7.5
0
#!/usr/bin/env python3 """claude/settings.json のテスト。 settings.json は全マシンのグローバル設定の正本で、JSON が壊れると設定が丸ごと 無視される (repo-standards の env-doctor が検知する事故そのもの)。ここでは パースの成立に加えて、`permissions.allow` が**読み取り専用の範囲を出ていない** ことを検証する。 allow は確認プロンプトを消すための宣言なので、うっかり書き込み系を載せると 「聞かれずに実行される」側へ倒れる。文書ルールで抑えるのでなく、変更を伴う コマンドが混ざった時点で CI が落ちるように...
shinyaoguri/setup
claude/tests/settings_test.py
.py
5f15c990580203c4
7.5
0
#!/usr/bin/env python3 """zshenv のテスト。 zshenv は「人が打つとき以外にも要るもの」の置き場。zshrc は非対話シェル (Claude Code の hook・scheduled task・cron) では読まれないので、そこへ置いたものは 無人セッションでだけ黙って消える。GYAZO_TOKEN_REF で一度踏み (#90)、SSH_AUTH_SOCK で 同じ轍を踏んだ (#91) ため、両方ここで固定する。 肝は SSH_AUTH_SOCK の分岐で、次の 2 つを対にして見る: - ローカルのシェルでは Secretive (Secure Enclave) の agent...
shinyaoguri/setup
claude/tests/zshenv_test.py
.py
67fed35fe53714ee
7.5
0
# -*- coding: utf-8 -*- from typing import List, Dict, Iterable, Iterator from pybiotk.bx.bitset import BinnedBitSet, MAX def binned_bitsets_from_list(lst: Iterable[List]) -> Dict: """Read a list into a dictionary of bitsets""" last_chrom = None last_bitset = None bitsets = dict() for bed in lst:...
liqiming-whu/pybiotk
src/pybiotk/intervals/merge_bed3.py
.py
c3ad84621fa2afcf
7.15
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Path: src/pybiotk/utils/bigwigfetcher.py """ Fetch signal value from bigwig file. """ import argparse import re import sys import time from typing import Sequence, Optional, Literal from pybiotk.io import Openbwn, Openbed from pybiotk.utils import configure_logging, get...
liqiming-whu/pybiotk
src/pybiotk/utils/bigwigfetcher.py
.py
9510e8ecb592dcf7
7.15
1
#!/usr/bin/env python # # @license Apache-2.0 # # Copyright (c) 2018 The Stdlib Authors. # # 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 # # ...
stdlib-js/math-base-special-acos
benchmark/python/benchmark.py
.py
e6d21beb4f63a1da
7.15
1
#!/usr/bin/env python # # @license Apache-2.0 # # Copyright (c) 2020 The Stdlib Authors. # # 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 # # ...
stdlib-js/math-base-special-acot
benchmark/python/benchmark.py
.py
19fde35c2840730f
7.24
2
#!/usr/bin/env python3 """One-off utility to populate the `leap_url` column for existing rows in the `compliance_documents` table. Run this once after upgrading the database schema. It is idempotent – rows that already possess a non-blank `leap_url` are skipped. """ from __future__ import annotations import argparse...
EPA-Ireland-Updates-Unofficial/epa_ireland_scraper
backfill_leap_url.py
.py
77aa0f123a150d34
7.24
2
#!/usr/bin/env python3 """ Script to regenerate CSV files for a specified date range. This will delete existing CSV files and regenerate them with the fixed deduplication logic. Usage: python regenerate_csvs.py <start_date> <end_date> Date format: YYYY-MM-DD If start_date and end_date are the same, only that single d...
EPA-Ireland-Updates-Unofficial/epa_ireland_scraper
regenerate_csvs.py
.py
0aab07c77550cdc3
7.24
2
#!/usr/bin/env python3 """Fix titles for Complaint documents in the local EPA Ireland SQLite DB. For each entry in the `compliance_documents` table with: • document_type = 'Complaint' • (title IS NULL OR title = '') this script parses the `metadata_json` column and attempts to extract the `subject` string (nested ...
EPA-Ireland-Updates-Unofficial/epa_ireland_scraper
update_complaint_titles.py
.py
a41ac7d7212c3377
7.24
2
#!/usr/bin/env python3 """Fix titles for Incident documents in the local EPA Ireland SQLite DB. For each entry in the `compliance_documents` table with: • document_type = 'Incident' • (title IS NULL OR title = '') this script parses the `metadata_json` column and attempts to extract the `subject` string (nested in...
EPA-Ireland-Updates-Unofficial/epa_ireland_scraper
update_incident_titles.py
.py
37fd6ff88633f7ba
7.24
2
#!/usr/bin/env python # # @license Apache-2.0 # # Copyright (c) 2018 The Stdlib Authors. # # 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 # # ...
stdlib-js/math-base-special-binomcoef
benchmark/python/scipy/benchmark.py
.py
c4cb49b85659ce8c
7.15
1
#!/usr/bin/env python # # @license Apache-2.0 # # Copyright (c) 2018 The Stdlib Authors. # # 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 # # ...
stdlib-js/math-base-special-hypot
benchmark/python/benchmark.py
.py
ee706dd2d4ea0b3f
7.24
2
""" Implementation of a simple multivalent binding model. """ from collections.abc import Callable import jax import jax.numpy as jnp import numpy as np import numpy.typing as npt import optimistix as opt from scipy.special import binom jax.config.update("jax_enable_x64", True) def Req_polyfc( Phisum: jax.Arra...
meyer-lab/valentBind
valentbind/model.py
.py
432d8fcafa729fa9
7.24
2
"""Deterministic regression and edge-case tests for the binding model. These complement the randomized property tests in test_model.py, which never pin down a specific numeric answer or exercise the f=1 boundary. """ import numpy as np from ..model import polyfc def test_polyfc_monovalent_matches_langmuir() -> Non...
meyer-lab/valentBind
valentbind/test/test_edge_cases.py
.py
a4ec480be8c5dee3
7.74
2
from collections.abc import Iterator import jax import numpy as np import numpy.typing as npt from jax import jacrev from scipy.special import binom from ..model import polyc, polyfc def genPerm(len: int, sum: int) -> Iterator[list[int]]: """ Enumerate every way to write ``sum`` as an ordered sum of ``len``...
meyer-lab/valentBind
valentbind/test/test_model.py
.py
01f57212fbeab390
7.74
2
""" python script to illustrate an application of the simple model language. usage: python3 sample2data.py <stack> [<angle> <time>] [<angle2> <time2>] ... with <stack> = sample description according to simple model language <angle> = sample orientation 'mu' on Amor <time> = counting time ! The intensity and...
reflectivity/orsopy
examples/sample2data.py
.py
af189f211be7f11d
7
0
""" Implementation of the data_source for the ORSO header. """ from dataclasses import dataclass, field from datetime import datetime from enum import Enum from typing import Dict, List, Optional, Union import yaml from .base import AlternatingField, ComplexValue, File, Header, Person, Value, ValueRange, ValueVector ...
reflectivity/orsopy
orsopy/fileio/data_source.py
.py
8d293df86ada8c7f
7
0
""" Build-in blocks of physical units used in model to describe more complex systems. All these need to follow the .model_building_blocks.SubStackType protocol and have a common "sub_stack_class" attribute that has to be set to the class name. """ from dataclasses import dataclass from typing import List, Optional, U...
reflectivity/orsopy
orsopy/fileio/model_complex.py
.py
6f14b7399ffbe7d1
7
0
""" Implementation of the top level class for the ORSO header. """ from dataclasses import dataclass from typing import BinaryIO, List, Optional, Sequence, TextIO, Union import numpy as np import yaml from .base import (JSON_MIMETYPE, Column, ErrorColumn, Header, OrsoDumper, _dict_diff, _nested_update, ...
reflectivity/orsopy
orsopy/fileio/orso.py
.py
fc1fab193f31c8c0
7
0
""" The reduction elements for the ORSO header """ import datetime from dataclasses import dataclass, field from typing import List, Optional, Union from .base import Header, Person @dataclass class Software(Header): """ Software description. :param name: Software name. :param version: Version ide...
reflectivity/orsopy
orsopy/fileio/reduction.py
.py
c361021fc8b5b584
7
0
""" Module for compatibility with Python <3.8. Requires the typing_extensions module to be installed. """ from typing import List, Tuple from typing_extensions import Literal def get_args(annotation): if annotation.__class__ is Literal.__class__: return annotation.__values__ return getattr(annotatio...
reflectivity/orsopy
orsopy/fileio/typing_backport.py
.py
3958a0253feef043
7
0
""" Manage database creation, insertion and access. """ import sqlite3 from .comparators import Comparator from .dbconfig import (DB_MATERIALS_CONVERTERS, DB_MATERIALS_FIELD_DEFAULTS, DB_MATERIALS_FIELDS, DB_MATERIALS_NAME, db_lookup) from .importers import importers from .material import Formu...
reflectivity/orsopy
orsopy/slddb/database.py
.py
a159f557edec29cb
7
0
""" Functions to create database compatible entries from other file formats. """ import os import pathlib from .dbconfig import db_lookup from .material import Formula, PolymerSequence class Importer(dict): """ Base class for importing database entries. Includes checks for correctness used by all importers. ...
reflectivity/orsopy
orsopy/slddb/importers.py
.py
fcd33c7655a158f8
7
0