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
# backend/services/calendar_service.py from googleapiclient.discovery import build from datetime import datetime, timezone, timedelta def get_events(creds, lookahead_days=7): service = build("calendar", "v3", credentials=creds) now = datetime.now(timezone.utc) time_max = now.replace(hour=23, minute=59) + t...
ANewProfile/breadcrumbs
backend/services/calendar_service.py
.py
bc5534d5f5404a6e
7
0
import random import time from concurrent.futures import ThreadPoolExecutor from googleapiclient.discovery import build from googleapiclient.errors import HttpError RATE_LIMIT_MAX_RETRIES = 5 RATE_LIMIT_BASE_DELAY_SECONDS = 1.0 # Calendar's batch endpoint lets one HTTP request carry many operations (Google # caps a s...
ANewProfile/breadcrumbs
backend/services/calendar_write.py
.py
e131956b3c1208d6
7
0
from datetime import datetime, timezone MIN_SAMPLES_FOR_HISTORY = 5 HISTORICAL_WEIGHT = 0.6 USER_ESTIMATE_WEIGHT = 0.4 RECENCY_DECAY = 0.85 # Sentinel for completions recorded before completed_at existed — sorts last # (lowest recency weight) rather than crashing on a missing timestamp. _MISSING_COMPLETED_AT = dateti...
ANewProfile/breadcrumbs
backend/services/estimation.py
.py
7b1cbf1d15bdb1a2
7
0
from datetime import datetime from bson import ObjectId def overlaps(a_start: datetime, a_end: datetime, b_start: datetime, b_end: datetime) -> bool: return a_start < b_end and a_end > b_start def find_conflicting_task(tasks_collection, user_id, exclude_task_id: str, new_start: datetime, new_end: datetime): ...
ANewProfile/breadcrumbs
backend/services/reschedule.py
.py
73c20405afba9d46
7
0
from datetime import date, timedelta DEFAULT_MAX_CONTINUOUS_MINUTES = 90 DEFAULT_MAX_SUBJECTS_PER_DAY = 3 PRIORITY_RANK = {"high": 0, "medium": 1, "low": 2} def _urgency_bucket(task: dict, today: date) -> int: """ Lower = more urgent. Due date drives this, not priority — a deadline is a hard constraint,...
ANewProfile/breadcrumbs
backend/services/scheduler.py
.py
09ae25b1cbf3a4e6
7
0
from datetime import date, datetime, time, timedelta from zoneinfo import ZoneInfo BLOCK_LETTERS = ["A", "B", "C", "D", "E", "F", "G", "T"] DAY_NUMBERS = ["1", "2", "3", "4", "5", "6"] # Events from the school-schedule tool are suffixed rather than prefixed, so # they read as "Chemistry [SCHOOL]" instead of "[Breadcr...
ANewProfile/breadcrumbs
backend/services/school_schedule_service.py
.py
b324c57a69abc239
7
0
import secrets from datetime import datetime, timedelta, timezone SESSION_TTL_DAYS = 30 def upsert_user(users_collection, *, google_sub: str, email: str, name: str | None, picture: str | None) -> dict: """Finds or creates a user keyed by their stable Google account id (sub) — this is the only identity we hav...
ANewProfile/breadcrumbs
backend/services/user_service.py
.py
b8f7a49b468ccf3f
7
0
""" Parser for Unlimited-OCR's grounded output stream. The model's ``infer(eval_mode=True)`` returns text interleaved with grounding markers:: <|det|>title [253, 436, 670, 455]<|/det|>3. Preparation of the iodine... <|det|>text [253, 461, 823, 535]<|/det|>Since you know very precise... <|det|>page_number ...
jdhori/DocAble
src/docable/det_stream.py
.py
0ca8f6b6fe943604
7
0
""" Office-document support via LibreOffice headless conversion. Office formats ride the existing PDF pipeline: convert to PDF, then render, OCR, and judge exactly like any other PDF. This works because LibreOffice preserves what matters for the verdict — typed text becomes a real text layer, while pasted scan images ...
jdhori/DocAble
src/docable/office.py
.py
411a923c8994c477
7
0
""" Document -> page decomposition. Turns an uploaded document (PDF or single image) into a uniform list of pages, each carrying a rendered PNG for the OCR model and whatever native text layer the source already had. Capturing the native text here is deliberate: comparing it against what OCR recovers is how the audit ...
jdhori/DocAble
src/docable/pages.py
.py
6e92338cde83d680
7
0
""" Pandoc fast path for born-digital office documents. Rasterizing a typed .docx and OCR-ing the pixels back is lossy theater — pandoc reads the document's own XML. What survives that the OCR path cannot give: true heading levels from styles, structured tables, OMML equations as real LaTeX (which MathJax then typeset...
jdhori/DocAble
src/docable/pandoc_doc.py
.py
9ac95ffb98837463
7
0
""" Self-contained HTML audit report — the deliverable. result.json is for machines and the vault projection; this is the artifact a human hands to an instructor or attaches to a remediation ticket. One file, no external assets, accessible (semantic table, real contrast, works without CSS), and honest about failures: ...
jdhori/DocAble
src/docable/report.py
.py
ea2816c39e547133
7
0
""" OCR runner: the one component that touches the GPU. Everything above this module speaks a two-member protocol (``model_id``, ``extract_page``), so the HTTP layer and pipeline are testable with a fake and the model dependency stays optional (the ``ocr`` extra in pyproject). """ from __future__ import annotations ...
jdhori/DocAble
src/docable/runner.py
.py
65db5fe94d64a1f5
7
0
""" Accessibility score: one explainable number, an itemized breakdown. This is a PRIORITIZATION signal in the spirit of Ally's 0-100 — it tells an auditor which documents to open first and roughly why. It is NOT a WCAG conformance measure and must never be presented as one: conformance is per-criterion and binary, an...
jdhori/DocAble
src/docable/score.py
.py
be6a6e19b0e5c6c9
7
0
""" The is_scanned verdict: does a page's text exist as text, or only as pixels? This is the judgment Canvas Bot's Excel report has always tracked as a manually-filled "Requires OCR" dropdown. Here it becomes computed: compare how much text the PDF's native layer holds against how much text the OCR model can actually ...
jdhori/DocAble
src/docable/verdict.py
.py
97fa8c34ca3f5da1
7
0
"""Shared fixtures: a tiny generated PDF with one born-digital text page and one image-only page — the two cases the audit pipeline must tell apart.""" import io import pymupdf import pytest from PIL import Image @pytest.fixture(scope="session") def mixed_pdf_bytes() -> bytes: doc = pymupdf.open() # Page 1: ...
jdhori/DocAble
tests/conftest.py
.py
4414c5d68ea50303
7.5
0
""" Tests for figure triage — the routing brain of the image linting service. Policy under test (user-specified): - Figure with a caption, or discussed in the preceding text -> the image is redundant with the text -> decorative candidate (alt="") - Chart/graph regions -> chart workflow (rebuild as accessible plotly/...
jdhori/DocAble
tests/test_figures.py
.py
f2ce90d959ec582d
7.5
0
"""Tests for output quality flags — the lint pass on recovered text.""" from docable.qc import quality_flags class TestQualityFlags: def test_clean_output_has_no_flags(self): md = "## Heading\n\nA normal paragraph of recovered text with variety." assert quality_flags(md, ocr_word_count=9) == [] ...
jdhori/DocAble
tests/test_qc.py
.py
2da14b1480fce5a4
7.5
0
""" Tests for the is_scanned verdict. The verdict answers the auditor's question per page: "does this page's text exist as real text, or only as pixels?" — and rolls that up to the document-level Requires OCR flag Canvas Bot's Excel report tracks. """ from docable.verdict import document_verdict, page_verdict class ...
jdhori/DocAble
tests/test_verdict.py
.py
035607a3d6366a73
7.5
0
"""FastAPI router for the player-facing halves of net check-ins (app/checkin.py) that need a human on the other end: registering the last-resort fallback name, and two PUBLIC node pickers (MeshCore and Meshtastic) so a person can pick a radio by name instead of typing an 8-hex reference by hand on either protocol. Two...
zvx-echo6/meshwars
app/checkin_api.py
.py
dddc1e804b3e11af
7
0
"""Pure grid-cell math for MeshCore ingest. No state, no database access. Cells are aligned to a fixed lat/lon grid, not geohash, so cell size is uniform and predictable everywhere (geohash cells warp with latitude). """ from __future__ import annotations import math CELL_LAT_DEG = 0.0027 CELL_LON_DEG = 0.00384 _EA...
zvx-echo6/meshwars
app/grid.py
.py
224027ebc326f613
7
0
"""Async HTTP client for the upstream meshview API. We do not assume a specific meshview version. The client is written to accept multiple plausible response shapes (some forks expose decoded position fields directly, some return raw bytes that need protobuf decoding). When the latter is the case we fall back to manua...
zvx-echo6/meshwars
app/meshview_client.py
.py
211672b1c1aaccd9
7
0
"""Shared helper for normalizing a Meshtastic/MeshCore node reference. Both the public join flow (app/join_api.py) and the key-authenticated node-management routes (app/nodes_api.py) accept the same two input shapes for a node id -- `!a1b2c3d4` or bare `a1b2c3d4`, in any case -- and both need to agree on exactly the s...
zvx-echo6/meshwars
app/node_ref.py
.py
6cea5fae602200cf
7
0
"""Credits "Places Worth Going" (docs/features/places.md) from an accepted, scoring ping -- hooked into the same write transaction as app/mc_scoring.apply_paint(), called right after it from both app/mc_ingest.py and app/ingest.py (see credit_places()'s docstring for exactly what gates a credit). This module never touc...
zvx-echo6/meshwars
app/place_scoring.py
.py
a72db6a459d376a7
7
0
"""How far a square is from the nearest town. Used only by the Frontier award (app/results.py) and, through the same Census anchors, by the seed's effort scoring (scripts/build_places_seed.py's "city limits" test). NOT by Explorer: Explorer is not an award at all -- it is the season-long Places Worth Going points rank...
zvx-echo6/meshwars
app/places.py
.py
35873149626116b1
7
0
"""Read routes for "Places Worth Going" (docs/features/places.md): what frontend/map2.js draws on the map and lists in its slide-out panel. Not part of the keyed /api/v1 surface (app/public_api.py) -- that is a deliberately separate, stable contract for external integrators, and every other route the site's OWN pages ...
zvx-echo6/meshwars
app/places_api.py
.py
16d2e7006a1d1a74
7
0
"""Tests for scripts/build_places_seed.py's score_points()/_summit_points() -- the elevation-scaling model added 2026-08-25 ("lets make the points for peaks scaling. 50 for low elevation peaks up to 100 for 9000ft +"). scripts/ is not a package (this pipeline is meant to run standalone -- see that module's own docstri...
zvx-echo6/meshwars
tests/test_build_places_seed.py
.py
5451287a8d4b9226
7.5
0
"""Tests for the one-time update notice: the player-facing read route (app/notice_api.py) and the singleton-row active/inactive semantics the admin save route (app/admin_ops.py's admin_notice_save) relies on. Same monkeypatch-the-module's-connect() pattern tests/test_places_api.py already uses, rather than spinning up...
zvx-echo6/meshwars
tests/test_notice_api.py
.py
8110bf7ac5813c43
7.5
0
"""Tests for app/place_rotation.py: the weekly rotation draw is deterministic from week_start alone, and respects MIN_SPACING_MILES's minimum spacing between chosen places (docs/features/places.md). """ from __future__ import annotations import time import app.place_rotation as rot_module from app.grid import distanc...
zvx-echo6/meshwars
tests/test_place_rotation.py
.py
4906b1368c0cabe2
7.5
0
"""Tests for the actual wiring between the MeshCore ingest pipeline (app/mc_ingest.py) and Places Worth Going (app/place_scoring.py) -- not app/place_scoring.credit_places() in isolation (tests/ test_place_scoring.py already covers that exhaustively), but the hook itself: McIngestor._process_batch_sync() -> _process_on...
zvx-echo6/meshwars
tests/test_place_scoring_ingest_hook.py
.py
38ec85b1117c4f9b
7.5
0
"""Tests for app/places_api.py's active-flag filtering: an inactive place (app/places_seed.py's reconcile flag, set when a place leaves the seed) must never appear in the viewport or "near here" panel response, even when a stale place_week row still points at it (a rotating place drawn earlier in the week, then deactiv...
zvx-echo6/meshwars
tests/test_places_api.py
.py
4729fbd6c5668bdd
7.5
0
"""Talking to EduPage, with the network stood in for. The school's server is somebody else's, it rations how often one address may ask, and it answers a lapsed session with a login page and HTTP 200. All three are handled, and none of it was tested: a build reaches this code every night and a checkout never does, beca...
nemecec/little-tools
tests/test_client.py
.py
a62af194b7039396
7.5
0
"""flair — the fun, opt-out layer. The dungeon announcer for game_loop. This is the ONLY part of game_loop that is decoration, not enforcement. It is deliberately isolated here so it never touches the gate logic. It is purely additive to output, only ever writes its own state keys, and can be turned off entirely (conf...
SupposedlySam/game_loop
.game_loop/bin/flair.py
.py
f1815e09aed1e32e
7
0
"""A change to what game_loop REFUSES must be recorded, or declared as unnoticeable — never neither. `.game_loop/behaviour.json` is the machine-readable record of what an existing verb now costs or refuses differently. It ships with the payload, `status` diffs the installed copy against main, and consumers read the de...
SupposedlySam/game_loop
test/behaviour_gate.py
.py
c23a398ac067f31b
7.5
0
#!/usr/bin/env python3 """Run test/run.py's sections across processes, and merge the results honestly. WHY THIS EXISTS. The suite is 1719 assertions in ~306 seconds on 14 cores, and it uses one of them. The cost is not compute: nearly every section builds a sandbox and then spawns the 14k-line binary several times, so...
SupposedlySam/game_loop
test/prun.py
.py
39d50d44581934a3
7.5
0
"""Regression tests for reconcile.py — run this before shipping any change. python test_reconcile.py Two guarantees are locked in here so past mistakes cannot silently recur: 1. LIMITS/DECIMALS behave per the agreed rules (target blank, decimals from the limits, no trailing .0, accuracy on Lower/Upper). ...
Gouravkim/Automated-Inspection-Standard-Reconciliation-MSIL-
test_reconcile.py
.py
1e9e36560e1c441c
7.5
0
"""The generic, framework-agnostic Carmel agent bridge. This module is the single test seam for the whole agentic layer: every future Carmel agent persona (Literature, Planning, Revision, Data, Reporting, ...) attaches to :class:`CarmelAgent` by supplying its own ``system_prompt``, ``tools`` and ``output_schema`` — no...
DanaResearchGroup/Carmel
carmel/agents/bridge.py
.py
5823684425e63a15
7
0
"""The Literature Agent and Verifier personas: prompts, output schemas, factories. Two strictly separated personas share the generic :class:`~carmel.agents.bridge.CarmelAgent` bridge: - The **Literature Agent** proposes findings. Everything it emits (:class:`ProposedFinding`) is UNTRUSTED until the deterministic gr...
DanaResearchGroup/Carmel
carmel/agents/literature_agent.py
.py
3f03b89619af4c00
7
0
"""Resolve a model FAMILY to the newest concrete model the provider actually serves. Carmel used to pin exact model names (``gemini-3.5-flash``, ``gemini-pro-latest``) in :data:`carmel.config.DEFAULT_TIER_MODELS`. Both failure modes of that approach were observed live on the same afternoon: - a **dated pin rots**. ``...
DanaResearchGroup/Carmel
carmel/agents/model_catalog.py
.py
82d9f4786cad6838
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """API key discovery for Carmel's agentic layer. Requiring an operator to hand-export an API key before every run (e.g. ``set -a; . ~/.config/google/env; set +a``) is bad ergonomics when the key already sits on disk in a well-known place. This...
DanaResearchGroup/Carmel
carmel/credentials.py
.py
761cfad456ed8310
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Centralized logging configuration for Carmel.""" import datetime import logging import shutil import sys from pathlib import Path from typing import Any from carmel.version import __version__ LOGGER_NAME = "carmel" LOG_FORMAT = "%(asctime...
DanaResearchGroup/Carmel
carmel/logger.py
.py
4b32a9a49f18ba44
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Path utilities and workspace initialization for Carmel.""" import os from pathlib import Path #: Where campaign workspaces live when nothing else says otherwise. #: #: Top-level ``~/carmel_workspaces``, per commit a986543 ("Move default wo...
DanaResearchGroup/Carmel
carmel/paths.py
.py
90628f021ea8441a
7
0
"""Schemas for the manual paper-acquisition queue. A live probe of 60 combustion-kinetics works found only 2 (3.3%) whose full text Carmel could fetch and read on its own. Manual acquisition is therefore the ORDINARY path for this field, not an error branch: most papers a campaign needs must be obtained by a human thr...
DanaResearchGroup/Carmel
carmel/schemas/acquisition.py
.py
4cd3a8d232cc3494
7
0
"""Per-action execution state and plan progress — the multi-action backbone. ``PlanProgress`` is the persisted source of truth for how far a plan has run: one :class:`ActionState` per planned action plus a ``cursor`` naming the next action to consider. The campaign-level state becomes a *projection* of this structure ...
DanaResearchGroup/Carmel
carmel/schemas/action_state.py
.py
a8a7cefe0dfaaa21
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Approval policy and decision schemas.""" from datetime import datetime from enum import StrEnum from pydantic import BaseModel, ConfigDict, Field class ActionKind(StrEnum): """Categories of actions that may require approval.""" ...
DanaResearchGroup/Carmel
carmel/schemas/approval.py
.py
115afd50ce3a62b4
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Campaign and input schemas.""" import math from datetime import datetime from enum import StrEnum from pathlib import Path from typing import Any from pydantic import BaseModel, ConfigDict, Field, field_validator class EntryMode(StrEnum)...
DanaResearchGroup/Carmel
carmel/schemas/campaign.py
.py
c08615c0298520b4
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Plan and planned-action schemas.""" from datetime import datetime from typing import Any from pydantic import BaseModel, ConfigDict, Field from carmel.schemas.approval import ActionKind, ApprovalRequirement #: Current plan schema version...
DanaResearchGroup/Carmel
carmel/schemas/plan.py
.py
1a2fce964fd40f8e
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Run record schemas.""" from datetime import datetime from enum import StrEnum from pathlib import Path from pydantic import BaseModel, ConfigDict, Field class RunStatus(StrEnum): """Status of a tool run.""" PENDING = "pending" ...
DanaResearchGroup/Carmel
carmel/schemas/run.py
.py
fc5eefd74afe75c1
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Campaign lifecycle state schemas.""" from datetime import datetime from enum import StrEnum from pydantic import BaseModel, ConfigDict, Field class CampaignStateValue(StrEnum): """Discrete states in the campaign lifecycle.""" DR...
DanaResearchGroup/Carmel
carmel/schemas/state.py
.py
da620208d5b0f250
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Private generic kernel shared by the typed envelope bridges. There are two content-addressed envelope types -- :class:`~carmel.schemas.datasets.DatasetEnvelope` and :class:`~carmel.schemas.datasets.ConditionSetEnvelope` -- and both need the ...
DanaResearchGroup/Carmel
carmel/services/_envelope_bridge.py
.py
e24ac39c5f7409df
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Per-publisher download recipes for the manual acquisition README. The manual queue is the only working route for closed-access papers, and the README this module feeds is the operator's ONLY instruction sheet. Two design decisions here are ...
DanaResearchGroup/Carmel
carmel/services/acquisition_recipe.py
.py
22d85489daf3bc05
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Approval policy evaluation and decision recording.""" from datetime import UTC, datetime from pathlib import Path from typing import TYPE_CHECKING from uuid import uuid4 if TYPE_CHECKING: from carmel.schemas.action_state import PlanPro...
DanaResearchGroup/Carmel
carmel/services/approvals.py
.py
fbe00fa10af4f396
7
0
"""Cheminformatics helpers backed by the optional ``rdkit`` dependency. Every function here fails SOFT: a missing ``rdkit`` install or an unparseable input returns ``None``, never an exception. ``rdkit`` is imported lazily inside each function so importing this module never fails when the optional dependency is absent...
DanaResearchGroup/Carmel
carmel/services/chem.py
.py
d47954fee70d772a
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Typed bridge between :class:`~carmel.schemas.datasets.ConditionSetEnvelope` and the content-addressed store in :mod:`carmel.services.dataset_store`. The sibling of :mod:`carmel.services.dataset_bridge`, and separate from it for the same reas...
DanaResearchGroup/Carmel
carmel/services/condition_set_bridge.py
.py
891aa780b0a5d62e
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Typed bridge between :class:`~carmel.schemas.datasets.DatasetEnvelope` and the content-addressed store in :mod:`carmel.services.dataset_store`. ``dataset_store`` is deliberately schema-blind: it hashes, stores, and loads whatever plain ``dic...
DanaResearchGroup/Carmel
carmel/services/dataset_bridge.py
.py
e9a38adb7a2bf254
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Append-only decision log writer.""" import json from datetime import UTC, datetime from pathlib import Path from typing import Any from carmel.logger import get_logger from carmel.services.state_machine import workspace_lock _log = get_lo...
DanaResearchGroup/Carmel
carmel/services/decision_log.py
.py
cb630251b1e4073b
7
0
# Copyright 2026 Dana Research Group # SPDX-License-Identifier: Apache-2.0 """Pure-Python SVG rendering for compute selection display. These renderers produce static SVG strings/files that visualize which species, reactions, and pressure-dependent networks T3 selected to be computed. The output is deterministic and p...
DanaResearchGroup/Carmel
carmel/services/drawing.py
.py
dc15a3f5acb5bc3d
7
0
#!/usr/bin/env python3 """ AI code review script used by GitHub Actions PR Review workflow. """ import json import os import subprocess import traceback MAX_DIFF_LENGTH = 18000 REVIEW_PATHS = [ '*.py', '*.md', 'README.md', 'AGENTS.md', 'docs/**', '.github/PULL_REQUEST_TEMPLATE.md', 'requir...
DT-1983/daily-stock-board
.github/scripts/ai_review.py
.py
1ae8fe1b80a72af4
7
0
"""Telegram 只推「反轉/警示」(美股+台股)+ 附完整 HTML 看板。 警示 = 🔴 賣出 / 🟢 買進;反轉 = 訊號 vs 上次不同(state/signals.json) 其餘(⚪觀望)不推,完整資料看 HTML 附件。 🔴🔴 **這支不只是通知程式,它是訊號狀態的唯一寫入者。要精簡 Telegram 時千萬別停掉它。** 本檔結尾會寫兩個檔(見 main 最後幾行): state/signals.json ← investment_chief 的「AI綜合訊號」材料 state/st_flips_today.json ← researche...
DT-1983/daily-stock-board
alert_telegram.py
.py
0d314ea39f38c288
7
0
# -*- coding: utf-8 -*- """ Auth middleware: protect /api/v1/* when admin auth is enabled. """ from __future__ import annotations import logging from typing import Callable from fastapi import Request from fastapi.responses import JSONResponse from starlette.middleware.base import BaseHTTPMiddleware from src.auth i...
DT-1983/daily-stock-board
api/middlewares/auth.py
.py
406fa711ea4e9266
7
0
# -*- coding: utf-8 -*- """Authentication endpoints for Web admin login.""" from __future__ import annotations import logging import os from fastapi import APIRouter, Request from fastapi.responses import JSONResponse, Response from pydantic import BaseModel, Field from api.deps import get_system_config_service fro...
DT-1983/daily-stock-board
api/v1/endpoints/auth.py
.py
93c8239a09d8d37d
7
0
# -*- coding: utf-8 -*- """Shared helpers for API error responses.""" from __future__ import annotations from typing import Any from fastapi import HTTPException from fastapi.responses import JSONResponse def error_body(error: str, message: str, *, detail: Any = None) -> dict[str, Any]: body: dict[str, Any] = ...
DT-1983/daily-stock-board
api/v1/errors.py
.py
307745cff5961ca0
7
0
# -*- coding: utf-8 -*- """Run-flow snapshot API contract.""" from __future__ import annotations from typing import Any, Dict, List, Literal, Optional from pydantic import BaseModel, ConfigDict, Field RunFlowStatus = Literal[ "pending", "running", "success", "failed", "degraded", "fallback"...
DT-1983/daily-stock-board
api/v1/schemas/run_flow.py
.py
5e95d0b3062d2671
7
0
"""Billing and subscription management endpoints.""" import json import logging from datetime import datetime, timedelta from uuid import UUID import stripe from fastapi import APIRouter, Depends, HTTPException, Request from sqlalchemy.orm import Session from stripe import StripeError, SignatureVerificationError fro...
rajath-raman/omnara
backend/api/billing.py
.py
72285cfbbf8db704
7
0
"""Mobile billing endpoints for iOS and Android subscriptions.""" import json import logging from datetime import datetime, timezone from typing import Optional from uuid import UUID import httpx from fastapi import APIRouter, Request, HTTPException, Depends from sqlalchemy.orm import Session from backend.auth.depen...
rajath-raman/omnara
backend/api/mobile_billing.py
.py
ccc8d7aa17340f01
7
0
"""Push notification endpoints""" from typing import List from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from sqlalchemy.exc import IntegrityError from pydantic import BaseModel from uuid import UUID from datetime import datetime, timezone import logging from backend.auth.dep...
rajath-raman/omnara
backend/api/push_notifications.py
.py
6c972cb8cc5508a8
7
0
""" User Settings API endpoints for managing notification preferences and other user settings. """ import re from fastapi import APIRouter, Depends, HTTPException from shared.database.models import User from shared.database.session import get_db from sqlalchemy.orm import Session from ..auth.dependencies import get_c...
rajath-raman/omnara
backend/api/user_settings.py
.py
65c9f23d7892d13d
7
0
import sys from pathlib import Path from uuid import UUID from datetime import datetime, timedelta # Add parent directory to path to import shared module sys.path.append(str(Path(__file__).parent.parent.parent)) from fastapi import Depends, HTTPException, Request from fastapi.security import HTTPAuthorizationCredenti...
rajath-raman/omnara
backend/auth/dependencies.py
.py
0a956eae7c775c91
7
0
import hashlib import sys from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any # Add parent directory to path to import shared module sys.path.append(str(Path(__file__).parent.parent.parent)) from jose import JWTError, jwt from shared.config.settings import settings def...
rajath-raman/omnara
backend/auth/jwt_utils.py
.py
d92a2d8591960f29
7
0
import sys from pathlib import Path # Add parent directory to path to import shared module sys.path.append(str(Path(__file__).parent.parent.parent)) from shared.config.settings import settings from supabase import Client, create_client def get_supabase_client() -> Client: """Get Supabase client with service rol...
rajath-raman/omnara
backend/auth/supabase_client.py
.py
89d5f7e86f58d034
7
0
import sys from pathlib import Path from uuid import UUID # Add parent directory to path to import shared module sys.path.append(str(Path(__file__).parent.parent.parent)) from shared.database.models import User from sqlalchemy.orm import Session from .supabase_client import get_supabase_client def sync_user_from_s...
rajath-raman/omnara
backend/auth/utils.py
.py
9c86a26383797803
7
0
"""FastAPI backend for Agent Dashboard""" import logging import os from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware import sentry_sdk from shared.config import settings from .api import ( agents, user_agents, push_notifications, billing, mobile_billing, user_setti...
rajath-raman/omnara
backend/main.py
.py
fa7b7a880806584e
7
0
"""Pytest configuration and fixtures for backend tests.""" import os import pytest from datetime import datetime, timezone from uuid import uuid4 from unittest.mock import Mock from fastapi.testclient import TestClient from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from testcontainers.po...
rajath-raman/omnara
backend/tests/conftest.py
.py
b3091522eeed27b5
7.5
0
"""Tests for authentication endpoints.""" from datetime import datetime, timezone from uuid import uuid4 from unittest.mock import patch, Mock from shared.database.models import User, APIKey class TestAuthEndpoints: """Test authentication endpoints.""" def test_get_session_unauthenticated(self, client): ...
rajath-raman/omnara
backend/tests/test_auth.py
.py
0f313143dec06118
7.5
0
"""Comprehensive tests for the unified message system.""" from datetime import datetime, timezone from uuid import uuid4 import time from shared.database.models import Message, AgentInstance from shared.database.enums import AgentStatus, SenderType class TestMessageSystem: """Test the core message system functi...
rajath-raman/omnara
backend/tests/test_message_system.py
.py
98a812b734399bca
7.5
0
"""Handler for Claude session resets (/clear and /reset commands)""" import time from pathlib import Path from typing import Optional, Tuple class SessionResetHandler: """Handles detection and recovery from Claude session resets""" def __init__(self, log_func=None): """Initialize the handler ...
rajath-raman/omnara
integrations/cli_wrappers/claude_code/session_reset_handler.py
.py
dcab58690d5ae5cb
7
0
"""Main client for interacting with the Omnara Agent Dashboard API.""" import time import uuid from typing import Optional, Dict, Any, Union, List from urllib.parse import urljoin import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from .exceptions import AuthenticationErro...
rajath-raman/omnara
omnara/sdk/client.py
.py
f9eb2004b93110fe
7
0
"""Utility functions for the Omnara SDK.""" import uuid from typing import Optional, Union, Dict, Any def validate_agent_instance_id( agent_instance_id: Optional[Union[str, uuid.UUID]], ) -> str: """Validate and convert agent_instance_id to string. Args: agent_instance_id: UUID string, UUID obje...
rajath-raman/omnara
omnara/sdk/utils.py
.py
87ca80827849ee0a
7
0
#!/usr/bin/env python3 """ Pre-commit hook to check if database schema changes require a new migration. This script detects changes to SQLAlchemy models and ensures that a corresponding Alembic migration has been created in the same commit. """ import subprocess import sys from pathlib import Path def get_staged_fi...
rajath-raman/omnara
scripts/check-migration-needed.py
.py
821af76066a3a0f8
7
0
"""Unified server combining MCP and FastAPI functionality. This server provides: - MCP tools at /mcp/ endpoint (log_step, ask_question, end_session) - REST API endpoints at /api/v1/* - Shared JWT authentication for both interfaces """ import logging from contextlib import asynccontextmanager import traceback from fa...
rajath-raman/omnara
servers/app.py
.py
10eb78186c7ccbf6
7
0
# ruff: noqa import contextlib import dataclasses import datetime import faulthandler import os import signal import time from moviepy.editor import ImageSequenceClip import numpy as np from openpi_client import image_tools from openpi_client import websocket_client_policy import pandas as pd from PIL import Image fro...
YannLau/tron2_openpi_comments
examples/droid/main.py
.py
373302967f231e3a
7
0
import dataclasses import enum import logging import pathlib import time import numpy as np from openpi_client import websocket_client_policy as _websocket_client_policy import polars as pl import rich import tqdm import tyro logger = logging.getLogger(__name__) class EnvMode(enum.Enum): """Supported environmen...
YannLau/tron2_openpi_comments
examples/simple_client/main.py
.py
3f4445762376cfa2
7
0
import numpy as np from PIL import Image def convert_to_uint8(img: np.ndarray) -> np.ndarray: """Converts an image to uint8 if it is a float image. This is important for reducing the size of the image when sending it over the network. """ if np.issubdtype(img.dtype, np.floating): img = (255 *...
YannLau/tron2_openpi_comments
packages/openpi-client/src/openpi_client/image_tools.py
.py
d48b4bd7f44e79fe
7
0
from typing_extensions import override from openpi_client import base_policy as _base_policy from openpi_client.runtime import agent as _agent class PolicyAgent(_agent.Agent): """An agent that uses a policy to determine actions.""" def __init__(self, policy: _base_policy.BasePolicy) -> None: self._p...
YannLau/tron2_openpi_comments
packages/openpi-client/src/openpi_client/runtime/agents/policy_agent.py
.py
c4d63952d1954bd4
7
0
import abc class Environment(abc.ABC): """An Environment represents the robot and the environment it inhabits. The primary contract of environments is that they can be queried for observations about their state, and have actions applied to them to change that state. """ @abc.abstractmethod d...
YannLau/tron2_openpi_comments
packages/openpi-client/src/openpi_client/runtime/environment.py
.py
1c12e5054b3401de
7
0
import logging import threading import time from openpi_client.runtime import agent as _agent from openpi_client.runtime import environment as _environment from openpi_client.runtime import subscriber as _subscriber class Runtime: """The core module orchestrating interactions between key components of the system...
YannLau/tron2_openpi_comments
packages/openpi-client/src/openpi_client/runtime/runtime.py
.py
3daa242a9ce61ffb
7
0
import logging import time from typing import Dict, Optional, Tuple from typing_extensions import override import websockets.sync.client from openpi_client import base_policy as _base_policy from openpi_client import msgpack_numpy class WebsocketClientPolicy(_base_policy.BasePolicy): """Implements the Policy in...
YannLau/tron2_openpi_comments
packages/openpi-client/src/openpi_client/websocket_client_policy.py
.py
c15addb2695db68b
7
0
"""Compute normalization statistics for a config. This script is used to compute the normalization statistics for a given config. It will compute the mean and standard deviation of the data in the dataset and save it to the config assets directory. """ import numpy as np import tqdm import tyro import openpi.models....
YannLau/tron2_openpi_comments
scripts/compute_norm_stats.py
.py
5c0405a5c43d124c
7
0
import dataclasses import enum import inspect import logging import os import socket import time import jax import numpy as np import tyro from openpi.policies import policy as _policy from openpi.policies import policy_config as _policy_config from openpi.serving import websocket_policy_server from openpi.shared imp...
YannLau/tron2_openpi_comments
scripts/serve_policy.py
.py
d61f11dcbb08ec07
7
0
# Copyright 2024 Big Vision Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
YannLau/tron2_openpi_comments
src/openpi/models/gemma.py
.py
7e42ada4ae7e9995
7
0
# Copyright 2024 Big Vision Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
YannLau/tron2_openpi_comments
src/openpi/models/gemma_fast.py
.py
563c6e1ffd8afa31
7
0
import math import re import flax.linen as nn import flax.struct as struct import jax.numpy as jnp import openpi.shared.array_typing as at @struct.dataclass class LoRAConfig: """Configuration for LoRA.""" # LoRA rank. rank: int # LoRA scaling factor. alpha: float = 1.0 # Initialization func...
YannLau/tron2_openpi_comments
src/openpi/models/lora.py
.py
ced28716950c34d8
7
0
"""Main blueprint for top-level pages.""" import logging from flask import Blueprint, render_template import services.movie_service as movie_service logger = logging.getLogger(__name__) main = Blueprint("main", __name__) @main.route("/") def index(): """Render the homepage using the active movie service.""" ...
AaryaMody1301/Movie-Recommendation-System
blueprints/main.py
.py
68dbfac554fe7ee1
7
0
import os from dotenv import load_dotenv load_dotenv() def _env_bool(name, default=False): """Parse common environment boolean values deterministically.""" value = os.environ.get(name) if value is None: return bool(default) return value.strip().lower() in {"1", "true", "yes", "on"} class Co...
AaryaMody1301/Movie-Recommendation-System
config.py
.py
bfce7203a867bd8a
7
0
"""Database extension and initialization helpers.""" import sqlite3 import click from flask.cli import with_appcontext from flask_sqlalchemy import SQLAlchemy from sqlalchemy import MetaData, event from sqlalchemy.engine import Engine NAMING_CONVENTION = { "ix": "ix_%(column_0_label)s", "uq": "uq_%(table_nam...
AaryaMody1301/Movie-Recommendation-System
database/db.py
.py
b2d8174745395f4d
7
0
"""Collaborative filtering using Surprise SVD. The model consumes application-user ratings using one stable raw-ID type (integers). Surprise owns conversion between those raw IDs and its internal integer IDs through the fitted Trainset. The wrapper keeps that Trainset alongside the fitted algorithm so recommendation/...
AaryaMody1301/Movie-Recommendation-System
models/collaborative_filtering.py
.py
f2180b5040d1841c
7
0
"""Application logging configuration helpers.""" from __future__ import annotations from datetime import datetime, timezone import json import logging import sys from typing import Optional class JsonFormatter(logging.Formatter): """Emit one JSON object per log record for production log collectors.""" def ...
AaryaMody1301/Movie-Recommendation-System
observability.py
.py
66e1ebe4916170bf
7
0
"""Pre-push plumbing guard: is this push going where the repo says it may? The content gates (``check_committed_identifiers.py``) answer "may these bytes be published". They cannot answer "may this repository be published *here*, by this identity, at this visibility" — the plumbing accident class: * pushing a private...
hraedon/acme-adcs-ra
scripts/check_publication_plumbing.py
.py
1873f095a7f20392
7
0
#!/usr/bin/env python3 """Check or update the pinned InstallVerifyLib.ps1 digest in each entry point. Five privileged PowerShell entry points authenticate ``scripts/lib/ InstallVerifyLib.ps1`` against a digest literal before executing it, because that library is the code which authenticates the privileged script tree ...
hraedon/acme-adcs-ra
scripts/lib_digest.py
.py
7394c6aa0e0fee79
7
0
#!/usr/bin/env python3 """Read-only revocation reconciliation (WI-017). This tool answers one question: **is everything the RA believes is revoked actually revoked at the CA?** It is the control an operator leans on to close a revocation incident, so the way it fails matters as much as the way it passes. The 2026-08-...
hraedon/acme-adcs-ra
scripts/reconcile_revocation.py
.py
2b6b6705f9471b7b
7
0