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 |
|---|---|---|---|---|---|---|
"""Synchronous engine loop: scheduling, execution, detokenization, and finish detection."""
from __future__ import annotations
import itertools
from dataclasses import dataclass
from clockwork.config import EngineConfig
from clockwork.engine.model_runner import ModelRunner
from clockwork.engine.sequence import Reque... | jasonjesuraja06/clockwork | clockwork/engine/llm_engine.py | .py | 5f711de862e9cc16 | 7 | 0 |
"""Attention entry points: dense reference plus paged prefill and decode in torch."""
import torch
from clockwork.kernels.triton_paged_attn import HAS_TRITON, triton_paged_attention_decode
__all__ = [
"HAS_TRITON",
"naive_attention",
"paged_attention_decode",
"paged_attention_decode_torch",
"page... | jasonjesuraja06/clockwork | clockwork/kernels/attention.py | .py | 5962e82a7f00771e | 7 | 0 |
"""Triton paged-attention decode kernel; imports cleanly without Triton."""
import torch
try:
import triton
import triton.language as tl
HAS_TRITON = True
except ImportError:
HAS_TRITON = False
if HAS_TRITON:
@triton.jit
def _paged_decode_kernel(
q_ptr,
k_ptr,
v_ptr... | jasonjesuraja06/clockwork | clockwork/kernels/triton_paged_attn.py | .py | 09102327e8391e89 | 7 | 0 |
class AllocatorOutOfMemory(RuntimeError):
"""Raised when the block pool cannot satisfy an allocation."""
class BlockAllocator:
"""Refcounted physical block pool with copy-on-write."""
def __init__(self, num_blocks: int, block_size: int) -> None:
if num_blocks <= 0:
raise ValueError(f"... | jasonjesuraja06/clockwork | clockwork/kvcache/block.py | .py | f9aca6118982102d | 7 | 0 |
from clockwork.engine.sequence import Sequence
from clockwork.kvcache.block import BlockAllocator
from clockwork.kvcache.kv_cache import PagedKVCache
class BlockManager:
"""Sequence-to-block mapping; owns admission, growth, copy-on-write, and prefix sharing."""
def __init__(
self,
allocator: ... | jasonjesuraja06/clockwork | clockwork/kvcache/block_manager.py | .py | 733089023c974198 | 7 | 0 |
import torch
class PagedKVCache:
"""Physical paged K/V tensors per layer, [num_blocks, block_size, num_kv_heads, head_dim]."""
def __init__(
self,
num_layers: int,
num_blocks: int,
block_size: int,
num_kv_heads: int,
head_dim: int,
dtype: torch.dtype = ... | jasonjesuraja06/clockwork | clockwork/kvcache/kv_cache.py | .py | 6e134bf6ce5de106 | 7 | 0 |
from __future__ import annotations
from dataclasses import dataclass, field
from clockwork.kvcache.block import BlockAllocator
from clockwork.radix.tree import RadixTree
@dataclass
class RadixCacheStats:
queries: int = 0
hit_tokens: int = 0
prompt_tokens: int = 0
@property
def hit_rate(self) ->... | jasonjesuraja06/clockwork | clockwork/radix/cache.py | .py | bc1050e5a01e1983 | 7 | 0 |
from __future__ import annotations
class RadixNode:
__slots__ = ("parent", "children", "token_ids", "block_ids", "last_access", "lock_count")
def __init__(
self,
parent: RadixNode | None = None,
token_ids: list[int] | None = None,
block_ids: list[int] | None = None,
) -> N... | jasonjesuraja06/clockwork | clockwork/radix/tree.py | .py | 7a913e9ba3d9f575 | 7 | 0 |
"""Continuous batching scheduler: decode first, FCFS admission, preemption by recompute."""
from __future__ import annotations
from dataclasses import dataclass, field
from clockwork.config import SchedulerConfig
from clockwork.engine.sequence import Sequence, SequenceStatus
from clockwork.kvcache.block_manager impo... | jasonjesuraja06/clockwork | clockwork/scheduler/scheduler.py | .py | fc35e703798acbdf | 7 | 0 |
"""Collect bench result CSVs into markdown tables, results.md, and figures."""
from __future__ import annotations
import argparse
import csv
import sys
from pathlib import Path
from clockwork.bench.metrics import summarize
from clockwork.bench.plots import plot_all
from clockwork.bench.runner import CSV_FIELDS, SUMM... | jasonjesuraja06/clockwork | scripts/collect_results.py | .py | d012382be15de553 | 7 | 0 |
# Fetches ACM events from Dragon Central RSS feed and updates docs/data/events.json
# Usage: python automation/scripts/fetch_rss.py
import hashlib, json, os, sys, re
from datetime import datetime, timezone
from xml.etree import ElementTree as ET
try:
import feedparser
except ImportError:
print(
"feedp... | MSUM-ACM/MSUM-ACM.github.io | automation/scripts/fetch_rss.py | .py | 79a42a925f1eb7dd | 7 | 0 |
#!/usr/bin/env python3
"""Say which pllsim build an APK actually is, by looking inside it.
The interpreted and compiled APKs are produced by the same Gradle task from
the same workspace, differing only in what ``android/app/pysrc/`` held at the
time. Nothing in the build log records which one you got, and the two are... | alexyudragonsword-collab/pll_simulator | .claude/skills/pllsim-android-build/scripts/inspect_apk.py | .py | 31ae1fc7afbcd992 | 7.5 | 0 |
"""Generate docs/roadmap.md: a register of known gaps, measured not remembered.
A roadmap is the documentation most likely to rot, and this project has just
spent two releases repairing rotted documentation. So this one states what is
*currently true and checkable* -- how many type errors stand between a package
and ... | alexyudragonsword-collab/pll_simulator | docs/gen_roadmap.py | .py | 4f45f6944e098c9a | 7 | 0 |
"""Emit the numbers the deck quotes, straight from the library.
The deck is a binary. Every count in it -- architectures, presets, examples,
tests, the version, the benchmark table -- was typed in by hand, and the
v0.9.0 deck went stale within one release: it still said 405 tests and 20
examples after the suite reach... | alexyudragonsword-collab/pll_simulator | docs/reports/collect_facts.py | .py | fe3f9a76d6064409 | 7 | 0 |
"""Build a Chaquopy-installable wheel with parts of pllsim compiled to native code.
Why this exists
---------------
The app ships Python. An APK is a zip, Chaquopy's payload inside it is a zip,
and `.pyc` gives back names, line numbers and docstrings to anyone who runs
`strings` -- measured on this codebase, the whol... | alexyudragonsword-collab/pll_simulator | packaging/android_wheel.py | .py | f77bf9ef2e6de15f | 7 | 0 |
"""Charge pump with mismatch, leakage and noise."""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from ..core.colored import synth_from_psd
from ..core.noise import CurrentNoise
@dataclass
class CPConfig:
icp: float # nominal current [A]
mismatch... | alexyudragonsword-collab/pll_simulator | src/pllsim/blocks/chargepump.py | .py | bb868c52aaadf030 | 7 | 0 |
"""Digital-to-time converter with gain error, INL and jitter.
The loop requests a delay in seconds; the DTC computes a code using its
*calibrated* gain (gain_corr, updated by LMS) and the physical device applies
its *true* gain (1 + gain_error) plus INL and random jitter. A mid-range
static offset keeps codes positiv... | alexyudragonsword-collab/pll_simulator | src/pllsim/blocks/dtc.py | .py | 5d5578ea65f74355 | 7 | 0 |
"""Sampling phase detector front-end (SSPLL / SPLL)."""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
KB = 1.380649e-23
T0 = 290.0
@dataclass
class SamplerConfig:
amp_v: float = 0.4 # sampled waveform amplitude at the PD [V]
c_samp: float = 50e-15 ... | alexyudragonsword-collab/pll_simulator | src/pllsim/blocks/sampler.py | .py | df421fc78870df43 | 7 | 0 |
"""Time-to-digital converter models: flash TDC and bang-bang PD."""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
@dataclass
class TDCConfig:
t_res: float # LSB [s]
n_bits: int = 7 # range = 2^bits * t_res (should cover ~1 Tdco)
in... | alexyudragonsword-collab/pll_simulator | src/pllsim/blocks/tdc.py | .py | 077cf590be0aad9f | 7 | 0 |
"""MCP server for synthetic compliance-evidence retrieval."""
import json
import re
import unicodedata
from pathlib import Path
from typing import Any
from mcp.server.fastmcp import FastMCP
PROJECT_NAME = "Evidence-Grounded MCP Agent"
DATA_FILE = Path(__file__).resolve().parent / "data" / "cases.json"
mcp = FastMCP... | Rickytrytobebetter/Evidence-Grounded-MCP-Agent | server.py | .py | 70c53121a93b820c | 7 | 0 |
"""
benchmark_noise.py - Comparaison de robustesse au bruit
ASH vs FFT+LDA vs Ondelettes+SVM sur signaux synthétiques avec bruit
Auteur : Patrice Portemann
Datasets : régénérer d'abord via les générateurs seedés de examples/
(les CSV sont ignorés par git — voir ../.gitignore et SHASUMS.txt).
"""
import numpy as np
im... | PORTEMANN/noetic-ash | benchmarks/benchmark_noise.py | .py | 573d58151921fabb | 7 | 0 |
# -*- coding: utf-8 -*-
"""
benchmark_mitdb_real.py
Validation de l'ASH sur la base MIT-BIH (enregistrement 100)
Classification binaire : battement normal vs anomalie (PVC)
Comparaison ASH, FFT+LDA, ondelettes+SVM
Nécessite : pip install wfdb numpy scipy scikit-learn pywt
Dataset : PhysioNet mitdb, record 100 — vérifi... | PORTEMANN/noetic-ash | benchmarks/mitdb/benchmark_mitdb_real.py | .py | 38af9cefd4c8bec0 | 7 | 0 |
"""
benchmark_mitdb_rf_smote.py
Validation ASH sur MIT-BIH 100 avec SMOTE + Random Forest.
Comparaison ASH, FFT+LDA, Ondelettes+SVM.
Dépendances : numpy, scipy, wfdb, scikit-learn, imbalanced-learn, pywt
Note C12.1 : ce script réimplémente l'extraction des invariants en local
(extract_ash_features) pour produire un ve... | PORTEMANN/noetic-ash | benchmarks/mitdb/benchmark_mitdb_rf_smote.py | .py | 77b63c23259838a4 | 7 | 0 |
"""
Analyse financière / séries temporelles lentes avec l'ASH
Usage: python finance_analyzer.py fichier.csv [freq_sampling] [f0] [octaves]
Auteur: Patrice Portemann
"""
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.signal import welch, find_peaks
def build_noetic_grid(f0... | PORTEMANN/noetic-ash | contrib/finance/finance_analyzer.py | .py | d9a8fa74a89703b6 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
swarm_ash.py - ASH distribué pour essaims de capteurs (IoT, drones)
Auteur : Patrice Portemann
Date : 2026-06-07
Implémente :
- Une classe `SwarmASH` qui gère un réseau de nœuds.
- Chaque nœud possède une instance locale de `ASH` (noyau consolidé).
- Propagation d'ale... | PORTEMANN/noetic-ash | contrib/swarm/swarm_ash.py | .py | 2ee1f7b7b9613466 | 7 | 0 |
"""What the automation is doing, as one page you can read.
The office already ships every part of this answer, and that is exactly the
problem it has: the schedule is on the Pipeline card, the public path is on the
Webhooks card, and what the runner actually DID is 24 receipts buried on each of
72 desks. Nobody assemb... | ariaxhan/nexus-office | client/automation.py | .py | b320cc9463e44a09 | 7 | 0 |
"""The local agent runtime, as a source the office can read.
The office already knows what work EXISTS, from the issue pipeline. This is the
half that knows what is happening RIGHT NOW: which agent is mid-run, what it is
blocked on, what it has cost. That lives on this machine and never leaves it, so
the adapter runs ... | ariaxhan/nexus-office | client/runtime.py | .py | 2df2858e4ddfbb5a | 7 | 0 |
"""The local data each fixture in the room reads.
The office already ships the pipeline's own state. These are the OTHER local
facts a room should show: what is scheduled, what it cost, what is waiting in
the mailroom, what memory holds. Each one lives in its own file under
`sources/`, and each is listed here once.
E... | ariaxhan/nexus-office | client/sections.py | .py | e1f269d08e3f7b3b | 7 | 0 |
"""One card per fixture: the sentence a person reads from across the room.
Every source in here already returns the whole truth, and that is the point of
them. None of it fits on a card at the far end of an office, and none of it fits
on a phone. So each source also answers a much smaller question: what is the one
lin... | ariaxhan/nexus-office | client/sources/_card.py | .py | e8140a92cbc98fcc | 7 | 0 |
"""The scheduled jobs, from jobctl.
A job that stopped firing looks exactly like a job with nothing to do. That is
the whole reason this source exists, and it is why the states here are kept
apart rather than folded into a health percentage:
ok succeeded inside the budget the job declares for itself
stale ... | ariaxhan/nexus-office | client/sources/clock.py | .py | b881d9763dad3163 | 7 | 0 |
"""the spend ledger.
The ledger is `<root>/_meta/logs/costs.jsonl`, one JSON object per line, written
by several different tools over about a year. It is NOT one schema. Measured on
2026-08-25 across 1225 rows: nine distinct key sets, two different names for the
money field (`total_cost` and `cost_usd`), two for the t... | ariaxhan/nexus-office | client/sources/cost.py | .py | 53c3e98b167f27a5 | 7 | 0 |
"""The intake and sync flows, one row each, read from the receipts themselves.
`clock.py` is the aggregate: every one of the ~52 scheduled jobs, judged by
`jobctl status`, folded into counts. This is the other lens: a NAMED handful of
flows, the ones that move data into the vault, each judged on its own row.
The reas... | ariaxhan/nexus-office | client/sources/flows.py | .py | 9d9594f4233dda0b | 7 | 0 |
"""What memory holds, as a source the office can read.
Two stores, and they are not the same thing, so they are read separately and
each reports its own reachability:
agentdb a SQLite file at <root>/_meta/agentdb/agent.db. Several hundred flat
learnings typed failure | gotcha | pattern | preference, e... | ariaxhan/nexus-office | client/sources/library.py | .py | a261084c9782ea52 | 7 | 0 |
"""The library source: what memory holds, and what it says when it cannot say.
The dangerous failure here is not a wrong number. It is a library that draws as
empty when it is actually unreadable, or a shelf of 20 presented as a shelf of
234. Both of those are false greens with furniture around them, so those are the
... | ariaxhan/nexus-office | tests/test_library.py | .py | 0a88196d864f11ae | 7.5 | 0 |
"""Add network and ownership columns to stations and basins
Revision ID: 0003
Revises: 0002
Create Date: 2026-03-18
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0003"
down_revision: str | None = "0002"
branch_labels: str | Sequence[str] | None = None
dep... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0003_add_network_and_ownership.py | .py | 2e41febffec03ed9 | 7 | 0 |
"""Rename flow_regime_configs q50/q90 columns to p50/p90
Revision ID: 0006
Revises: 0005
Create Date: 2026-03-20
"""
from collections.abc import Sequence
from alembic import op
revision: str = "0006"
down_revision: str | None = "0005"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str]... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0006_rename_flow_regime_percentiles.py | .py | b2906e0cc924b8b3 | 7 | 0 |
"""Make models.description NOT NULL
Revision ID: 0007
Revises: 0006
Create Date: 2026-03-20
"""
from collections.abc import Sequence
from alembic import op
revision: str = "0007"
down_revision: str | None = "0006"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def ... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0007_models_description_not_null.py | .py | 7acfddfac7f1bb80 | 7 | 0 |
"""Convert boolean columns to text enum columns
Converts nwp_cycle_is_fallback, active, is_active, and is_stale
from boolean to text enum columns per enums-over-booleans rule.
Revision ID: 0009
Revises: 0008
Create Date: 2026-03-24
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic impo... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0009_bool_to_enum_conversions.py | .py | 509ea7c512f93bc7 | 7 | 0 |
"""Add supporting indexes for Phase 2 store implementations
- ix_station_group_members_station_id: enables artifact group fallback lookup
- ix_skill_scores_station_freshness: enables efficient mark_stale updates
Revision ID: 0010
Revises: 0009
Create Date: 2026-03-24
"""
from collections.abc import Sequence
from a... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0010_add_supporting_indexes.py | .py | d45ffa2db366138a | 7 | 0 |
"""Add QC columns to forecasts/hindcasts and forecast_qc_overrides table
Adds qc_status and qc_flags columns to forecasts and hindcast_forecasts
tables for forecast output quality checking. Creates the
forecast_qc_overrides table for per-station forecast QC threshold overrides.
Revision ID: 0012
Revises: 0011
Create ... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0012_add_forecast_qc_columns.py | .py | 5af5d4aba091651e | 7 | 0 |
"""Add LAKE station kind and parameter column to flow_regime_configs
Revision ID: 0013
Revises: 0012
Create Date: 2026-03-25
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0013"
down_revision: str | None = "0012"
branch_labels: str | Sequence[str] | None =... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0013_lake_support.py | .py | 2d421b62cc4233f4 | 7 | 0 |
"""Rename forecast_target to forecast_targets (JSONB array)
Revision ID: 0014
Revises: 0013
Create Date: 2026-03-26
"""
from collections.abc import Sequence
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB
from alembic import op
revision: str = "0014"
down_revision: str | None = "0013"
bra... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0014_rename_forecast_target_to_targets.py | .py | 4e7cdd5eefc96f73 | 7 | 0 |
"""Add parameter to hindcast_forecasts compound index.
Revision ID: 0015
Revises: 0014
Create Date: 2026-03-26
"""
from collections.abc import Sequence
from alembic import op
revision: str = "0015"
down_revision: str | None = "0014"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] |... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0015_hindcast_parameter_index.py | .py | 86ae4e54ab84c418 | 7 | 0 |
"""Widen forecast unique index to include parameter.
Revision ID: 0017
Revises: 0016
Create Date: 2026-03-27
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0017"
down_revision: str | None = "0016"
branch_labels: str | Sequence[str] | None = None
depends_on... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0017_widen_forecast_unique_index.py | .py | 41931a1f45443cba | 7 | 0 |
"""Add model_ids and alert_model_strategy to alerts table.
Revision ID: 0018
Revises: 0017
Create Date: 2026-03-30
"""
from collections.abc import Sequence
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB
from alembic import op
revision: str = "0018"
down_revision: str | None = "0017"
bran... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0018_alert_model_fields.py | .py | ceba08ca2e869209 | 7 | 0 |
"""Add gauging_status column to stations (nullable with default).
Step 1 of 2: add as nullable with server_default so the previous app image
can still INSERT rows without knowledge of this column during rolling deployment.
Revision ID: 0019
Revises: 0018
Create Date: 2026-04-02
"""
from collections.abc import Seque... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0019_add_gauging_status_nullable.py | .py | 81808d7bb6cf4148 | 7 | 0 |
"""Make gauging_status NOT NULL.
Step 2 of 2: all existing rows have the default 'gauged' from migration 0019.
Now enforce NOT NULL.
Revision ID: 0020
Revises: 0019
Create Date: 2026-04-02
"""
from collections.abc import Sequence
from alembic import op
revision: str = "0020"
down_revision: str | None = "0019"
bra... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0020_gauging_status_not_null.py | .py | fc9fc997643c0916 | 7 | 0 |
"""Add sha256_hash to model_artifacts.
Revision ID: 0022
Revises: 0021
Create Date: 2026-04-07
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0022"
down_revision: str | None = "0021"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequen... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0022_add_sha256_hash_to_model_artifacts.py | .py | d2be18c96c39fc13 | 7 | 0 |
"""Add multi-model combination columns and nullable artifact_id.
Revision ID: 0024
Revises: 0023
Create Date: 2026-04-13
"""
from collections.abc import Sequence
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB
from alembic import op
revision: str = "0024"
down_revision: str | None = "0023"... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0024_add_combination_columns.py | .py | c9390d6a83b3bf39 | 7 | 0 |
"""forecast provenance: nullable nwp_cycle_reference_time + runoff_only source
Revision ID: 0026
Revises: 0025
Create Date: 2026-07-01
epic-088 M4 forecast provenance. Runoff-only forecasts have no NWP cycle, so
``forecasts.nwp_cycle_reference_time`` becomes NULLABLE and the
``nwp_cycle_source`` CHECK admits the thir... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0026_forecast_provenance_runoff_only.py | .py | e5a7782b22263a52 | 7 | 0 |
"""station water-level datum metadata
Revision ID: 0027
Revises: 0026
Create Date: 2026-07-07
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0027"
down_revision: str | None = "0026"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0027_station_water_level_datum.py | .py | e1a3844fe7b1406e | 7 | 0 |
"""orphan header cleanup — delete forecast and hindcast headers with no value rows
Revision ID: 0028
Revises: 0027
Create Date: 2026-07-10
IMPORTANT — destructive data migration. Before running in production:
1. Run the dry-run queries below to confirm blast radius.
2. Take a full database backup.
3. Pause all flows... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0028_orphan_header_cleanup.py | .py | 5311fb3dae3b4d41 | 7 | 0 |
"""Hindcast deduplication constraint: unique index + values FK index.
Revision ID: 0029
Revises: 0028
Create Date: 2026-07-10
IMPORTANT — destructive data migration. Before running in production:
1. Run the dry-run queries below to confirm blast radius.
2. Take a full database backup.
3. Pause all flows.
4. Run `alem... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0029_hindcast_dedup_constraint.py | .py | a642cba87f784b8f | 7 | 0 |
"""weather-source role — forecast vs reanalysis identity
Revision ID: 0030
Revises: 0029
Create Date: 2026-07-14
Plan 115a. Adds a NULL-tolerant ``role`` column to ``station_weather_sources``
and backfills it from ``nwp_source``. NULL-tolerant so a previous-image
container can still write rows during the rollback win... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0030_weather_source_role.py | .py | 83250d41a5684dba | 7 | 0 |
"""retire the camels-ch weather binding (Release B, in-migration guard)
Revision ID: 0033
Revises: 0032
Create Date: 2026-07-18
Plan 115b5 — Release B of the 115b4 two-release cutover. Retires the
``camels-ch`` ``station_weather_sources`` REANALYSIS binding now that
Release A (the hybrid MeteoSwiss-priority reader) i... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0033_retire_camels_ch_weather_binding.py | .py | 20e3be826239f1cd | 7 | 0 |
"""observation + forecast rating-curve binding (Plan 035 Task 2)
Revision ID: 0035
Revises: 0034
Create Date: 2026-07-19
Catches the database up to the ``Observation``/``RawObservation`` types (which
already carry ``rating_curve_id`` + ``rating_curve_correction_version``) and
binds a forecast to the rating curve acti... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0035_observation_forecast_rating_curve_binding.py | .py | 069705e9f268d4fa | 7 | 0 |
"""observation_versions archive table (Plan 035 Task 3)
Revision ID: 0036
Revises: 0035
Create Date: 2026-07-20
Archives the (value, producing-curve) of a rating-curve-derived observation before
Flow 12 Branch A overwrites it during a rating-curve reprocessing (Task 5 wires the
writer; this task only builds the table... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0036_observation_versions_table.py | .py | 733cb3887a5e28c8 | 7 | 0 |
"""stations.tenant_id NOT NULL (Plan 147 Slice A, step 2/4)
Revision ID: 0042
Revises: 0041
Create Date: 2026-07-23
Add-nullable -> backfill every existing station onto the default
``sapphire`` tenant (seeded by 0041) -> NOT NULL. Also adds
``UNIQUE (id, tenant_id)`` — redundant with the PK alone, but is the FK
targe... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0042_stations_tenant_id.py | .py | 528cea6ff0347fd3 | 7 | 0 |
"""station_groups.tenant_id NOT NULL, per-tenant name uniqueness (Plan 147
Slice A, step 3/4)
Revision ID: 0043
Revises: 0042
Create Date: 2026-07-23
Add-nullable -> backfill every existing group onto the default ``sapphire``
tenant -> replace the old GLOBAL ``UNIQUE (name)`` with ``UNIQUE (tenant_id,
name)`` -> NOT ... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0043_station_groups_tenant_id.py | .py | 88719c20a5c9fcb3 | 7 | 0 |
"""station_group_members.tenant_id + composite tenant-match FKs (Plan 147
Slice A, step 4/4)
Revision ID: 0044
Revises: 0043
Create Date: 2026-07-23
The structural, fail-closed invariant: a membership row's SINGLE
``tenant_id`` is bound by TWO composite FKs — ``(station_id, tenant_id) ->
stations(id, tenant_id)`` and... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0044_station_group_members_tenant_id.py | .py | c27bdf4bff6e2471 | 7 | 0 |
"""audit_log role-independent append-only guard (Plan 147 Slice B, 2/2)
Revision ID: 0046
Revises: 0045
Create Date: 2026-07-24
The append-only GUARANTEE, owned here (not by the later DB-roles slice):
a `BEFORE UPDATE OR DELETE` row-level trigger PLUS a `BEFORE TRUNCATE`
statement-level trigger that RAISE uncondition... | hydrosolutions/SAPPHIRE_flow | alembic/versions/0046_audit_log_append_only_guard.py | .py | 682beeab0e4e3aff | 7 | 0 |
"""Add image_url to listings and create emergency_alerts table.
Revision ID: 002_images_alerts
Revises: 001_initial
Create Date: 2024-01-02 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision: str = "002_images_aler... | R0HITHRAO/Townpulse | backend/alembic/versions/002_images_alerts.py | .py | 7ddcc592c6c7de6b | 7 | 0 |
"""
TownPulse Reviews Endpoints
============================
Community citizen reviews and star ratings for local service listings.
"""
import uuid
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import func
from sqlalchemy.orm import Session
from app.core.database import get_db
from app... | R0HITHRAO/Townpulse | backend/app/api/reviews.py | .py | f27169fd4aa4c643 | 7 | 0 |
"""
TownPulse Review Schemas
=========================
Pydantic schemas for review submission, responses, and ratings aggregation.
"""
from datetime import datetime
import uuid
from pydantic import BaseModel, ConfigDict, Field
class ReviewUserSummary(BaseModel):
"""Minimal user details for review attribution."""... | R0HITHRAO/Townpulse | backend/app/schemas/review.py | .py | 6bff0763d4375470 | 7 | 0 |
"""
TownPulse Admin Service
=========================
Administrative logic for viewing platform statistics, managing submissions,
and retrieving moderation queues.
"""
from typing import Any
from sqlalchemy import func
from sqlalchemy.orm import Session
from app.models.claim import Claim, ClaimStatus
from app.models... | R0HITHRAO/Townpulse | backend/app/services/admin_service.py | .py | e5e2667946fbc478 | 7 | 0 |
"""
TownPulse Claim Service
=========================
Handles business owner claim submissions and administrator reviews.
Approving a claim promotes the user to business_owner and sets listing ownership.
"""
import uuid
from datetime import datetime, timezone
from fastapi import HTTPException, status
from sqlalchemy.... | R0HITHRAO/Townpulse | backend/app/services/claim_service.py | .py | 8464bab2ed4dcc9d | 7 | 0 |
"""
TownPulse Listing Service
===========================
Business logic for listing CRUD operations, PostGIS radius queries,
and PostgreSQL full-text search with tsvector.
"""
import uuid
from typing import Any
from geoalchemy2.functions import ST_DWithin, ST_Distance, ST_MakePoint, ST_SetSRID
from sqlalchemy import... | R0HITHRAO/Townpulse | backend/app/services/listing_service.py | .py | c3c8f22aa19fd160 | 7 | 0 |
"""
TownPulse Admin Unit Tests
============================
Tests for admin endpoints, analytics KPIs, and RBAC authorization barriers.
"""
from fastapi.testclient import TestClient
def test_admin_analytics_authorized(client: TestClient, admin_token: str) -> None:
"""Test that admin can view platform analytics."... | R0HITHRAO/Townpulse | backend/tests/test_admin.py | .py | f7173552d30e6aa2 | 7.5 | 0 |
# System Modules
import math
# Installed Modules
# - None
def area_of_circle(radius):
"""Calculate the area of a circle given its radius."""
if radius < 0:
raise ValueError("Radius cannot be negative")
return math.pi * radius ** 2
def get_nth_fibonacci(n):
"""Calculate the nth Fibonacci num... | SattiSaiPavan/skills-test-with-actions | src/calculations.py | .py | 91e7cce73b34586a | 7 | 0 |
"""Build the deprecated optional cross-dataset-overlap condition index.
This artifact is not the native pilot input. It is retained only for an
optional TensorOrbit-to-Alex paired-data or leakage audit. The native pilot
uses ``build_tensororbit_condition_cache.py`` and does not require this
cross-dataset identity join... | future3317/gaugeflow | archive/f_cond_deprecated/scripts/build_f_scalar_condition_index.py | .py | aaa48a5d0adeb581 | 7 | 0 |
"""Prepare, but never start, matched TensorOrbit-JARVIS-v2 oracle training."""
from __future__ import annotations
import argparse
import json
import subprocess
from pathlib import Path
from typing import Any
from gaugeflow.file_utils import sha256_file
ROOT = Path(__file__).resolve().parents[1]
def _resolve(value... | future3317/gaugeflow | archive/f_cond_deprecated/scripts/prepare_v2_oracle_qualification.py | .py | c94d5c6dd98b7c21 | 7 | 0 |
"""Replaceable TensorOrbit transforms and SO(3)-orbit qualification tools.
This module is deliberately outside ``gaugeflow.production``. It provides a
small, explicit contract for the F-Cond qualification work and does not
choose the final production condition representation.
"""
from __future__ import annotations
... | future3317/gaugeflow | archive/f_cond_deprecated/src/gaugeflow/qualification/tensor_orbit.py | .py | 31b79ee92336acdb | 7 | 0 |
# hushtorch.py
"""
Main module for HushTorch application.
"""
import argparse
import logging
import sys
from typing import Optional
class HushTorch:
"""Main class for HushTorch functionality."""
def __init__(self, verbose: bool = False):
"""Initialize with verbosity setting."""
self.verbo... | sannejanhvb/HushTorch | hushtorch.py | .py | ce0990616776d2a5 | 7 | 0 |
# test_hushtorch.py
"""
Tests for HushTorch module.
"""
import unittest
from hushtorch import HushTorch
class TestHushTorch(unittest.TestCase):
"""Test cases for HushTorch class."""
def test_initialization(self):
"""Test class initialization."""
instance = HushTorch()
self.assertI... | sannejanhvb/HushTorch | test_hushtorch.py | .py | 935f033808967010 | 7.5 | 0 |
# -*- coding: utf-8 -*-
"""Horidoro AV — shell helpers.
Thin wrappers over the commands Horidoro orchestrates. All antivirus work
happens inside the `clamav` distrobox; nothing here touches the host OS
beyond reading status.
"""
import re
import subprocess
from branding import CONTAINER_NAME
def run(cmd, capture=T... | CommanderSabi/horidoro-av | horidoro/shell.py | .py | c425c2dccdf7d622 | 7 | 0 |
#!/usr/bin/env python3
"""Horidoro AV — GUI construction smoke test.
Guards the class of bug where a widget-build error crashes the app silently
on launch (a terminal-less "Launch" makes the traceback invisible — exactly
what happened with the Schedule-tab NameError that broke real installs on
both test machines). Con... | CommanderSabi/horidoro-av | tests/test_gui.py | .py | e9606c748717f89c | 7.5 | 0 |
#!/usr/bin/env python3
"""Horidoro AV — bundled sound sanity test.
The four notification clips must be embedded (they ship with everyone),
decode to valid WAV data, and play_sound() must never raise (toggle off,
missing file, missing player -> silent).
Run: python3 tests/test_sounds.py
"""
import base64
import os
im... | CommanderSabi/horidoro-av | tests/test_sounds.py | .py | 114a37ceff07f2de | 7.5 | 0 |
"""暴雨强度公式求值与芝加哥设计雨型生成。
公式库位于 data/rainfall/*.yaml,三种收录形式:
general 总公式: q = A·(1 + C·lgP) / (t + b)^n A 已含 167 换算
interval 区间公式:q = 167·A(P) / (t + b(P))^n(P) A/b/n = p1 + p2·ln(P - p3)
single 单一重现期:q = A / (t + b)^n(校验用)
统一归一为雨力形式:i_avg(t) = a / (t + b)^n [mm/min],累积雨量 H(t) = a·t/(t+b)^n。
单位:q [L/(... | YYer-ai/swmm-copilot | swmm_copilot/design_storm.py | .py | 0e107c3ade014db2 | 7 | 0 |
"""栅格水文分析:填洼、D8 流向、汇流累积、坡度(纯 numpy/heapq,无网络依赖)。"""
from __future__ import annotations
import heapq
import numpy as np
def fill_depressions(dem: np.ndarray) -> np.ndarray:
"""优先级填洼(Barnes 2014 简化版):边界入堆,向内传播,洼地抬升至出口。"""
m, n = dem.shape
filled = np.full_like(dem, np.inf)
visited = np.zeros(dem.shap... | YYer-ai/swmm-copilot | swmm_copilot/hydrology.py | .py | b16492e6defb612e | 7 | 0 |
"""土地覆盖获取与不透水率估算:ESA WorldCover 10m(免认证)。
数据源:ESA WorldCover v200 (2021),AWS 开放数据桶 esa-worldcover(eu-central-1)
https://registry.opendata.aws/esa-worldcover/ (CC-BY 4.0)
获取方式:COG HTTP Range 窗口读取(只传输 bbox 所需数据块,通常 < 1MB),
窗口结果缓存为本地 GeoTIFF,之后完全离线。
瓦片按 3°×3° 分块,命名 N{floor(lat/3)*3:02d}E{floor(lon/3)*3:03d}。
类目:50=建成区... | YYer-ai/swmm-copilot | swmm_copilot/landcover.py | .py | 0165c95472843db2 | 7 | 0 |
"""中文评估报告生成(Markdown):概况、设计降雨、结果、受影响区域分析、声明。"""
from __future__ import annotations
from datetime import datetime
def _sample(flood: list, bbox: list, lon: float, lat: float) -> float:
"""积水场最近邻采样(度 → 网格索引)。"""
h, w = len(flood), len(flood[0])
west, south, east, north = bbox
c = (lon - west) / (east ... | YYer-ai/swmm-copilot | swmm_copilot/report.py | .py | 497cd398d6a48a49 | 7 | 0 |
"""公式库自检:与官方公布的雨量表/单一重现期公式交叉验证。"""
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from swmm_copilot import chicago_hyetograph, intensity, load_db, rain_depth
class TestFormulaLibrary(unittest.TestCase):
@classmethod
def setUpClass(cls):
... | YYer-ai/swmm-copilot | tests/test_design_storm.py | .py | 6fcf9935ca046bb8 | 7.5 | 0 |
"""M4 评估报告测试(TDD:先写失败测试,再实现 swmm_copilot/report.py)。
依赖本地数据缓存(先联网跑过一次 demo),无缓存跳过。
"""
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from swmm_copilot.pipeline import ROOT, assess
from swmm_copilot.report import analyze_impact, generate_docx, gen... | YYer-ai/swmm-copilot | tests/test_report.py | .py | 92440bdac0770afc | 7.5 | 0 |
"""Build a :class:`z4j_core.models.Config` from Flask app config + env vars.
Resolution priority (highest first):
1. ``Z4J_*`` environment variables
2. ``app.config['Z4J_*']`` flat keys (idiomatic Flask)
3. ``app.config['Z4J']`` nested dict (optional)
4. Defaults declared on :class:`z4j_core.models.Config`
Why env v... | z4jdev/z4j-flask | src/z4j_flask/config.py | .py | f8a2dceeef0a0c1d | 7 | 0 |
"""Flask config shim for the declarative scheduler reconciler (1.2.2+).
The reconciler logic lives in ``z4j_bare.declarative`` so all
framework adapters share it. This module is the Flask-specific
glue: it reads ``Z4J_SCHEDULES`` (and optional
``CELERY_BEAT_SCHEDULE`` if ``Z4J_RECONCILE_CELERY_BEAT=True``)
from ``app.... | z4jdev/z4j-flask | src/z4j_flask/declarative.py | .py | 241bf2319a0979f5 | 7 | 0 |
"""Unit tests for ``z4j_flask.config.build_config_from_flask``.
Seeds the ``z4j-flask`` package with its first test suite - until
audit pass 8 (2026-04-21) this adapter had no ``tests`` directory
at all. The bug that drove audit pass 8 (resolver treating
``brain_url=""`` as "not passed" and sliding onto the env
fallba... | z4jdev/z4j-flask | tests/unit/test_build_config.py | .py | a224831d66856218 | 7.5 | 0 |
"""The Flask extension must UNREGISTER the process singleton when the
runtime fails to start, so a later install path can register + start a fresh
runtime instead of reusing the poisoned, never-started one."""
from __future__ import annotations
import secrets
import pytest
from flask import Flask
@pytest.fixture(a... | z4jdev/z4j-flask | tests/unit/test_singleton_cleanup.py | .py | b23438f111003c19 | 7.5 | 0 |
"""Isolated Bulk Acquisition Framework V1 - shared contract vocabulary.
Domain-agnostic acquisition/retention contract: the outcome vocabulary, the
acquisition-specification shape, the raw-document-record schema (see
docs/acquisition_landing_framework.md, "Manifest schema"), and the
qualification-state boundary marker... | tungthanhnguyen2312-wq/stock-core-private | acquisition_landing_contract.py | .py | 7dd1a584c621f4b2 | 7 | 0 |
"""Document identity: logical identity vs content identity.
A document's *logical* identity - "the same thing we asked for" - is
derived only from where it was requested from (domain + source locator).
Its *content* identity is its SHA-256. The two are deliberately different
concepts: the same logical identity can poi... | tungthanhnguyen2312-wq/stock-core-private | acquisition_landing_identity.py | .py | 6d92c71fb6d20afe | 7 | 0 |
"""Fail-closed production-isolation guard.
Every write this framework performs must pass through assert_write_allowed
first. The check is deliberately redundant (both an allow-list check
against the landing root and a deny-list check against protected roots)
so a bug in either half does not by itself open a hole - see... | tungthanhnguyen2312-wq/stock-core-private | acquisition_landing_isolation.py | .py | 6382e868580d5cee | 7 | 0 |
"""Atomic file writing, validation, and promotion helper.
Provides atomic write, replacement, and validation guarantees on Windows and Unix filesystems.
Ensures temporary files are generated in the destination directory, validated prior to replacement,
atomically replaced via os.replace, and cleaned up on failure so e... | tungthanhnguyen2312-wq/stock-core-private | atomic_io.py | .py | 30ba4057f234b076 | 7 | 0 |
"""Deterministic audit/review-opinion classification from already-retained official filings.
WHAT THIS IS
A two-stage, citation-bound classifier over page text already produced by the existing
`pypdf`-based extraction path (`official_document_store.assess_parser_state` /
`official_document_acquisition._ext... | tungthanhnguyen2312-wq/stock-core-private | audit_opinion_evidence.py | .py | cba77fd49c88bcc2 | 7 | 0 |
"""Deterministic, read-only explanation of Pillar A canonical fact conflicts.
This is deliberately a projection over retained canonical facts, not a resolver that chooses
between values. The canonical builder remains the only authority that can establish a fact's
status. In particular, an unresolved period variant o... | tungthanhnguyen2312-wq/stock-core-private | canonical_conflict_decomposition.py | .py | f35c115685c5db4b | 7 | 0 |
"""Versioned, fail-closed mapping of observed VCI cash-flow and capital items."""
from __future__ import annotations
import math
from typing import Any, Mapping, Sequence
VERSION = "1.3.0"
_CORPORATE = {
("cash_flow", "net_cash_inflows_outflows_from_operating_activities"): "operating_cash_flow",
("cash_flow"... | tungthanhnguyen2312-wq/stock-core-private | cash_flow_debt_mapping.py | .py | c1d2469f11ac4da0 | 7 | 0 |
"""Forward-only current snapshots for source-scoped company relationships.
The providers do not expose historical relationship snapshots. This module
therefore stores only responses fetched locally; it never backfills or infers
relationship changes from a missing record.
"""
from __future__ import annotations
impor... | tungthanhnguyen2312-wq/stock-core-private | company_subsidiaries_sync.py | .py | d1cc7118a12f1ea5 | 7 | 0 |
"""EIR-targeted probe placement (L5 — Element Interference Ratio).
Greedy multi-stamp placement to achieve a desired EIR value.
EIR = |{e ∈ E : bbox(e) ∩ S' ≠ ∅}| / |E|
"""
from __future__ import annotations
import math
from typing import List, Tuple
import numpy as np
def is_element_interfered(elemen... | ef1026/ProSA | experiment/eir_targeting.py | .py | ccc7c1a829b20320 | 7.15 | 1 |
"""Extract all paper numbers required by acl_latex2.tex.
Emits both a human-readable stdout report and a machine-readable
``experiment/output/paper_numbers.json`` side-car containing the full
per-pipeline aggregates. The JSON is the canonical source for filling
the ``[TBD_P1]`` placeholders in Sections 5.2--5.5, the a... | ef1026/ProSA | experiment/extract_paper_numbers.py | .py | 64922fe89a6b2d6c | 7.15 | 1 |
from __future__ import annotations
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from queue import Queue
from typing import Any, Optional
import numpy as np
from tqdm import tqdm
def setup_cuda_dll_paths() -> None:
import sys
if sys.platform != "win32":
retu... | ef1026/ProSA | experiment/gpu_pool.py | .py | 3df8b8a454696204 | 7.15 | 1 |
"""Canonical probe and placement identifiers used by the released ProSA code.
The camera-ready paper defines a nine-probe catalog (P1--P9). Earlier
internal Phase-2 logs used P8/P9/P10 for the final three families. The helper
functions below normalize those legacy identifiers by inspecting the parameter
schema, whil... | ef1026/ProSA | experiment/probes/catalog.py | .py | e31022910294ce21 | 7.15 | 1 |
from __future__ import annotations
import cv2
import numpy as np
class SolidVisual:
def __init__(self, color: tuple[int, int, int]):
self.color = tuple(int(c) for c in color)
def render(self, mask: np.ndarray) -> np.ndarray:
h, w = mask.shape[:2]
vis = np.zeros((h, w, 3),... | ef1026/ProSA | experiment/probes/visual.py | .py | a0e435dcafa3873e | 7.15 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.