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
"""Console entry point for acme-adcs-ra. Loads configuration from the environment and starts the FastAPI ACME server. """ from __future__ import annotations import os import sys import urllib.parse import uvicorn from acme_adcs_ra.config import RAConfig from acme_adcs_ra.enrollment import CertsrvEnrollmentLeg, Fak...
hraedon/acme-adcs-ra
src/acme_adcs_ra/__main__.py
.py
71e176d323c0f3b9
7
0
"""Shared state, helpers, and URL builders used by ACME routes.""" from __future__ import annotations import asyncio import hashlib import hmac import logging import threading from collections.abc import Callable, Iterator from contextlib import asynccontextmanager, contextmanager from dataclasses import dataclass, f...
hraedon/acme-adcs-ra
src/acme_adcs_ra/app_state.py
.py
0db038d0fe55fa7f
7
0
"""Bounded serialization of attacker-controlled audit detail fields. Daybreak 2026-08-15 second rescan, F4 (the standing WI-014), part one. Auditing a pre-authentication denial is mandatory — an RA that silently drops evidence of people trying to talk to it is worse than one whose disk fills. But the *size* of that e...
hraedon/acme-adcs-ra
src/acme_adcs_ra/audit_bounds.py
.py
e42ca1c24e784a48
7
0
"""Audit retention: the floor, the footprint, and the gate on deletion. Part three of the standing WI-014, after ``audit_bounds`` (row *size*) and ``audit_coalesce`` (row *count* for replayable denials). Those two bound growth without deleting anything. This module is where deletion becomes possible, and therefore whe...
hraedon/acme-adcs-ra
src/acme_adcs_ra/audit_retention.py
.py
a3c039990865ab35
7
0
"""CSR validation gates for the ACME finalize path.""" from __future__ import annotations from cryptography import x509 from cryptography.hazmat.primitives.asymmetric import ec, rsa from cryptography.x509.oid import ExtendedKeyUsageOID, ExtensionOID, NameOID, ObjectIdentifier from acme_adcs_ra.acme_errors import bad...
hraedon/acme-adcs-ra
src/acme_adcs_ra/csr_validation.py
.py
afda4fa761630cc8
7
0
"""In-tree Negotiate (SPNEGO) auth for ``requests``, with Extended Protection (channel binding) support. Replaces ``requests-negotiate-sspi`` — a single-maintainer package (a provenance concern already noted in the threat model) that additionally *broke on Python 3.14*: its error handler subscripts a ``pywintypes.erro...
hraedon/acme-adcs-ra
src/acme_adcs_ra/negotiate_auth.py
.py
c09988cb6ef6abac
7
0
"""Issuance policy — deterministic allow/deny for certificate requests. Pure functions: same inputs always produce the same decision. No LLM, no network, no time-based randomness. """ from __future__ import annotations from collections.abc import Sequence from dataclasses import dataclass @dataclass(frozen=True) c...
hraedon/acme-adcs-ra
src/acme_adcs_ra/policy.py
.py
9b92f8b493b54296
7
0
"""In-process token bucket for unauthenticated endpoints. ``/acme/new-nonce`` is unauthenticated and every call performs a SQLite ``INSERT``. SQLite has a single writer, so an unauthenticated flood does not just grow a table — it contends for the write lock with the issuance path, where a blocked write surfaces as a 5...
hraedon/acme-adcs-ra
src/acme_adcs_ra/rate_limit.py
.py
881d4199d333a1c9
7
0
"""Certificate retrieval (RFC 8555 §7.4.2).""" from __future__ import annotations from fastapi import APIRouter, Depends, Request from fastapi.responses import Response from acme_adcs_ra.acme_errors import malformed, unauthorized from acme_adcs_ra.app_state import ServerContext, authenticate_account, get_context fro...
hraedon/acme-adcs-ra
src/acme_adcs_ra/routes/certificates.py
.py
dbe5740ac301b01b
7
0
"""Directory and nonce endpoints (RFC 8555 §7.1.1, §7.2).""" from __future__ import annotations from typing import Any from fastapi import APIRouter, Depends, Response from acme_adcs_ra.acme_errors import rate_limited from acme_adcs_ra.app_state import ( _ACME_PATHS, ServerContext, _url, get_context...
hraedon/acme-adcs-ra
src/acme_adcs_ra/routes/directory.py
.py
ebec4b75c281881f
7
0
"""Order creation (incl. rate limiting) and finalize orchestration (RFC 8555 §7.1, §7.4).""" from __future__ import annotations from fastapi import APIRouter, Depends, Request from fastapi.responses import JSONResponse from acme_adcs_ra.acme_errors import ( issuance_halted, malformed, rate_limited, r...
hraedon/acme-adcs-ra
src/acme_adcs_ra/routes/orders.py
.py
72a6ef7aa2b25ed8
7
0
"""Certificate revocation (RFC 8555 §7.6).""" from __future__ import annotations import json from typing import Any, cast from cryptography import x509 from cryptography.hazmat.primitives.serialization import Encoding from cryptography.x509 import DNSName from cryptography.x509.oid import ExtensionOID from fastapi i...
hraedon/acme-adcs-ra
src/acme_adcs_ra/routes/revocation.py
.py
dc9387d0330d3896
7
0
"""JSON serializers for ACME protocol objects.""" from __future__ import annotations from typing import Any from acme_adcs_ra.app_state import ( ServerContext, _url, ) def _account_to_json(context: ServerContext, account: Any) -> dict[str, Any]: return { "status": account.status, "conta...
hraedon/acme-adcs-ra
src/acme_adcs_ra/serializers.py
.py
190366bb57f69ca8
7
0
"""FastAPI ACME server (RFC 8555 subset) for the ADCS Registration Authority. This module is the composition root — it wires the app, includes routers, and sets up the exception handler. Route logic lives in routes/, shared state in app_state.py, finalize helpers in finalize.py, CSR validation in csr_validation.py, an...
hraedon/acme-adcs-ra
src/acme_adcs_ra/server.py
.py
bf0079d121f5f62d
7
0
"""JWS request verification used by the ACME server routes. This module only **verifies** signatures; it never signs anything. """ from __future__ import annotations import json from typing import Any from urllib.parse import urlparse from fastapi import Request from acme_adcs_ra.acme_errors import ( bad_nonce...
hraedon/acme-adcs-ra
src/acme_adcs_ra/server_jws.py
.py
c1bf552ea3beca88
7
0
"""Complementary control: no signing-capable library in the dependency set. This is the **dependency-layer backstop** to the AST guard in ``test_no_signing_key.py``. Even if a future change hides a cert-minting import behind dynamic dispatch (which the AST scanner may not catch), the library must still be *installed*...
hraedon/acme-adcs-ra
tests/architecture/test_no_signing_dependencies.py
.py
e5b148b6911034cc
7.5
0
"""Wheel artifact test: verify fixture PEMs are packaged correctly. Builds the wheel and inspects its contents to ensure package data (the fixture PEMs) are included. This guards against build-config regressions that could silently drop the fixtures from the installed wheel. """ from __future__ import annotations i...
hraedon/acme-adcs-ra
tests/architecture/test_wheel_artifacts.py
.py
a201dd2c2ba67dc8
7.5
0
"""Shared test helpers. The only thing here is a placeholder-JWK builder. Plenty of tests need a handful of *distinct* account keys and do not care what they contain — the store just needs different thumbprints. They used to spell those inline as ``{"kty": "RSA", "n": "x1", "e": "AQAB"}``. That stopped working when `...
hraedon/acme-adcs-ra
tests/conftest.py
.py
05e77e6f8cc659ce
7.5
0
"""A minimal hand-rolled ACME client for integration tests. This module lives under ``tests/`` and is allowed to **sign** JWS because it simulates Certify the Web. It is NOT scanned by the architecture guardrail. """ from __future__ import annotations import base64 import json from typing import Any from cryptogra...
hraedon/acme-adcs-ra
tests/hand_rolled_acme_client.py
.py
a9350b88cf1e55b6
7.5
0
"""Dependency composition for command-line, API and worker entry points.""" from __future__ import annotations from dataclasses import dataclass from tg_botx.config import Settings from tg_botx.features.checkin.runtime import CheckinService from tg_botx.infrastructure.persistence.db import Database @dataclass(slot...
Jonathan143/tg-botx
src/tg_botx/application/container.py
.py
3946226c0d5fedb0
7
0
"""Small in-process event bus used to decouple features. The bus is deliberately process-local. It is useful for wiring task status updates to notifications or monitoring in one worker; deployments that need cross-process delivery can replace it with a broker-backed adapter later. """ from __future__ import annotati...
Jonathan143/tg-botx
src/tg_botx/core/events.py
.py
d2fd36603bc8ed04
7
0
"""Channel notification contracts and a transport-agnostic service.""" from __future__ import annotations import inspect from collections.abc import Awaitable, Callable from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Protocol @dataclass(frozen=True, slots=True) cl...
Jonathan143/tg-botx
src/tg_botx/features/channel.py
.py
53593836035ba653
7
0
"""Extensible command dispatching for a future Telegram bot account. Handlers are plain async callables, which keeps this module independent from Telethon. A Telethon adapter only needs to turn an incoming event into a ``CommandContext`` and pass it to :meth:`CommandRegistry.dispatch`. """ from __future__ import ann...
Jonathan143/tg-botx
src/tg_botx/features/commands.py
.py
faf7ce2ec36a0aa3
7
0
"""Rule-based group monitoring primitives. This module handles deterministic matching and reply decisions only. A Telegram adapter is responsible for receiving events and sending replies; summarization can be supplied later without coupling the monitor to an LLM. """ from __future__ import annotations import inspec...
Jonathan143/tg-botx
src/tg_botx/features/monitoring.py
.py
4c4a0b4f70c4d58a
7
0
"""Telethon construction helpers kept at the integration boundary.""" from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Protocol from telethon import TelegramClient @dataclass(frozen=True, slots=True) class TelegramAccountConfig: """The minimum dat...
Jonathan143/tg-botx
src/tg_botx/integrations/telegram.py
.py
594f76207454f404
7
0
from __future__ import annotations import asyncio import json from datetime import datetime, timezone import logging from logging.handlers import RotatingFileHandler from pathlib import Path import typer from tg_botx.config import Settings from tg_botx.features.accounts.auth import AuthService from tg_botx.features....
Jonathan143/tg-botx
src/tg_botx/interfaces/cli.py
.py
2c4449974d02849b
7
0
""" CLI for physcons demonstrations. Entry point: `physcons demo` """ import argparse import sys import numpy as np from .data import generate_conserved_field, generate_broken_field from .router import PatchRouter from .conservation import ConservationLayer def demo_command(): """ Run the conservation demo...
abinesha312/physcons
src/physcons/cli.py
.py
376307478ff39be4
7
0
""" Conservation layer that wraps the Rust kernel. Implements the hard conservation constraint from PI-HC-MoE and the residual-based correction from PI-MFM. """ import numpy as np from typing import Tuple, Optional class ConservationLayer: """ Applies hard conservation constraints to model outputs. ...
abinesha312/physcons
src/physcons/conservation.py
.py
84740b0624a51a5e
7
0
""" Synthetic 1D conserved field generation. For demonstration purposes only. Real physics would involve PDEs, molecular dynamics, or other domain-specific simulations. """ import numpy as np from typing import Tuple def generate_conserved_field( n_points: int = 100, total_mass: float = 1000.0, seed: in...
abinesha312/physcons
src/physcons/data.py
.py
be7300462fb8a57b
7
0
""" Patch-based router inspired by Shodh-MoE. Routes patches of the input field to different "experts" (simple MLPs). The routing is deterministic and local, based on patch statistics. """ import numpy as np from typing import List, Tuple class SimpleExpert: """ A tiny expert network (just a linear layer fo...
abinesha312/physcons
src/physcons/router.py
.py
3156514a74d22bd8
7
0
""" Tests for CLI interface. """ import pytest from unittest.mock import patch import sys from physcons.cli import main, demo_command def test_demo_command_runs_without_error(): """Demo command should execute without raising exceptions.""" # This test just verifies the demo can run # It doesn't verify o...
abinesha312/physcons
tests/test_cli.py
.py
b98a0274d47f245c
7.5
0
""" Tests for synthetic data generation. """ import pytest import numpy as np from physcons.data import generate_conserved_field, generate_broken_field def test_conserved_field_has_correct_sum(): """Conserved field should sum to target.""" field, target = generate_conserved_field(n_points=100, total_mass=10...
abinesha312/physcons
tests/test_data.py
.py
2db30bd7c0b2440d
7.5
0
# app/actions.py """ Simple file-based wiki actions used by tests and scripts. In the current Streamlit-only setup the UI uses its own helper functions, but these actions are still useful for a minimal programmatic API and tests. """ from pathlib import Path from typing import Dict from slugify import slu...
Dhruv2012-collab/rag-platform
app/actions.py
.py
428926b75eef9a17
7
0
# app/agent/planner.py """ Deterministic agent planner: plan → rewrite → retrieve → draft → critic Tidy, human-readable output and clean action payloads. """ import os import re from typing import Dict, List, Tuple from app.rag.embedder import Embedder from app.rag.index import DocIndex from app.rag.rerank...
Dhruv2012-collab/rag-platform
app/agent/planner.py
.py
8a41c410603e504e
7
0
# app/rag/chunker.py from __future__ import annotations import re from typing import Dict, List # Very lightweight markdown chunker: # - Keeps headings together with their following paragraph(s) # - Splits into chunks of at most `max_chars` # - Uses a simple sliding-window when a single block is very long ...
Dhruv2012-collab/rag-platform
app/rag/chunker.py
.py
ea19c2d0cbcd6a68
7
0
# app/rag/embedder.py from __future__ import annotations from typing import List import numpy as np from sentence_transformers import SentenceTransformer class Embedder: """ Thin wrapper around SentenceTransformer used throughout the app. - Provides a default model so tests can call Embedder...
Dhruv2012-collab/rag-platform
app/rag/embedder.py
.py
c72b22bc1ed7f374
7
0
# app/rag/evaluator.py """ Tiny evaluation helper used by tests and local experiments. This is deliberately minimal: it provides a Recall@k style metric on top of a Retriever-like object with a ``dense(query, k)`` method. """ from typing import Dict, List class Evaluator: def __init__(self, retrieve...
Dhruv2012-collab/rag-platform
app/rag/evaluator.py
.py
e80bf47010af2069
7
0
# app/rag/reranker.py from typing import List, Dict, Tuple try: from sentence_transformers import CrossEncoder except Exception: CrossEncoder = None class Reranker: """Cross-encoder reranker. Falls back to a simple heuristic if model unavailable.""" def __init__(self, model_name: str): ...
Dhruv2012-collab/rag-platform
app/rag/reranker.py
.py
7ea94dbb3cab06ea
7
0
# app/rag/retriever.py """ Lightweight Retriever used by unit tests and legacy scripts. The Streamlit app uses Embedder + DocIndex directly. This module provides a tiny, dependency-free retriever for simple tests. """ from typing import Dict, List class Retriever: """In-memory toy retriever. ...
Dhruv2012-collab/rag-platform
app/rag/retriever.py
.py
0e5be41f166187d0
7
0
# app/rag/utils.py import json import pathlib try: import yaml # optional dependency except ModuleNotFoundError: yaml = None def ensure_dirs(): """Ensure required data folders exist.""" for d in ["data/raw", "data/processed/wiki", "data/index", "data/billing"]: pathlib.Path(d)...
Dhruv2012-collab/rag-platform
app/rag/utils.py
.py
8cfa387c6447d77d
7
0
# app/storage.py import os import pathlib USE_AZURE = os.getenv("VARIANT", "local").lower() == "dbx" if USE_AZURE: # pip install azure-storage-blob from azure.storage.blob import BlobServiceClient AZURE_BLOB_CONNECTION_STRING = os.getenv("AZURE_BLOB_CONNECTION_STRING") AZURE_BLOB_CONTAINER...
Dhruv2012-collab/rag-platform
app/storage.py
.py
06009e58f16ac4ea
7
0
""" Build FAISS index with optional progress callbacks. This script: - Scans all Markdown files under data/processed/ - Splits them into chunks using the shared chunker - Embeds all chunks with the configured SentenceTransformers model - Builds a fresh FAISS index + docstore.json Supports progress callbacks ...
Dhruv2012-collab/rag-platform
scripts/build_index.py
.py
e9414b57d910762b
7
0
# scripts/fetch_gitlab_handbook.py """ Fetch a curated subset of the GitLab Handbook (public pages). Stores raw HTML and markdownified text under data/raw and data/processed. Skips gated pages (e.g., culture/ → sign-in). """ import time, pathlib, requests from markdownify import markdownify as md RAW = path...
Dhruv2012-collab/rag-platform
scripts/fetch_gitlab_handbook.py
.py
dc8c76c30cd8e4bd
7
0
# scripts/promote_or_rollback.py import argparse import json import shutil import sys import time from pathlib import Path from typing import Any, Dict, List import mlflow import pathlib ROOT = pathlib.Path(__file__).resolve().parents[1] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) ...
Dhruv2012-collab/rag-platform
scripts/promote_or_rollback.py
.py
764d5d518ed91574
7
0
# services/config_service.py import json import os from typing import Dict, Any CONFIG_DIR = "config" CONFIG_PATH = os.path.join(CONFIG_DIR, "user_settings.json") def load_user_settings() -> Dict[str, Any]: """ Carga la configuración del usuario desde un JSON. Si no existe, devuelve un dict vacío. "...
vivz-dev/AI_Artwork_Catalog_PDF_Generator
services/config_service.py
.py
28b6c7de5433c6bc
7
0
# services/pdf_service.py from typing import List, Dict, Optional, Tuple import os import io from fpdf import FPDF from PIL import Image def _to_latin1(text) -> str: """ FPDF uses latin-1 internally, so we convert text to avoid encoding errors. Accepts any object and converts it to str. """ if t...
vivz-dev/AI_Artwork_Catalog_PDF_Generator
services/pdf_service.py
.py
c23925e92b7dc5be
7
0
# app.py import concurrent.futures import os import streamlit as st from PIL import Image from utils.image_utils import read_uploaded_file, bytes_to_pil_image from services.extraction_service import extract_image_text from services.pdf_service import build_ocr_pdf from services.config_service import load_user_settin...
vivz-dev/AI_Artwork_Catalog_PDF_Generator
streamlit_app.py
.py
cd6ac00e4d76c0a0
7
0
#!/usr/bin/env python3 """Checkpoint 50 acceptance contract: peer health classification.""" from core import AxvenCore checks=[] def ok(name, condition): assert condition, name checks.append(name) def state(core, peer): for item in core.outbound_peer_status(): if (item["host"],item["port"]) == p...
AxvenLabs/axven-core
checkpoint50_peer_health_classification_spec.py
.py
2a78ac3d6e47cce7
7.5
0
#!/usr/bin/env python3 """Checkpoint 15: two-node operational devnet rehearsal. Runs two independent Axven chains/mempools/wallets with real TCP P2P servers. No consensus parameters are changed. """ from __future__ import annotations import json, tempfile, shutil import axven, wallet, p2p from datadir import DataDir ...
AxvenLabs/axven-core
devnet_rehearsal.py
.py
8fae69a3d5059742
7
0
#!/usr/bin/env python3 """Restore missing labels on an existing Flatpak OCI index. Indexes published before the AppStream passthrough fix list the right images but only carry their ``org.flatpak.*`` labels: the publisher filtered ``org.freedesktop.appstream.*`` out. The metadata is still on the images in the registry,...
tuna-os/flatpak-index
scripts/enrich-index.py
.py
7949ec6882ebeb3d
7
0
"""Minimal read-only OCI registry client used by the index scripts. Only supports what the index needs: anonymous (or token-authenticated) pulls of a manifest and its config blob, so the image's labels can be read back. """ import json import subprocess import time import urllib.parse MANIFEST_ACCEPT = ",".join( ...
tuna-os/flatpak-index
scripts/oci.py
.py
30172e14f750f1c4
7
0
#!/usr/bin/env python3 """Add or replace one application's entry in a Flatpak OCI index. This is the canonical copy. Application repositories vendor it at ``.github/scripts/update-index.py`` and run it from their publish workflow after ``flatpak build-bundle --oci``. It is deliberately self-contained: one file, standa...
tuna-os/flatpak-index
scripts/update-index.py
.py
db1bc938cf0c0c91
7
0
""" Analytics dashboard — sales by vendor/product/location, revenue trends, conversion rates, and business intelligence endpoints. """ import frappe from frappe import _ from frappe.utils import flt, now_datetime, add_to_date, getdate @frappe.whitelist() def get_dashboard_summary(days=30): """High-level dashboard...
Ashutosh-Neupane/saathimart
saathimart/api/analytics.py
.py
71bee794ead84da2
7
0
""" Auth helpers — permission checks + bootinfo + token generation. """ import uuid import frappe from frappe import _ _COOKIE_NAME = "sm_cart_session" def get_session_id(): """Return the guest cart-session ID (ported from saathi_middleware). Resolution order: 1. sm_cart_session cookie from the request 2. ses...
Ashutosh-Neupane/saathimart
saathimart/api/auth.py
.py
9658393f968a53aa
7
0
""" Authentication: signup, login, OTP verification, password reset. Modeled after trevo_ecommerce patterns but self-contained for SaathiMart (no ERPNext dependency). """ from __future__ import annotations import hashlib import re import secrets import frappe from frappe import _ from frappe.utils import add_to_date...
Ashutosh-Neupane/saathimart
saathimart/api/auth_full.py
.py
8f314a161f6c0f56
7
0
""" Redis caching layer for hot product endpoints. Reduces DB load by serving cached results for read-heavy endpoints like list_products and get_banners. Cache strategy: - Short TTL (30s) for dynamic results (search, filters) - Medium TTL (60s) for product detail pages - Long TTL (300s) for static data (banners,...
Ashutosh-Neupane/saathimart
saathimart/api/cache.py
.py
503cd3bfceff03b1
7
0
""" Cart API — session-based cart for guests, user-keyed cart for logged-in users. Cart identity (ported from saathi_middleware): - Guests: the cart keys off a sm_cart_session cookie / explicit session_id. - Logged-in users: the cart keys off `user`, so every device and browser shares one basket. A pre-login g...
Ashutosh-Neupane/saathimart
saathimart/api/cart.py
.py
83ecd368cceab38f
7
0
""" Circuit breaker for vendor sync — prevents wasting resources pushing events to a vendor whose site is down. After consecutive failures, stops trying for a cooldown period, then allows a test request. States: CLOSED (normal) → OPEN (blocking) → HALF_OPEN (testing) → CLOSED """ import frappe from frappe.utils import...
Ashutosh-Neupane/saathimart
saathimart/api/circuit_breaker.py
.py
da2511815d0484cb
7
0
""" Clock skew tolerance — handles time differences between hub and vendor servers. Problem: Hub and vendor servers may have clocks that differ by seconds or even minutes. If the HMAC timestamp window is too tight, legitimate requests get rejected. If too wide, replay attacks have more opportunity. Solution: Adaptive...
Ashutosh-Neupane/saathimart
saathimart/api/clock_sync.py
.py
8e5f11e0eb256121
7
0
""" Connection pooling for outbound HTTP requests to vendors. Instead of creating a new TCP connection for every webhook delivery, reuse connections via urllib3's PoolManager. This reduces latency by ~100ms per request (no TCP handshake + TLS negotiation) and prevents port exhaustion under load. Also handles: - Con...
Ashutosh-Neupane/saathimart
saathimart/api/connection_pool.py
.py
de1736b95713c3b2
7
0
""" Dead letter auto-recovery — retries failed webhook events, archives old ones, and alerts admins when dead-letter count exceeds threshold. Three entry points: - retry_dead_letters(): daily cron — retries Dead events with reset backoff - archive_old_events(): weekly cron — archives events older than 7 days - d...
Ashutosh-Neupane/saathimart
saathimart/api/dead_letter.py
.py
13e5b8512736f856
7
0
""" Delivery API — delivery zones, charges, and time estimation. Endpoints: get_delivery_zones — GET /api/method/saathimart.api.delivery.get_delivery_zones estimate_delivery — GET /api/method/saathimart.api.delivery.estimate_delivery """ from __future__ import annotations import frappe from frappe import _ fro...
Ashutosh-Neupane/saathimart
saathimart/api/delivery.py
.py
350335326272be05
7
0
""" Event batching and compression — reduces the number of HTTP calls between hub and vendor by combining related events. Problem: During peak hours, 100+ stock.update events fire per vendor. Each is a separate HTTP POST. This wastes network resources and hits rate limits. Solution: 1. Batch multiple stock updates ...
Ashutosh-Neupane/saathimart
saathimart/api/event_batch.py
.py
9c4ce5ada1bf5543
7
0
""" Event deduplication — prevents the same event from being processed twice. Uses a sliding window of event fingerprints (hash of event_type + target + payload_key). The vendor already has idempotency checks, but this catches duplicates at the hub level before they waste network resources. Fingerprint TTL: 10 minute...
Ashutosh-Neupane/saathimart
saathimart/api/event_dedup.py
.py
207f53ebecab7dd0
7
0
""" Event ordering guarantees — ensures the vendor processes events in the correct sequence even if they arrive out of order. Problem: Network retries can cause events to arrive at the vendor out of order. Example: order.new (seq=5) arrives before order.accepted (seq=4). Solution: Each event carries a monotonic seque...
Ashutosh-Neupane/saathimart
saathimart/api/event_ordering.py
.py
aaf72dab65d2252e
7
0
""" Event priority system — ensures critical events (payments, order cancellations) are delivered before lower-priority events (stock updates, analytics). Priority levels: CRITICAL (1): payment.received, order.cancelled — must deliver ASAP HIGH (2): order.new, order.accepted — customer-facing NORMAL (3): o...
Ashutosh-Neupane/saathimart
saathimart/api/event_priority.py
.py
060299a03ad9fe9b
7
0
""" Fallback delivery path — if the primary webhook POST to a vendor fails, try alternative delivery methods before giving up. Delivery paths (in order): 1. Primary: HMAC-signed POST to vendor's webhook URL 2. Secondary: Poll-based — vendor pulls from hub's event API 3. Tertiary: Email payload to vendor admin (l...
Ashutosh-Neupane/saathimart
saathimart/api/fallback_delivery.py
.py
d18141ce94d91e5c
7
0
""" Filters API — returns available filter values for the product listing sidebar. Blinkit-style filter sidebar needs: - Categories (with product counts) - Price ranges (with product counts) - Brands / Vendors (with product counts) - Ratings (with product counts) - Dietary / Tags (with product counts) All e...
Ashutosh-Neupane/saathimart
saathimart/api/filters.py
.py
f7d76306533e6309
7
0
""" Health check endpoints — lightweight probes for monitoring hub ↔ vendor connectivity, Redis availability, MariaDB responsiveness, and overall system health. Endpoints: - health_check(): Public, returns basic alive status - deep_health_check(): Authenticated, returns full system status - vendor_h...
Ashutosh-Neupane/saathimart
saathimart/api/health.py
.py
584d9837074cf859
7
0
""" Image handling — thumbnail generation, format optimization, and CDN URL support. Supports: - Auto-generate thumbnails at upload time (300px, 600px, 1200px) - WebP conversion for modern browsers - CDN URL rewriting when configured """ import frappe from frappe import _ import os THUMBNAIL_SIZES = { "sma...
Ashutosh-Neupane/saathimart
saathimart/api/images.py
.py
0508de7ff87b14d2
7
0
""" Location API — nearest-vendor resolution using MariaDB spatial functions. All methods are whitelisted (allow_guest=True). Query params: lat — Customer latitude (required for distance calc) lng — Customer longitude (required for distance calc) radius_km — Search radius in km (default: 5)...
Ashutosh-Neupane/saathimart
saathimart/api/location.py
.py
616147222741a684
7
0
""" Mailing utilities for SaathiMart. Sends OTP emails, order confirmation emails, and password reset emails using Frappe's built-in sendmail. No ERPNext dependency. """ import frappe from frappe import _ def _get_site_name(): try: s = frappe.get_single("Settings") return getattr(s, "site_name", ...
Ashutosh-Neupane/saathimart
saathimart/api/mailing.py
.py
7b021f8896467f66
7
0
""" Mobile API optimization — lighter payloads, cursor pagination, field selection, and offline sync support for mobile apps. """ import frappe from frappe import _ from frappe.utils import cint, cstr import json @frappe.whitelist(allow_guest=True) def list_products_light(category=None, search=None, page=1, page_size...
Ashutosh-Neupane/saathimart
saathimart/api/mobile.py
.py
ebb861fe4e78642b
7
0
""" Notification system — handles order status updates, email confirmations, and push notification support for the storefront. """ import frappe from frappe import _ def create_order_status_notification(doc, new_status): """Create a notification when order status changes.""" status_messages = { "Confi...
Ashutosh-Neupane/saathimart
saathimart/api/notifications.py
.py
e7ea9ba6a76ea956
7
0
""" Event sourcing for orders — every state change is recorded in an immutable event log. Enables audit trail, timeline view, and replay capability. """ import frappe from frappe import _ import json as cjson from frappe.utils import now_datetime def record_order_event(order_id, event_type, data=None, actor=None): ...
Ashutosh-Neupane/saathimart
saathimart/api/order_events.py
.py
35c508b07821c56f
7
0
""" Partial failure isolation — ensures one vendor's failure doesn't block delivery to other vendors. Problem: If the drain_event_queue cron processes events sequentially and one vendor's delivery hangs, all subsequent vendors wait. Solution: Per-vendor goroutine-like isolation with timeouts and independent error tra...
Ashutosh-Neupane/saathimart
saathimart/api/partial_failure.py
.py
108f47173eb0e100
7
0
""" Vendor payouts API — how much is currently owed to a vendor, and recording that a payout actually happened. Money owed lives implicitly in Vendor Fulfillment rows: paid, non-cancelled fulfillments whose `vendor_payout` link is still empty. Vendor Payout records that link (see saathimart.saathimart.doctype.vendor_p...
Ashutosh-Neupane/saathimart
saathimart/api/payouts.py
.py
9db5c913c7045eae
7
0
""" Auth failure rate limiter — blocks brute-force attacks on webhook endpoints. Tracks failed authentication attempts per IP using Redis. After MAX_FAILURES failures within the WINDOW, the IP is blocked for BLOCK_DURATION. """ import frappe from frappe import _ from saathimart.api.redis_fallback import get_cache_fall...
Ashutosh-Neupane/saathimart
saathimart/api/rate_limiter.py
.py
8ec01cefddcd364d
7
0
""" Stock reconciliation — compares hub's Vendor Stock records with the vendor's actual ERPNext Bin quantities. Runs hourly to catch drift from missed events, manual adjustments, or race conditions. Two modes: - Auto-correct: mismatch within tolerance → silently fix - Flag for review: mismatch beyond tolerance → c...
Ashutosh-Neupane/saathimart
saathimart/api/reconciliation.py
.py
cec7eb6b6cf2ae81
7
0
""" Graceful degradation when Redis is unavailable. All Redis-backed features (rate limiter, circuit breaker, cache) fall back to MariaDB-based alternatives so the app doesn't break when Redis is down. Usage: from saathimart.api.redis_fallback import get_cache_fallback cache = get_cache_fallback() cache.s...
Ashutosh-Neupane/saathimart
saathimart/api/redis_fallback.py
.py
e0eac5ef525f4fc7
7
0
""" One error shape for every endpoint, ported from saathi_middleware's api/responses.py (adapted: saathimart endpoints signal failures by raising, so the decorator layer is not needed here — see below). Errors leave this app two different ways: 1. Thrown — `frappe.throw(...)`. Frappe puts the text in `_server_mess...
Ashutosh-Neupane/saathimart
saathimart/api/responses.py
.py
d8324432c761c855
7
0
""" Review API — product reviews and ratings. Endpoints: list_reviews — GET /api/method/saathimart.api.reviews.list_reviews add_review — POST /api/method/saathimart.api.reviews.add_review get_product_rating — GET /api/method/saathimart.api.reviews.get_product_rating """ from __future__ import annotatio...
Ashutosh-Neupane/saathimart
saathimart/api/reviews.py
.py
0bdae74e2a56abfd
7
0
""" Search improvements — full-text search with MariaDB FULLTEXT indexes, fuzzy matching for typos, and autocomplete suggestions. """ import frappe from frappe import _ from frappe.utils import cint @frappe.whitelist() def search_products(query="", page=1, page_size=20, category=None, brand=None, ...
Ashutosh-Neupane/saathimart
saathimart/api/search.py
.py
c2909c1492560bd0
7
0
""" Zero-downtime webhook secret rotation. Rotating a shared secret between two live sites has one hard constraint: at no instant may a legitimately-signed request be rejected. Flipping both sides "at the same time" is impossible over a network, so instead we make the receiver temporarily accept TWO secrets and walk t...
Ashutosh-Neupane/saathimart
saathimart/api/secret_rotation.py
.py
2336255f27d05322
7
0
""" Stock snapshot sync — periodic full-stock comparison between hub and vendor. Problem: Individual stock.update events can be lost or processed out of order, causing silent drift between hub's Vendor Stock and vendor's Bin quantities. Solution: Hourly full-stock snapshot where the hub sends ALL current stock quanti...
Ashutosh-Neupane/saathimart
saathimart/api/stock_snapshot.py
.py
22f973626dc85d37
7
0
"""Pure helpers for keeping a character identity stable across scene assets.""" from __future__ import annotations import hashlib import json from collections.abc import Mapping from typing import Any, Dict, Optional _IDENTITY_FIELDS = ( "character_key", "face_asset", "image_file_id", "asset_version...
Leejinhoe/soft_capston
DB연결 테스트/character_identity.py
.py
f697b72f75d9e416
7
0
"""Deterministic cache-key helpers for generated story media.""" from __future__ import annotations import hashlib import json import unicodedata from collections.abc import Mapping from typing import Any, Dict, Optional CACHE_KEY_VERSION = "media-v1" def _normalize_text(value: Any) -> str: """Normalize user-...
Leejinhoe/soft_capston
DB연결 테스트/media_cache.py
.py
5ab57466a83df74a
7
0
"""Shared policy for single-character motion classification and training.""" from __future__ import annotations from typing import Any, Mapping # Keep this list conservative: every motion must be readable without a partner # or a handoff/object interaction in the training example. SOLO_ANIMATION_ACTIONS = frozenset...
Leejinhoe/soft_capston
DB연결 테스트/motion_policy.py
.py
eb4c34a9ab4fff4b
7
0
"""Build a transparent 4x2 crawl-cycle sheet for male_01. The source character is kept intact and reused from the existing run-cycle sheet. Local PIL transforms provide a low, forward-facing crawl silhouette without introducing a new character design or an external model dependency. """ from __future__ import annota...
Leejinhoe/soft_capston
tools/asset_workers/build_male_01_crawl_cycle.py
.py
de660b9784a6b743
7
0
"""Configuration management for httpcall.""" from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): """Application settings loaded from environment variables.""" model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore") T...
abinesha312/httpcall
httpcall/config.py
.py
db4012f5e606fcd4
7
0
"""Phone number validation and security checks.""" import re from typing import Tuple def validate_e164(phone_number: str) -> Tuple[bool, str]: """ Validate that a phone number is in E.164 format. E.164 format: +[country code][subscriber number] Maximum 15 digits including country code. ...
abinesha312/httpcall
httpcall/validation.py
.py
4a32efe23963cdb7
7
0
"""Tests for phone number validation.""" import pytest from httpcall.validation import validate_e164, is_likely_premium_rate class TestValidateE164: """Tests for E.164 phone number validation.""" def test_valid_us_number(self): """Test valid US phone number.""" is_valid, error = validate...
abinesha312/httpcall
tests/test_validation.py
.py
e842526226b56e22
7.5
0
""" svg_embed_images.py — 把图片以 base64 data:URL 嵌入 SVG。 功能: 1. 读取 placement JSON 决定每张图嵌入哪页、什么坐标 2. 内置双 base64 前缀修复(防止多次运行产生 data:image/...;base64,data:image/...) 3. 可选: 按精确坐标删除旧的占位 <image>(处理"双图并存"问题) 用法: python svg_embed_images.py \\ --svg-dir ./svg \\ --placements placements.json """ import argpa...
galagersharp-code/svg-defense-ppt
scripts/svg_embed_images.py
.py
055e62928dff9b37
7
0
""" svg_legibility.py — 字号 + 颜色升级(高对比度排版)。 核心思想: 不直接对 SVG 用 +3 一刀切(容易溢出),而是用温和档 + 可选 reverse 两步映射。 用法: # 默认温和档(v4) python svg_legibility.py --svg-dir ./svg # 反向回退(v3 → v2),可与 upgrade 配合做两步走 python svg_legibility.py --svg-dir ./svg --reverse # 一次性激进档(v3,不推荐,会溢出) python svg_legibility.py --svg...
galagersharp-code/svg-defense-ppt
scripts/svg_legibility.py
.py
bfe002323d335f57
7
0
""" svg_to_pdf.py — 把 N 张 SVG 合并成 16:9 PDF。 每个 SVG 先用 fitz 高保真渲染为 PNG(默认 2x = 2560×1440),再插入到对应 PDF 页面。 这样能 100% 还原 SVG 中的中文、渐变、阴影、图案等。 用法: python svg_to_pdf.py --svg-dir ./svg --out ./out/deck.pdf --scale 2.0 """ import argparse import re from pathlib import Path import fitz # PyMuPDF SVG_HEADER_RE = re.comp...
galagersharp-code/svg-defense-ppt
scripts/svg_to_pdf.py
.py
9dca9aff447188d5
7
0
""" svg_to_pptx_editable.py — 把 SVG 转成 16:9 PPTX(**完全可编辑**)。 每个 SVG 元素都映射为独立的 PowerPoint 原生对象: <text> → TextBox (可改字、改字号、改色) <rect> → RECTANGLE Shape (可改色、移动、旋转) <circle> → OVAL Shape (可改色) <line> → 极扁 RECTANGLE (作为粗线条) <image> → PICTURE (可换图、缩放) <g transform> → 递归应用 transform ...
galagersharp-code/svg-defense-ppt
scripts/svg_to_pptx_editable.py
.py
33ed6f2164967bb0
7
0
#!/usr/bin/env python3 """各向异性摩擦椭圆的金标生成器——**闭式解,独立于被验内核**。 本文件只用``math``。**不import任何`physics_engine.contact`的东西**: 金标若调了被验的映射,它验的就只剩"这段代码没变过"。 记``a = μ_∥·N``、``b = μ_⊥·N``为椭圆两个半轴(力的量纲,N), ``m̂``为滑移方向的单位矢量(面内,与纵向轴夹角``ψ``)。 ## 一、支撑函数:关联流动下沿``m̂``稳态滑移的耗散/单位距离 最大耗散原理(Hill)说实际切向力在容许集上使``f·m̂``最大, 而凸集上"沿给定方向的最大投影"就是**支撑函...
Rtiming/physics-engine
cases/anisotropic_friction_ellipse/generate_oracle.py
.py
67f8e7997f6ece3f
7
0
#!/usr/bin/env python3 """整杆各向异性弯曲与扭转的金标——**四条闭式,全部独立于被验内核**。 ## 一、螺旋线运动学(含一条恰好为零的判据) 参数化``x(θ) = (R cos θ, R sin θ, p θ)``的曲率与挠率是教科书闭式: κ = R/(R² + p²), τ = p/(R² + p²) **第三个数是零,而且它是结构零不是收敛零。** 把材料帧的``m1``取成解析主法线 ``n(θ) = −(cos θ, sin θ, 0)``后,螺旋线上**没有任何hard-way弯曲**: * 顶点``θ_v``两侧的两条弦,其叉积(离散曲率二法矢``κb``)与解析...
Rtiming/physics-engine
cases/anisotropic_rod_twist/generate_oracle.py
.py
ee4b70c66485be0f
7
0
#!/usr/bin/env python3 """`AxialStretch`梯度与Hessian的独立解析金标——**精确有理算术,不调被验内核**。 本案例闭合的是决策0024第六节登记的那处缺口:拉伸项的Hessian此前**只有有限差分 背书**。按spec/12第6.1节的口径,有限差分门只验"雅可比是不是我写的那个能量的导数", 不验"那个能量对不对"——能量本身写错时FD照样全绿。这份金标是那一栏缺的第二道门。 ## 独立性(轴7规则4的力学版,spec/12第3.2节) 本脚本**不import`physics_engine.energies`**,一个函数也不复用。它只从 `physics_engine.o...
Rtiming/physics-engine
cases/axial_stretch_hessian/generate_oracle.py
.py
d105a1650e815f6b
7
0
#!/usr/bin/env python3 """带重力连续弹跳的金标生成器——**闭式,不跑引擎**。 四条闭式全部来自同一个事实:**刚体瞬时碰撞下,每一跳的出射速率是上一跳的``e``倍**。 * 从高``h``静止释放,落地耗时``t0 = √(2h/g)``、落地速率``v0 = g·t0``; * 第``n``跳以``e^n·v0``离开,那一段飞行耗时``2·e^n·v0/g = 2·e^n·t0``; * 总时长 ``T = t0·(1 + 2·Σ_{n≥1} e^n) = t0·(1+e)/(1−e) = √(2h/g)·(1+e)/(1−e)``; * 顶点 ``h_n = (e^n v0)²/(2g) =...
Rtiming/physics-engine
cases/bouncing_ball_gravity_train/generate_oracle.py
.py
c2c622af18430499
7
0