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 |
|---|---|---|---|---|---|---|
"""MOMUS red-team node + Treasury payer node — topology anchors for Alien Monitor.
Two nodes on purpose. MOMUS finds and signs; the Treasury (its own key, its own container) is the
only thing that can pay. Drawing them as separate orbs with a "pays / separate key" edge is how
the graph makes the "someone else pays" pr... | alexar76/alien-monitor | backend/momus_layers.py | .py | a723d64c3e0dc020 | 7 | 0 |
"""Bearer/service-token and signed browser-session guard for Alien Monitor.
Behaviour:
- Service clients authenticate with the configured Bearer token.
- Browsers exchange that token once for a signed HttpOnly session cookie; unsafe
cookie-authenticated requests additionally require an origin-bound CSRF marker.
- No... | alexar76/alien-monitor | backend/monitor_auth.py | .py | 41de7ff378ed45a3 | 7 | 0 |
"""ASGI middleware: /monitor/api/* → /api/*, /monitor/ws → /ws (standalone :9100)."""
def strip_monitor_prefix(path: str) -> str | None:
if path.startswith("/monitor/api"):
return path[len("/monitor") :] or "/"
if path == "/monitor/ws":
return "/ws"
if path.startswith("/monitor/ws/"):
... | alexar76/alien-monitor | backend/monitor_base_path.py | .py | 3bdc036c36da4b96 | 7 | 0 |
"""Per-node on-chain identity (contract address / wallet + network) for the
NodeDetail card.
Each mode fills `node["onchain"]` with the values that are actually true there:
- LIVE → real Base-mainnet addresses + chain id 8453 + basescan explorer
- UNI → the local Universe Anvil deployment (chain id 31337, no ex... | alexar76/alien-monitor | backend/onchain_refs.py | .py | 1f162b961f9848e8 | 7 | 0 |
"""A short TTL in front of the satellite pollers.
The state tick is 1.5 s (ALIEN_STATE_TICK_SEC) and every rebuild calls every
satellite's `fetch_*_sync`, none of which cached. So each satellite was being asked
roughly 40 times a minute, for numbers that change on its own poll cycle — often
every 5 minutes. It was pur... | alexar76/alien-monitor | backend/poll_cache.py | .py | 401dbec189388777 | 7 | 0 |
"""Settlement node — topology anchor and edges for Alien Monitor.
Placed between the hub and the escrow, because that is literally where it sits: the hub
records what a buyer authorised, a signer turns one such authorisation into one
``debitChannel``, and the escrow is where the result becomes true.
The node is named... | alexar76/alien-monitor | backend/settlement_layers.py | .py | c3e2dec89bb6bdeb | 7 | 0 |
"""ChatDoc FastAPI app.
Run locally with:
uv run uvicorn api.app:app --reload --port 8000
"""
from __future__ import annotations
import logging
import os
import threading
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from api.routes_au... | n1khil01/ChatDoc | api/app.py | .py | 95e2a970f9f87eb1 | 7 | 0 |
"""Argon2 password hashing + HttpOnly cookie session management.
Sessions are opaque random tokens stored in Postgres (`sessions` table), not signed
JWTs -- a DB-backed session can be revoked immediately (logout, breach response) and
its expiry can slide on activity, which is required so a live SSE generation cannot
o... | n1khil01/ChatDoc | api/auth.py | .py | a88397636a9a455d | 7 | 0 |
"""Double-submit-cookie CSRF protection for mutating routes.
The cookie session alone is not enough: a browser will attach it automatically to a
cross-site form POST. A second value that only a legitimate client can produce must be
echoed back in a header, which a cross-site attacker cannot do.
The classic version of... | n1khil01/ChatDoc | api/csrf.py | .py | 454520e826a697c1 | 7 | 0 |
"""Crash-safe ingest job queue: enqueue, claim, complete/fail (PROJECT_PLAN.md §7 Phase 4).
`claim_job` is the only place concurrency matters. It runs `FOR UPDATE SKIP LOCKED` inside
a transaction that also flips the row to 'processing' and pushes `visible_at` forward, so
the row is unavailable to any other claimant -... | n1khil01/ChatDoc | api/jobs_repo.py | .py | 9080e8b04c2058b6 | 7 | 0 |
"""PDF blob storage: local disk in dev, Cloudflare R2 (S3-compatible) in production
(PROJECT_PLAN.md §5 "Blob storage" -- Render's free tier has no persistent disk, so an
uploaded PDF written to local disk is gone the moment the container spins down or restarts,
which for a free-tier box spinning down after 15 minutes ... | n1khil01/ChatDoc | api/storage.py | .py | 63aee5f4a2a84091 | 7 | 0 |
"""Standalone ingest worker process (PROJECT_PLAN.md §7 Phase 4).
Run as its own process/container, separate from the FastAPI web process:
uv run python -m api.worker
Polls `jobs` for claimable work (see api/jobs_repo.py's `claim_job` for the SKIP LOCKED
query), runs the Phase 1 ingestion pipeline, and marks the... | n1khil01/ChatDoc | api/worker.py | .py | e4ea1b14550f3501 | 7 | 0 |
"""Build the four-tier negative taxonomy (PROJECT_PLAN.md §7 Phase 0, step 2).
Zero API calls. Built only over the numeric-gradable split (eval/data/answerable.jsonl)
because the leak check needs a single gold figure to search for.
N1 — same-document evidence ablation (60%): correct filing, evidence page(s) remov... | n1khil01/ChatDoc | eval/build_negatives.py | .py | 7e07d22e69514fe4 | 7 | 0 |
"""The grounding gate: L1 (retrieval confidence, experimental) / L2 (schema sufficiency +
citation validation) / L3a (numeric + operand provenance) / L3b (prose claim support).
PROJECT_PLAN.md §7 Phase 2.
Every function here is a pure check over an already-parsed eval.gate_schema.GateAnswer plus
retrieval context capt... | n1khil01/ChatDoc | eval/gate.py | .py | 81d2b721e68f1474 | 7 | 0 |
"""Structured-output schema for the grounding gate (PROJECT_PLAN.md §7 Phase 2, step 1).
The model must fill `sufficient` and `operands` as typed fields, not phrases a parser hopes
to find. Derived answers (growth rates, ratios) are verified through their `operands` rather
than the final `value`, per the plan -- arith... | n1khil01/ChatDoc | eval/gate_schema.py | .py | 3affabbf4d112677 | 7 | 0 |
"""Thin wrapper around google-genai that converts a real 429 (with its actual
Retry-After) into eval.quota_guard.RateLimited, per PROJECT_PLAN.md §9 Challenge 3:
"read the actual 429 response and Retry-After header instead of trusting the SDK's
default retry policy."
"""
from __future__ import annotations
import json... | n1khil01/ChatDoc | eval/gemini_client.py | .py | d8f214693b57384f | 7 | 0 |
"""Numeric normalization shared by dataset classification and grading.
FinanceBench gold answers are free text ("$1,577.00", "1577", "$1.577 billion", "12.3%").
This is the one normalizer both `build_dataset.py` (classification) and the future
grader (`runner.py`) must use, so a number is graded the same way it was cl... | n1khil01/ChatDoc | eval/normalize.py | .py | 3b9e570c88373d6e | 7 | 0 |
"""Prompt template for the Phase 2 grounding-gate runner (PROJECT_PLAN.md §7 Phase 2 step 5).
Excerpts are wrapped in explicit <excerpt id="..."> delimiters and the prompt states plainly
that excerpt content is data to read, never instructions to follow. This is the prompt-side
half of the prompt-injection defense; ci... | n1khil01/ChatDoc | eval/prompt.py | .py | 1b5017638d8020f1 | 7 | 0 |
"""Client-side quota guard for the Gemini free tier (PROJECT_PLAN.md §7 Phase 0 step 5;
§8 Cost control; §9 Challenge 3).
Google cut the 2.5-flash free-tier daily request cap in December 2025 and no longer
publishes the number. Treat it as a runtime input, never a constant:
- `daily_budget` must be passed in explic... | n1khil01/ChatDoc | eval/quota_guard.py | .py | 99eb8824f8a60360 | 7 | 0 |
"""Phase 2 resumable eval runner -- retrieval via the Phase 1 hybrid pipeline, generation via
schema-constrained Gemini structured output (PROJECT_PLAN.md §7 Phase 2).
Unlike eval/runner.py (the naive Phase 0 baseline), this runner does NOT decide pass/fail --
it only produces and caches raw GateAnswer generations plu... | n1khil01/ChatDoc | eval/runner_v2.py | .py | ea9fddf5262ca56b | 7 | 0 |
"""Table-aware, page-anchored PDF chunking (PROJECT_PLAN.md §7 Phase 1).
Two chunk types come out of every page:
* "table" -- one atomic chunk per PyMuPDF-detected table, serialized to Markdown,
never split across chunks, with scale/unit metadata sniffed from
nearby footnote text and t... | n1khil01/ChatDoc | ingest/chunker.py | .py | f2ac46bdacffcac0 | 7 | 0 |
"""Postgres connection + insert/query helpers for the chunks table.
Reads DATABASE_URL from the environment (.env), pointed at the local docker-compose
pgvector instance in Phase 1; unchanged code path once this moves to Neon.
"""
from __future__ import annotations
import os
from contextlib import contextmanager
fro... | n1khil01/ChatDoc | ingest/db.py | .py | 51e3524730348d59 | 7 | 0 |
"""int8 ONNX bge-small-en-v1.5 embeddings via fastembed, CPU, single-threaded.
`intra_op_num_threads=1` per PROJECT_PLAN.md §7 Phase 1 memory rationale: this runs on a
memory-constrained box, so we trade thread parallelism for a predictable, small footprint
rather than importing torch (which alone costs ~250-350MB RSS... | n1khil01/ChatDoc | ingest/embeddings.py | .py | 78439ef0bf42b5b1 | 7 | 0 |
"""Ingest a single FinanceBench PDF into Postgres: table-aware chunking -> embeddings -> insert.
Usage (library):
from ingest.pipeline import ingest_pdf
document_id = ingest_pdf(conn, pdf_path, excluded_pages=frozenset())
"""
from __future__ import annotations
import time
from collections.abc import Callable... | n1khil01/ChatDoc | ingest/pipeline.py | .py | f4ba1b4c27659eb9 | 7 | 0 |
"""Cross-encoder rerank: cross-encoder/ms-marco-MiniLM-L6-v2, ONNX, CPU.
PROJECT_PLAN.md §5: bge-reranker-base is ~1.1GB fp32 and does not fit; MiniLM-L6 (22.7M params,
~25MB quantized) ships a pre-exported ONNX checkpoint and makes the same "cross-encoder
reranking" claim on hardware this project actually runs on.
f... | n1khil01/ChatDoc | ingest/reranker.py | .py | d72cfe18162c9d4a | 7 | 0 |
"""Hybrid retrieval: pgvector halfvec HNSW (dense, cosine) + tsvector/tsquery (sparse),
fused with Reciprocal Rank Fusion, then reranked with a MiniLM cross-encoder.
RRF: score(d) = sum over rankers of 1 / (k + rank_in_that_ranker), k=60 (standard default,
Cormack et al. 2009 -- no dataset-specific tuning justifies de... | n1khil01/ChatDoc | ingest/retrieval.py | .py | b5d6c6bdc431994b | 7 | 0 |
"""Crash-safety proof for the ingest queue (PROJECT_PLAN.md §7 Phase 4, §6 metric
"Ingest job loss rate under spin-down").
Enqueues a real ingest job, starts `api.worker` as its own OS process, SIGKILLs it mid-job
(simulating Render spin-down / OOM), and asserts the job is *not* lost: a second worker
started afterward... | n1khil01/ChatDoc | scripts/kill_worker_test.py | .py | 7493e37811753942 | 7.5 | 0 |
"""Live-deployment crash-recovery proof (PROJECT_PLAN.md §7 Phase 4, §6 metric "Ingest job
loss rate under spin-down") -- the counterpart to scripts/kill_worker_test.py that runs
against the actual deployed Render service instead of a local process/container.
Local (kill_worker_test.py, and the Docker container-kill p... | n1khil01/ChatDoc | scripts/live_recovery_test.py | .py | a26a35f50ecc53b1 | 7.5 | 0 |
"""
T32: Chaos-order completeness benchmark.
Compute C(f) = D_f / D_d for elementary benchmarks to establish
the full range of the chaos index.
"""
import numpy as np, math
def gap_D(vals):
gaps = [abs(vals[i+1] - vals[i]) for i in range(len(vals)-1)]
mg, vg = float(np.mean(gaps)), float(np.var(gaps))
retu... | Puronbo/Law-Of-Repulsive-Emanation | Universals/chaos_order_benchmark.py | .py | 50e93678171239bb | 7.24 | 2 |
"""
Composite distribution analysis on the natural numbers up to N.
Three patterns, all direct sieve consequences:
1. Last-digit distribution — composites ending in 0,2,4,5,6,8 are saturated
(multiples of 2 or 5); 1,3,7,9 are rarer (compete with primes).
2. Smallest-prime-factor (SPF) decay — fraction whose smalles... | Puronbo/Law-Of-Repulsive-Emanation | Universals/composite_analyzer.py | .py | b23e2e2aac572b92 | 7.24 | 2 |
"""
continuous_spectrum.py
======================
Parameterize d_t(n) = Π_p (a_p + 1)^t and show C(t) monotonic.
Map Mersenne families onto the continuous t-scale.
"""
import math, json, numpy as np
N = 100
def factorise(n):
if n == 1: return {}
d, pf, p = n, {}, 2
while p * p <= d:
while d % p =... | Puronbo/Law-Of-Repulsive-Emanation | Universals/continuous_spectrum.py | .py | 1e9b98bcc5060626 | 7.74 | 2 |
"""
energy_landscape.py
===================
Analyze the energy landscape V(q) on the Poincare disk.
The repulsion potential V(q) defines a gradient flow on the Poincare disk.
The origin is an unstable fixed point (source), the boundary is an
attractor (sink). Morse theory connects the topology of sublevel sets
to the ... | Puronbo/Law-Of-Repulsive-Emanation | Universals/energy_landscape.py | .py | 99c91da20500eabe | 7.24 | 2 |
"""
Two-constraint inverse solver for the C0 law.
Given two distinct contexts and a candidate C0 value, use Newton's
method to solve for the unique q0 such that V(q0; context_i) = C0
for both contexts simultaneously.
This fixes the inverse problem (Section 8.1 / Item 10 in the audit):
a single V(q) = C0 constraint gi... | Puronbo/Law-Of-Repulsive-Emanation | Universals/inverse_solver.py | .py | 8d1868d778e10c39 | 7.24 | 2 |
"""
C0 Hamiltonian flow on the Poincare disk (numpy).
The C0 energy potential V = sum_{i<j} 1/|x_i - x_j| drives a repulsive
interaction between concept points. Hamiltonian dynamics on the disk
with leapfrog integration separate concept positions while friction
lets the system settle.
The flow operates at the CONCEPT... | Puronbo/Law-Of-Repulsive-Emanation | Universals/manifold/c0_flow.py | .py | 119eb88aae6724b7 | 7.24 | 2 |
"""
Poincare disk geometry, implemented with PyTorch so that gradients are
computed by autograd instead of hand-rolled finite differences.
Provides the geometric primitives for the Puno Calculus:
- geodesic_distance: exact hyperbolic distance
- project_to_disk: clamp to unit disk
- riemannian_scale: conformal fa... | Puronbo/Law-Of-Repulsive-Emanation | Universals/manifold/poincare.py | .py | 47c70455d0f58dbe | 7.24 | 2 |
"""
Polysphere routing manifold.
Each face of a spherical polyhedron carries its own truth function.
Points on the sphere route outward through the face whose truth best matches.
"""
from __future__ import annotations
import numpy as np
from scipy.spatial.distance import cdist
# --- sphere utilities ---
def fibon... | Puronbo/Law-Of-Repulsive-Emanation | Universals/manifold/polysphere.py | .py | 67c790317febd84b | 7.24 | 2 |
"""
noether_analysis.py
===================
Verify Noether's theorem: C0 = H(q0, 0) is the conserved charge under
time-translation symmetry of the Hamiltonian.
NOTE: This is the same fact as the C0 law and the "shifted Wheeler-DeWitt
constraint" — all three are energy conservation for a time-independent
Hamiltonian. T... | Puronbo/Law-Of-Repulsive-Emanation | Universals/noether_analysis.py | .py | 599775c8d8ef6367 | 7.24 | 2 |
"""
prime_analysis.py
=================
Integrate prime numbers into the L.O.R.E. framework.
Connections:
- Prime-indexed steps in Hamiltonian trajectories
- Prime geodesic distances (hyperbolic analogue of prime numbers)
- Recurrence time prime factorization
- C0 law verified at every prime step
"""
import n... | Puronbo/Law-Of-Repulsive-Emanation | Universals/prime_analysis.py | .py | bf3b233812b4ce08 | 7.24 | 2 |
"""
Segmented Sieve Benchmark — T31 PNT Window Verification
Verifies Li(x) prediction against actual prime counts in
2e6-wide windows from 1e6 to 1e15, using O(sqrt(x)) memory.
"""
import math, time, numpy as np
WINDOW = 2_000_000
def segmented_primes_in_window(start, n_primes_seeds):
"""Count primes in [start, ... | Puronbo/Law-Of-Repulsive-Emanation | Universals/segmented_sieve_benchmark.py | .py | f9745cbf35abbee9 | 7.24 | 2 |
#!/usr/bin/env python3
"""
serve_dashboard.py
==================
Start a local HTTP server for the L.O.R.E. dashboard.
Opens http://localhost:8080/docs/ in your default browser.
Serving layout:
/ -> 302 redirect to /docs/ (the dashboard)
/docs/ -> docs/index.html (the dashboard UI)
/docs/* ... | Puronbo/Law-Of-Repulsive-Emanation | Universals/serve_dashboard.py | .py | a01a09518f8a05bb | 7.24 | 2 |
"""
spectrum_extended.py
====================
Extend the chaos spectrum with σ(n) (sum of divisors) and φ(n) (Euler totient).
Compute D and C(f) = D_f / D_d for all functions.
"""
import math, json, numpy as np
N = 100
def factorise(n):
if n == 1: return {}
d, pf, p = n, {}, 2
while p * p <= d:
w... | Puronbo/Law-Of-Repulsive-Emanation | Universals/spectrum_extended.py | .py | 870ca4ecd4606c95 | 7.74 | 2 |
#!/usr/bin/env python3
"""Generate PDF for Toomre-Millennium paper."""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'sigma_venv'))
from fpdf import FPDF
class ToomreMillenniumPDF(FPDF):
def header(self):
self.set_font('Helvetica', 'I', 8)
self.c... | Puronbo/Law-Of-Repulsive-Emanation | _gen_toomre_mill_pdf.py | .py | f553597b8f0955d2 | 7.24 | 2 |
#!/usr/bin/env python3
"""
修复 Latest.mvsv 及归档文件中 Date/Time 列相关数据问题
检测并修复:
1. 混合列宽:同一文件中 6 列与 8 列行混排(缺失 Date/Time)
2. 异常列宽:列数不在 {6, 8} 范围内(如之前 bug 产生的 10 列)
3. 元数据与数据列数不一致
修复策略:
- 6 列 → 从 ts 按北京时间(Date/Time)补全为 8 列
- 异常列宽 → 截取前 2 列(ts,Date,Time) + 后 5 列(c,v,t,r,cp) = 8 列
- 更新 #字段 / #字段名称 / #字段类型 元数据
用法:
... | ACANX/Distribution | Python/Quote/FixLatestDateCols.py | .py | 8ba774f1695f2143 | 7.74 | 2 |
#!/usr/bin/env python3
"""Task 4: Archive SecuQuoteExecLog json files into a single daily .jsonl file
- 读取 Data/Finv/SecuQuoteExecLog 下生成的 json 文件(每个文件一个 JSON 对象)
- 将全部数据汇总、去重(唯一键: ts + selected_code)并按时间顺序排列
- 合并导出为一个 jsonl:Archive/Finv/SecuQuoteExecLog/{yyyyMMdd}.jsonl(每行一条记录)
- 文件名日期严格按北京时间处理(运行当天 BJT 日期)
- 目标文件已存在... | ACANX/Distribution | Python/Quote/Task04ArchiveSecuQuoteExecLogDaily.py | .py | 02c6df03f6e0fd7b | 7.24 | 2 |
"""
配置加载模块
优先级: Config.yaml < 环境变量
相对路径以 git 仓库根为参考点
"""
import os
import subprocess
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List
import yaml
@dataclass
class Config:
"""全局配置"""
repo_root: Path
data_dir: Path # 原始采集数据根目录
archive_dir: ... | ACANX/Distribution | Python/Quote/common/config.py | .py | 412271795fc4f6f7 | 7.24 | 2 |
"""
Git 操作封装
使用 subprocess,支持 add/commit/rm/push,含 push_with_retry 增量发布。
"""
import os
import subprocess
from pathlib import Path
from typing import List, Optional
_git_dir: Optional[str] = None
def _run(args: List[str], cwd: Optional[str] = None) -> subprocess.CompletedProcess:
"""Run git command and return ... | ACANX/Distribution | Python/Quote/common/gitutil.py | .py | 431b0387201e7424 | 7.24 | 2 |
"""
中文结构化日志模块
格式: [ISO8601][LEVEL][task][code] 消息
输出: stdout + 文件 (Python/Quote/logs/{task}_{yyyymmdd}.log)
"""
import logging
import os
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Optional
BJT = timezone(timedelta(hours=8))
class QuoteFormatter(logging... | ACANX/Distribution | Python/Quote/common/logger.py | .py | 5ed93f55fc292fb2 | 7.24 | 2 |
"""
Fleet Pattern Agent
======================
Looks for recurring signals across vessels (near-misses, incident reports)
that individually look minor but together indicate an emerging fleet-wide
issue. This is the "one vessel's experience protects the fleet" capability.
"""
from collections import Counter
from core.d... | serinalapoez/Manrova | agents/fleet_pattern/agent.py | .py | 82de3196434c910f | 7 | 0 |
"""
Nav Integrity Agent
=====================
Detects GPS/radar/gyro/speed inconsistencies. Safety-critical math is
deterministic; only the interpretation step is agentic.
"""
import math
from core.domain.models import AgentEvent, Severity, new_id
def _haversine_meters(p1: tuple, p2: tuple) -> float:
lat1, lon1 ... | serinalapoez/Manrova | agents/nav_integrity/agent.py | .py | 41dfd74aef239224 | 7 | 0 |
"""
Agent Gateway
===============
Unified routing and policy enforcement point, per the Fortified Enterprise
Fleet track requirement. Every tool call any agent makes passes through
here first - this is the single place that checks an agent is calling only
what it's permitted to (per the Agent Registry's `permissions` f... | serinalapoez/Manrova | enterprise/gateway/gateway.py | .py | 887d8ef9c2fe613d | 7 | 0 |
"""
Memory Bank
=============
Persistent, secure cross-session context for the Fortified Enterprise Fleet
track. Backed by Cloud Firestore (Firebase Spark plan - genuinely free, no
billing account required, distinct from Cloud Run/Compute which do need
billing). Every investigation the OOW completes is written here, so... | serinalapoez/Manrova | enterprise/memory/firestore_bank.py | .py | 4cf35e3f3e9a3f5f | 7 | 0 |
"""
Agent Observability
======================
OpenTelemetry-compliant audit logs and end-to-end reasoning-chain traces,
per the Fortified Enterprise Fleet track requirement. Wraps an investigation
run in a trace span, with each specialist consultation and the final risk
fusion as child spans - the same shape you'd see... | serinalapoez/Manrova | enterprise/observability/observability.py | .py | c39a99b6515d1a32 | 7 | 0 |
"""
Tenancy
=========
Genuine multi-tenant data isolation: any shipping company can register,
add their own vessels (real or anonymized/coded names - a company may not
want to disclose a real hull name), and run investigations on their own
real data. Backed by Firestore, same free Spark plan as the Memory Bank
and Agen... | serinalapoez/Manrova | enterprise/tenancy/tenancy.py | .py | 90dbffe148a9d504 | 7 | 0 |
"""
Strands Agents
================
Wires the deterministic core into a Strands multi-agent system using the
"agents as tools" pattern: each specialist is its own Strands Agent with one
tool, then wrapped as a @tool the Officer of the Watch agent can call. This
mirrors providers/google/adk/agents.py's sub_agents compos... | serinalapoez/Manrova | providers/aws/strands/agents.py | .py | f205df2f0c9e422b | 7 | 0 |
"""
Strands Tools
==============
@tool-decorated functions Strands agents call directly. Each wraps a
deterministic core agent (core/, agents/) - the LLM never computes distances,
fatigue scores, or compliance risk itself, only calls these and narrates
the result. Identical responsibility split to providers/google/adk/... | serinalapoez/Manrova | providers/aws/strands/tools.py | .py | 98945c58254fb1c8 | 7 | 0 |
"""
Fallback Gemini Model
========================
Wraps ADK's Gemini model to automatically retry against a different Gemini
model when the current one is unavailable - overloaded, rate-limited,
deprecated, or over quota. Google retires/renames Gemini models fairly
often and free-tier quota is per-model, so trying sev... | serinalapoez/Manrova | providers/google/adk/fallback_model.py | .py | 5a85f0622b609dd3 | 7 | 0 |
"""Visium → Hist2ST-format tensors (patches, grid positions, adj, log1p labels)."""
from __future__ import annotations
import sys
from pathlib import Path
import cv2
import numpy as np
import pandas as pd
import torch
SCRIPT_DIR = Path(__file__).resolve().parent
HIST2ST_DIR = SCRIPT_DIR.parent / "hist2st"
sys.path.... | dingzetao/BEACON | benchmark/beacon_vs_hist2st/dataset_visium.py | .py | 558318e34c76dcfc | 7.15 | 1 |
"""CTransPath factory (Wang et al. / Path2Space).
Prefer the bundled SwinTransformer (matches Zenodo ctranspath.pth key layout).
Fall back to timm only if needed (newer timm requires ConvStem **kwargs + BHWC).
"""
from __future__ import annotations
from itertools import repeat
import collections.abc
from torch impo... | dingzetao/BEACON | benchmark/beacon_vs_path2space/ctrans/ctranspath.py | .py | dacb6e3d53c702b4 | 7.15 | 1 |
"""Path2Space-B models: frozen CTransPath encoder + MLP abundance head."""
from __future__ import annotations
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
class AbundanceMLP(nn.Module):
"""Path2Space-style MLP regressor (no graph). Output is non-negative on log1p ... | dingzetao/BEACON | benchmark/beacon_vs_path2space/models.py | .py | 535191a9f035bea3 | 7.15 | 1 |
"""UNI+MLP abundance head (no graph) — ablation vs BEACON GAT."""
from __future__ import annotations
import torch
import torch.nn as nn
class UniAbundanceMLP(nn.Module):
"""
Spot-wise MLP on frozen UNI 1024-d features.
Mirrors BEACON's post-GAT MLP capacity (128 → 32 → 1) with a linear
projection f... | dingzetao/BEACON | benchmark/beacon_vs_uni_mlp/models.py | .py | 76febd992ef3f382 | 7.15 | 1 |
import torch.nn as nn
import torch.nn.functional as F
class GraspModel(nn.Module):
"""
An abstract model for grasp network in a common format.
"""
def __init__(self):
super(GraspModel, self).__init__()
def forward(self, x_in):
raise NotImplementedError()
def compute_loss(sel... | Abnerzyr/agx_arm_ros-ros2 | src/agx_arm_vision/agx_arm_vision/models/grasp_model.py | .py | daf687ffaa19340d | 7 | 0 |
"""Full TQBR backfill via MOEX ISS (1927 tickers, ~5y daily OHLCV).
This script backfills the COMPLETE TQBR universe from MOEX ISS REST:
- Live + delisted + archived tickers (any STATUS: N, D, X, etc.)
- ~5 years of daily OHLCV (or whatever ISS retains)
- Classifies tickers into source='moex', class_code='TQBR'
Hones... | m0rtal/alphard | scripts/backfill_full_universe.py | .py | 87dc8fa46c411d75 | 7.15 | 1 |
"""Daily PostgreSQL backup script (Phase 2.9 step 1).
Why pg_dump (not filesystem copy)?
- A filesystem copy of /var/lib/postgresql/data is inconsistent unless
Postgres is shut down. pg_dump is the official, online-safe way to
snapshot a Postgres database.
- The output is a single SQL file that's portable to any P... | m0rtal/alphard | scripts/backup_database.py | .py | 50a680a84721e8a0 | 7.15 | 1 |
"""MOEX ISS corporate-actions fetcher (Phase 2.5 step 2a).
Why this script?
----------------
PHASE1-AUDIT flagged "Adjusted prices — adj_close = close placeholder, no
split/dividend adjustment". Phase 2.5 ships:
- Step 1 (PR #45): pure adjustment math (`src.data.adjustment`).
- Step 2a (this script): fetch raw co... | m0rtal/alphard | scripts/fetch_moex_corporate_actions.py | .py | b5405fe2b3e3d9fa | 7.15 | 1 |
"""Mark tickers that have failed backfill N consecutive times as delisted.
This implements the documented Phase 1 fix:
> **delisted_at** sync invoked from cron (PHASE1-AUDIT gap #7)
> Treats no-data tickers as known-unrecoverable rather than retrying forever.
Heuristic (deterministic, conservative):
1. backfill_com... | m0rtal/alphard | scripts/mark_terminally_failed.py | .py | 5fb12aac607950f5 | 7.15 | 1 |
#!/usr/bin/env python3
"""Replay a single sizing decision from the audit log.
Usage:
scripts/replay_sizing.py <audit_log.jsonl> <ts>
scripts/replay_sizing.py <audit_log.jsonl> --ticker SBER
scripts/replay_sizing.py <audit_log.jsonl> --all
What it does
------------
Reads the audit log (JSONL — one line per... | m0rtal/alphard | scripts/replay_sizing.py | .py | ef052b3b5d33093a | 7.15 | 1 |
#!/usr/bin/env python3
"""Macro sync: pull CBR + USD/RUB + IMOEX, classify regime, upsert to Postgres.
Phase 2.3 Macro Agent. Idempotent: re-running within the cache TTL window
is a no-op for the network call but always re-classifies and upserts.
The script mirrors ``daily_sync.py`` and ``apply_corporate_actions.py``... | m0rtal/alphard | scripts/run_macro_sync.py | .py | 061f60dd7b502201 | 7.15 | 1 |
"""BrokerAccount ABC — interface for any broker implementation.
All concrete brokers (Tinkoff, BCS, Finam) implement this interface.
The interface is intentionally narrow — only methods that need broker
round-trip live here. Local computation belongs to other agents.
"""
from __future__ import annotations
from abc i... | m0rtal/alphard | src/broker/account.py | .py | b0d594c549782d78 | 7.15 | 1 |
"""OrderSlicer — split orders into 5% ADV chunks.
Tinkoff API doesn't support TWAP/VWAP/iceberg natively. This module
implements custom slicing: for large orders, split into 5%-of-ADV
chunks, max 30 minutes total, with rate-limit TokenBucket.
Use: OrderSlicer.slice(intent, adv_shares, risk_limits) -> list[slice_batch... | m0rtal/alphard | src/broker/slicer.py | .py | e186de4924a4f0e4 | 7.15 | 1 |
"""Split and dividend adjustments for OHLCV bars.
Why this module?
---------------- Phase 1.1 stores both ``close`` (raw exchange close) and
``adj_close`` (split-adjusted close) on every OHLCV bar. Phase 1.1 ships
the schema but ``adj_close = close`` is a placeholder — there is no
corporate-action processing yet. Phas... | m0rtal/alphard | src/data/adjustment.py | .py | 15c5c4f45dcd2639 | 7.15 | 1 |
"""AdvProvider — Average Daily Volume source for OrderFlow (issue #230).
Pre-#230 ``OrderFlow.submit_market`` built the OrderSlicer's ``adv_shares``
as ``max(qty * 20, 100)`` — a hardcoded placeholder unrelated to real
ADV — which made the slicer's 5%-ADV-chunk policy collapse to exactly
one chunk for every realistic ... | m0rtal/alphard | src/data/adv_provider.py | .py | 2bcb069a07aa4b14 | 7.15 | 1 |
"""Sync delisted_at for the ticker universe via MOEX ISS reference data.
Why
---
``ticker_universe.delisted_at`` is the boundary date for the backfill
age-aware completion formula: ``expected_bars =
trading_days(listed_at, today|delisted_at) * (1 - halts_pct)``. Without
a real delisted_at the formula can't tell a 2018... | m0rtal/alphard | src/data/delist_source.py | .py | 4198ee9e350cb2d8 | 7.15 | 1 |
"""Shared pydantic models for the Data Agent.
Why central models?
-------------------
Both ``DataLoader`` (network side) and ``DataStore`` (DB side) speak the
same wire types. Putting them in one module prevents drift between the
two contracts — if we ever evolve the schema, this file is the single
point of edit.
Why... | m0rtal/alphard | src/data/models.py | .py | d5274f173667cb4d | 7.15 | 1 |
"""Pydantic models for the Macro Agent (Phase 2.3).
Why frozen?
- The fetcher builds a snapshot, the classifier consumes it, the
persistence layer writes it. We don't want a downstream function
silently mutating the input and producing a regime label that doesn't
match what was fetched.
- Mirrors the project's `... | m0rtal/alphard | src/macro/models.py | .py | 5fb64fa88ff0f304 | 7.15 | 1 |
"""Contract-shaped error models for Q-Trace API.
Matches the shared error shape in board/contracts/circuit-simulation.md:
{ "error": { "code": str, "message": str, "requestId": str, "details": dict | None } }
"""
from __future__ import annotations
from typing import Any
from pydantic import BaseModel
class Erro... | vinodkrishna221/Q-Trace | apps/api/app/models/errors.py | .py | 9590d87e91ec6958 | 7 | 0 |
"""Repository module and dependency injection selectors for Q-Trace."""
from typing import Optional
from app.repositories.base import DataRepositoryProtocol
from app.repositories.memory import InMemoryRepository
_default_repository: Optional[DataRepositoryProtocol] = None
def get_repository() -> DataRepositoryProto... | vinodkrishna221/Q-Trace | apps/api/app/repositories/__init__.py | .py | 08aadc29af463953 | 7 | 0 |
"""Base repository protocols for Q-Trace data analytics and persistence."""
from typing import Optional, Protocol, runtime_checkable
from app.models.entities import (
Challenge,
ChallengeAttempt,
CircuitModel,
InstructorInsight,
InstructorProfile,
LearnerProfile,
LearningPath,
Misconcep... | vinodkrishna221/Q-Trace | apps/api/app/repositories/base.py | .py | dd0d1bafde408fc8 | 7 | 0 |
"""Basis-order normalization for Qiskit → contract label mapping.
Qiskit Aer statevectors use LITTLE-ENDIAN wire order:
- The rightmost character of the basis string = qubit 0 (LSB)
- e.g., for 2 qubits, Qiskit index 1 (binary "01") means q0=1, q1=0
The contract uses BIG-ENDIAN labels (qubit 0 = MSB / leftmost ch... | vinodkrishna221/Q-Trace | apps/api/app/services/quantum/normalizer.py | .py | a934c7ad268ea724 | 7 | 0 |
"""Unit tests for InMemoryRepository and repository protocols."""
import pytest
from app.models.entities import (
Challenge,
ChallengeAttempt,
CircuitModel,
GateName,
InstructorProfile,
LearnerProfile,
LearningPath,
MisconceptionSignal,
Module,
Operation,
PredictionCheckpoin... | vinodkrishna221/Q-Trace | apps/api/tests/unit/data/test_memory_repository.py | .py | dc570e7a5d55d2ba | 7.5 | 0 |
#!/usr/bin/env python3
"""
SHIP-3 · check_story_claims.py
Verifies docs/DEMO-SCRIPT.md satisfies the SHIP-3 card test:
1. Every number claim has a source URL in the Sourced Evidence Ledger.
2. The 90-second script includes all eight learner beat tags (B1–B8).
3. A FALLBACK CUE is explicitly scripted.
Exit 0 = al... | vinodkrishna221/Q-Trace | scripts/check_story_claims.py | .py | 1a7856382e6aef74 | 7 | 0 |
"""trend 렌더러 — 시간 추이 (라인).
정적 주제(survey_year 컬럼)는 연도별 추이로, 실시간 주제(snapshot_time 등)는
config["x_axis_column"] 기준 시점별 추이로 그린다. 보조 축(region_type / gender /
device_type)이 있으면 계열로 분리해 격차를 보여준다.
"""
import plotly.graph_objects as go
from ..theme import ACCENT, SERIES_2
SERIES_CANDIDATES = ("region_type", "gender", "device... | devleeeasy/insight-dashboard-hub | dashboard/renderers/trend.py | .py | 02e89bd0a0072a3c | 7 | 0 |
"""
FastAPI 서빙 계층
GET /dashboards -> 등록된(is_active=TRUE) 대시보드 메타데이터 목록
GET /dashboards/{id}/data -> 해당 대시보드의 data_source_table 데이터 (선택적 세그먼트 필터)
대시보드 허브(Streamlit)는 이 API를 통해서만 데이터를 가져오며, 새로운 주제가
dashboard_registry에 추가되어도 이 파일은 수정할 필요가 없다.
실행:
uvicorn src.api.main:app --reload
"""
import logging... | devleeeasy/insight-dashboard-hub | src/api/main.py | .py | 15dcc5d8c9a6641b | 7 | 0 |
"""
실시간 상권 유동인구 수집기 - 서울시 실시간 도시데이터 API
흐름:
장소별로 순차 호출 (API가 한 번에 장소 1곳만 조회 가능)
→ 실패 시 지수 백오프 재시도, 최대 횟수 넘으면 로그 남기고 다음 장소로
(한 장소 실패가 전체 수집을 죽이지 않음)
→ 원본 XML 응답을 S3 raw에 그대로 저장 (원본 불변 원칙, 감사/재현용)
→ 파싱한 결과를 MySQL foot_traffic_timeseries 에 upsert
(place_id+snapshot_time 기준, 재수집해도 중복 안 쌓임)
실행:
... | devleeeasy/insight-dashboard-hub | src/collectors/foot_traffic/collect.py | .py | 8e4be42b073f7375 | 7 | 0 |
"""
MySQL 스키마 생성 스크립트
dashboard_registry, segment_dim, household_spending_agg, media_usage_agg,
foot_traffic_timeseries, foot_traffic_places 테이블을 생성한다.
이미 존재하면 건드리지 않는다(CREATE TABLE IF NOT EXISTS).
실행:
python -m src.db.init_db
환경변수 (.env, .env.example 참고):
MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWORD, MYSQ... | devleeeasy/insight-dashboard-hub | src/db/init_db.py | .py | 09013144d1428e63 | 7 | 0 |
"""
마이그레이션 0001: dashboard_registry에 실시간 대시보드 지원 컬럼 추가
- data_freshness ENUM('static', 'realtime') DEFAULT 'static'
대시보드가 정적 배치 결과인지, 주기적으로 갱신되는 실시간 데이터인지 구분
- refresh_interval_minutes INT NULL
realtime 대시보드의 수집 주기(분). static 대시보드는 NULL
기존 3개 주제(OTT-소비, 연령대별 소비, 도시/비도시 미디어)는 컬럼 추가 시
DEFAULT 'static'이 기존 행에도 즉... | devleeeasy/insight-dashboard-hub | src/db/migrations/m0001_add_dashboard_freshness_columns.py | .py | 5ef38055f5bc2051 | 7 | 0 |
"""
마이그레이션 0002: dashboard_registry에 created_at 컬럼 추가
- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
등록 시각. get_connection()이 세션 타임존을 +09:00으로 고정해두므로
DEFAULT CURRENT_TIMESTAMP도 Asia/Seoul 기준으로 정확히 채워진다.
(다른 테이블처럼 애플리케이션이 매번 값을 채우는 대신, dashboard_registry는
개별 등록 스크립트(register_dashboard.py 등)로 관... | devleeeasy/insight-dashboard-hub | src/db/migrations/m0002_add_created_at_to_dashboard_registry.py | .py | 271d33d0c39bf467 | 7 | 0 |
"""
마이그레이션 0004: dashboard_registry.chart_type ENUM에 'realtime_monitor' 추가
실시간 상권 유동인구 모니터링 대시보드는 기존 4개 chart_type(correlation,
comparison, trend, distribution)처럼 지표4개+차트1개 고정틀에 안 맞는
다중 위젯 레이아웃(지표카드+Line+요일별Bar+성별Donut+연령대Bar+Top5테이블)이 필요해서
새 chart_type을 추가한다. 새 주제를 코드 수정 없이 등록한다는 원칙은 유지하되,
"이 chart_type은 렌더러가 섹션 전체를 ... | devleeeasy/insight-dashboard-hub | src/db/migrations/m0004_add_realtime_monitor_chart_type.py | .py | adf71dc103a7c140 | 7 | 0 |
"""
MySQL 연결 / 적재 / 조회 유틸리티
전처리 파이프라인(run_pipeline.py)이 집계 결과를 적재할 때, 그리고 API 계층이
dashboard_registry/agg 테이블을 조회할 때 공통으로 사용하는 저수준 유틸을 모아둔다.
"""
import logging
import os
import re
from datetime import datetime
from zoneinfo import ZoneInfo
import mysql.connector
import numpy as np
import pandas as pd
from dotenv impo... | devleeeasy/insight-dashboard-hub | src/db/mysql_client.py | .py | 239378627dbde85a | 7 | 0 |
"""
OTT 이용 행태 x 소비 지출 분석 - 전처리 파이프라인
흐름:
S3(raw) 원본 CSV 로드
→ 인코딩/헤더 정규화
→ 세그먼트 키 표준화 (연령대 버킷팅)
→ 가중값 적용 집계
→ S3(processed)에 Parquet 저장
→ MySQL agg 테이블에 적재
실행:
python -m src.preprocessing.ott_spending.run_pipeline
"""
import logging
import pandas as pd
from src.storage.s3_client import read_... | devleeeasy/insight-dashboard-hub | src/preprocessing/ott_spending/run_pipeline.py | .py | ba48cab6bc00a6dc | 7 | 0 |
"""
S3 기반 원본/가공 데이터 입출력 유틸리티
버킷 구조:
s3://<BUCKET>/insight-dashboard-hub/
raw/<topic>/<filename>.csv # 원본 (읽기 전용, 수정 금지)
processed/<topic>/<filename>.parquet # 전처리 완료본
환경변수:
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION
S3_BUCKET_NAME
"""
import io
import os
import logging
from f... | devleeeasy/insight-dashboard-hub | src/storage/s3_client.py | .py | 7259d85df6c46f0a | 7 | 0 |
#!/usr/bin/env python3
"""
alias_variant_table.py
Write a copy of a clinical variant table carrying additional column names, so
that a variant browser expecting a different capitalisation or naming
convention can read it.
Why this is needed
------------------
The dashboard's variant browser resolves columns by exact ... | patkarlab/mm-awgs-nextflow | bin/alias_variant_table.py | .py | 7f3ebcbac1b12d75 | 7 | 0 |
#!/usr/bin/env python3
"""
augment_sv_support.py
The SURVIVOR-merged VCF drops per-caller read support (it keeps only SUPP/
SUPP_VEC and coordinates), so support_reads cannot be recovered from the merged
file or from mm_annotated.tsv. This script layers the real per-caller support
back on, read directly from each call... | patkarlab/mm-awgs-nextflow | bin/augment_sv_support.py | .py | 6e64e5a5bfd1b93d | 7 | 0 |
#!/usr/bin/env python3
"""
build_ig_segments.py
====================
Emit a BED of immunoglobulin locus sub-regions: constant, J, D and V.
Why this exists
---------------
An IGH breakend's position within the locus carries mechanistic information
that its coordinate alone does not. Primary translocations in plasma ce... | patkarlab/mm-awgs-nextflow | bin/build_ig_segments.py | .py | 6d1f8a5ff89aa055 | 7 | 0 |
"""Parse the cohort BAF / LOH screen output for a single sample.
Unlike the other parsers in this package, the underlying artefact is
cohort-scoped rather than per-sample: the screen writes one table covering every
sample in the run, because it normalises heterozygous site density for each
panel region against the coh... | patkarlab/mm-awgs-nextflow | bin/dashboard_builder/parsers/baf_loh.py | .py | 45c6bbb7f95d4b95 | 7 | 0 |
"""Parse CNV-related outputs.
Per the agreed run layout, a sample's CNV outputs look like::
<sample>/
cnv_consensus/
<sample>_cnv_clinical.tsv # the clinical CNV table
cnvkit_plots/
<sample>.final-scatter.png # genome-wide scatter (PNG)
<sample>.final-diagram.pdf #... | patkarlab/mm-awgs-nextflow | bin/dashboard_builder/parsers/cnv.py | .py | 4dc2157c173b00c3 | 7 | 0 |
"""Optional build-time variant annotation via the GeneBe REST API.
GeneBe (https://genebe.net) provides ACMG classification, ClinVar status, gnomAD
allele frequencies and more. We POST batches of clinical variants and embed the
returned annotations into the per-sample dashboard.
Endpoint:
POST https://api.genebe.... | patkarlab/mm-awgs-nextflow | bin/dashboard_builder/parsers/genebe.py | .py | f7c8ab196c21aaed | 7 | 0 |
"""Parse Picard CollectHsMetrics output.
Picard files have two blocks:
## METRICS CLASS picard.analysis.directed.HsMetrics
<header line>
<data line>
## HISTOGRAM java.lang.Integer
<header line>
<rows>
We return a dict with:
- metrics: dict of column -> value (numeric where possible, else str)
- hist... | patkarlab/mm-awgs-nextflow | bin/dashboard_builder/parsers/hsmetrics.py | .py | 1093fdb8e0fea0b1 | 7 | 0 |
"""
ichor.py - dashboard parser for ichorCNA output.
The copy-number tab shows the ichorCNA genome-wide figure and the fitted
parameters. It deliberately does not show a segment call table: large-scale
copy number is read off the plot, and the per-bin segment file is not a
clinical reporting artefact.
Inputs, as laid... | patkarlab/mm-awgs-nextflow | bin/dashboard_builder/parsers/ichor.py | .py | cda83487576770a4 | 7 | 0 |
"""Extract the IGV-reports embedded tableJson and build a chr:pos:ref:alt -> unique_id lookup.
igv-reports renders an HTML page that embeds, as a <script> blob, a JS object:
const tableJson = {"headers": ["unique_id", "CHROM", "POSITION", "REF", "ALT", ...],
"rows": [[0, "chr1", 92478757, "... | patkarlab/mm-awgs-nextflow | bin/dashboard_builder/parsers/igv.py | .py | d4b7f26859d9e62b | 7 | 0 |
"""Optional build-time OncoKB annotation of clinical variants.
OncoKB (https://www.oncokb.org) is a precision-oncology knowledge base curated
by Memorial Sloan Kettering. The REST API requires an authentication token --
register a free academic account at https://www.oncokb.org/account/register
and copy the token from... | patkarlab/mm-awgs-nextflow | bin/dashboard_builder/parsers/oncokb.py | .py | 90aa1d106d1005f6 | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.