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 |
|---|---|---|---|---|---|---|
import json
import requests
from time import sleep
import logging
from typing import Dict, Optional
class llm_API:
def __init__(self, api_url: str):
self.api_url = api_url
def request(self, data: Dict, max_retries: int = 3, retry_delay: int = 2) -> Optional[str]:
for attempt in range(max_retr... | SharkSpicy-NLP/Beyond-Factual-Knowledge | data_generate/utils.py | .py | c2ee177df3034501 | 7.45 | 7 |
#!/usr/bin/env python3
# Copyright 2024 OASR Authors
# SPDX-License-Identifier: Apache-2.0
"""Measure engine throughput, latency, and real-time factor.
``--max-batch-size`` controls the offline micro-batch width or the streaming
concurrency cap. See ``--help`` for decode families and output options.
"""
import argpar... | chiendb97/oasr | benchmarks/bench_engine.py | .py | 338a0a08420ae3ac | 7.64 | 18 |
"""OASR benchmark routine registry.
Each routine module exposes:
- SUBROUTINES: list[str] — available sub-kernel names
- parse_args(parser) — add routine-specific CLI args
- run_test(args, output) — run a single benchmark test
- get_default_configs() — default configs per subroutine... | chiendb97/oasr | benchmarks/routines/__init__.py | .py | 96ad286faf797457 | 7.64 | 18 |
"""
API key authentication for flacfetch HTTP API.
"""
import os
from typing import Optional
from fastapi import HTTPException, Security
from fastapi.security import APIKeyHeader
# API key header
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
def get_api_key() -> Optional[str]:
"""Get the con... | nomadkaraoke/flacfetch | flacfetch/api/auth.py | .py | 8da95cf3c20e686e | 7.5 | 9 |
"""
Flacfetch HTTP API - FastAPI application.
This module provides the main FastAPI application for the flacfetch HTTP API,
enabling remote search and download of audio files.
Usage:
# Run directly
uvicorn flacfetch.api.main:app --host 0.0.0.0 --port 8080
# Or via CLI
flacfetch serve --port 8080
... | nomadkaraoke/flacfetch | flacfetch/api/main.py | .py | f4078dd52729c685 | 7.5 | 9 |
"""
Cache management endpoints for flacfetch HTTP API.
"""
import logging
from typing import Optional
from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
from ..auth import verify_api_key
from ..services import get_search_cache_service
logger = logging.getLogger(__name__)
router = APIRouter(... | nomadkaraoke/flacfetch | flacfetch/api/routes/cache.py | .py | 516568a021bc430a | 7.5 | 9 |
"""
Download endpoints for flacfetch HTTP API.
"""
import logging
import os
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException
from fastapi.responses import FileResponse
from ..auth import verify_api_key
from ..models import (
CheckYoutubeRequest,
CheckYoutubeResponse,
DownloadByIdRequ... | nomadkaraoke/flacfetch | flacfetch/api/routes/download.py | .py | 07b4ae220aefe195 | 7.5 | 9 |
"""
Torrent management endpoints for flacfetch HTTP API.
"""
import logging
import os
from fastapi import APIRouter, Depends, HTTPException, Query
from ..auth import verify_api_key
from ..models import (
CleanupRequest,
CleanupResponse,
TorrentDeleteResponse,
TorrentInfo,
TorrentListResponse,
... | nomadkaraoke/flacfetch | flacfetch/api/routes/torrents.py | .py | 4695ac5018307358 | 7.5 | 9 |
"""
Flacfetch API services.
"""
from datetime import datetime, timezone
from typing import Optional
from .disk_manager import DiskManager, get_disk_manager
from .download_manager import DownloadManager, get_download_manager
from .health_check import DeepHealthService, get_deep_health_service
from .search_cache import ... | nomadkaraoke/flacfetch | flacfetch/api/services/__init__.py | .py | a64cb30610643ad6 | 7.5 | 9 |
"""
Search result caching service using Google Cloud Storage.
Caches search results by normalized artist+title with configurable TTL.
"""
import asyncio
import hashlib
import json
import logging
import os
import re
import unicodedata
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, time... | nomadkaraoke/flacfetch | flacfetch/api/services/search_cache.py | .py | ebb9e65519aaf980 | 7.5 | 9 |
"""
Categorization logic for organizing search results into meaningful groups.
This module provides functionality to categorize and deduplicate release results
for cleaner, more organized display in the CLI.
"""
from dataclasses import dataclass
from typing import Optional
from .models import Release, TrackQuery
@... | nomadkaraoke/flacfetch | flacfetch/core/categorize.py | .py | 4bc4afa28e22d0fa | 7.5 | 9 |
import re
from difflib import SequenceMatcher
def clean_filename(filename: str) -> str:
# Remove file extension
if '.' in filename:
filename = filename.rsplit('.', 1)[0]
# Remove track numbers like "01 - ", "01. ", "1-", "A1 "
filename = re.sub(r'^(\d{1,3}[ .-]+)+', '', filename)
filename ... | nomadkaraoke/flacfetch | flacfetch/core/matching.py | .py | b49d55b92cb6454d | 7.5 | 9 |
from dataclasses import dataclass
from enum import Enum, auto
from typing import Optional
class AudioFormat(Enum):
FLAC = auto()
MP3 = auto()
AAC = auto()
WAV = auto()
OPUS = auto()
VORBIS = auto() # OGG Vorbis - Spotify source format (320kbps, converted to FLAC)
OTHER = auto()
class Med... | nomadkaraoke/flacfetch | flacfetch/core/models.py | .py | b835363ea9d4172c | 7.5 | 9 |
"""Browser lifecycle management using Patchright (anti-detection Playwright fork)."""
import logging
import os
from pathlib import Path
logger = logging.getLogger(__name__)
# Default profile directory (persistent disk on GCE)
DEFAULT_PROFILE_DIR = "/mnt/flacfetch-data/browser-profiles/google"
def get_profile_dir() ... | nomadkaraoke/flacfetch | flacfetch/credential_keeper/browser.py | .py | 2ffe38fde5ad40f1 | 7.5 | 9 |
"""librespot credential keeper.
Mints reusable Spotify credentials for librespot by driving its *native* OAuth
flow (``librespot --enable-oauth``) through the persistent, Google-logged-in
browser. The resulting ``credentials.json`` is what the Spotify downloader hands
to librespot via ``-c``.
Why this exists: Spotify... | nomadkaraoke/flacfetch | flacfetch/credential_keeper/librespot.py | .py | e08ba739b9dadbf6 | 7.5 | 9 |
"""Probe exported YouTube cookies with a real yt-dlp extraction.
The keeper's browser can report "Google session active - logged in" while
YouTube has already invalidated the exported cookie snapshot server-side
(observed on the netcup datacenter IP 2026-08-23/24: exports went dead within
hours of a fresh browser laun... | nomadkaraoke/flacfetch | flacfetch/credential_keeper/probe.py | .py | c4765319a4cbba63 | 7.5 | 9 |
"""Spotify token keeper - performs OAuth flow via 'Continue with Google' in the browser."""
import json
import logging
import os
from urllib.parse import parse_qs, urlencode, urlparse
import httpx
logger = logging.getLogger(__name__)
FLACFETCH_API_URL = "http://localhost:8080"
def _build_oauth_url() -> str:
""... | nomadkaraoke/flacfetch | flacfetch/credential_keeper/spotify.py | .py | cb05c9b6892e31ca | 7.5 | 9 |
"""Spotify downloader for flacfetch.
This module provides download functionality for Spotify tracks using:
- librespot binary (Rust) with pipe backend for audio capture
- Spotify Web API (via spotipy) for playback control
- ffmpeg for PCM to FLAC conversion
Output: FLAC at 44.1kHz/16-bit (CD quality)
"""
import os
i... | nomadkaraoke/flacfetch | flacfetch/downloaders/spotify.py | .py | 1ddde4b120ddaeac | 7.5 | 9 |
"""Coordinates concurrent downloads that resolve to the SAME torrent.
Transmission dedupes an ``add`` by info-hash, so several jobs that each want a
different file from one album torrent all attach to a *single* torrent instance
in the daemon. flacfetch was originally built assuming every download owned its
torrent ex... | nomadkaraoke/flacfetch | flacfetch/downloaders/torrent_coordinator.py | .py | 267bab2b7a58a472 | 7.5 | 9 |
import logging
import os
import shutil
import tempfile
import time
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Optional
import yt_dlp # type: ignore
from ..core.interfaces import Downloader
from ..core.models import Release
logger = logging.getLogger(__name__)
# Abuse... | nomadkaraoke/flacfetch | flacfetch/downloaders/youtube.py | .py | edc36f841ef9eb50 | 7.5 | 9 |
"""Provider for OPS private music tracker."""
from ..core.models import Release, TrackQuery
from .gazelle import GazelleProvider
class OPSProvider(GazelleProvider):
"""Provider for OPS private music tracker.
Requires both an API key and base URL to be provided.
The base URL should be set via the OPS_API... | nomadkaraoke/flacfetch | flacfetch/providers/ops.py | .py | fc9d5d6cd9bbd93a | 7.5 | 9 |
"""Provider for RED private music tracker."""
from ..core.models import Release, TrackQuery
from .gazelle import GazelleProvider
class REDProvider(GazelleProvider):
"""Provider for RED private music tracker.
Requires both an API key and base URL to be provided.
The base URL should be set via the RED_API... | nomadkaraoke/flacfetch | flacfetch/providers/red.py | .py | d2c0a421f88736de | 7.5 | 9 |
"""Spotify provider for flacfetch.
This module provides search functionality for Spotify using the official Web API
via spotipy. Requires Spotify Premium for downloading (handled by downloader).
Authentication: OAuth2 via spotipy (browser-based login, cached automatically)
Quality: CD-quality FLAC output (44.1kHz/16-... | nomadkaraoke/flacfetch | flacfetch/providers/spotify.py | .py | 41b3c028d42e41a0 | 7.5 | 9 |
#!/usr/bin/env python3
"""Export public GeoTask Core files according to public-manifest.yaml.
Usage:
python .release/export_public.py [--dry-run] [--clean] OUTPUT_DIR
Reads ``.release/public-manifest.yaml``, considers repository-tracked files only,
copies include-matched files to OUTPUT_DIR, respects exclude patt... | stpku/GeoTask | .release/export_public.py | .py | 086000fb0dd0ec27 | 7.42 | 6 |
#!/usr/bin/env python3
"""Generate and verify SHA-256 manifest for a public export directory.
Usage:
python .release/hash_public_export.py generate EXPORT_DIR [OUTPUT]
python .release/hash_public_export.py verify EXPORT_DIR MANIFEST
Does NOT access network. Excludes dist/, egg-info, pycache, pytest_cache.
"""... | stpku/GeoTask | .release/hash_public_export.py | .py | b733392f7d5c2739 | 7.42 | 6 |
"""Authenticated OpenAI client resolution kept outside GeoTask Core."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Protocol, runtime_checkable
class OpenAIClientResolutionError(ValueError):
"""Raised when an opaque authorization reference cannot resolve a client."""
... | stpku/GeoTask | examples/model_adapters/openai_responses/src/geotask_openai_responses_adapter/client.py | .py | 99bc4d72095360dd | 7.42 | 6 |
"""Deterministic no-network model provider used by the public Adapter skeleton."""
from __future__ import annotations
from collections.abc import Mapping
from .contracts import StructuredModelInvocation, StructuredModelResult
class MockStructuredModelProvider:
"""Return one preconfigured structured result with... | stpku/GeoTask | examples/model_adapters/provider_neutral/src/geotask_model_adapter_reference/mock_provider.py | .py | d75773e77018ba19 | 7.42 | 6 |
#!/usr/bin/env python3
"""
Audit GitHub Actions workflows for mutable selectors.
Hard-fails on:
- `uses: <action>@main`, `@master`, `@develop`, `@latest`
- `uses: <action>@v<N>` or `@v<N>.<M>` (loose major / minor selectors;
tags are mutable and the action publisher can move them)
- `go-version: stable` / `l... | leanprover/lean-eval-submissions | scripts/action_pin_audit.py | .py | 742cebd02c29b15a | 7.42 | 6 |
#!/usr/bin/env python3
"""Explain *why* the `evaluate` job failed, for the comment `notify` posts.
`notify` used to tell every submitter that "the most common cause is that
`Submission.lean` failed to compile". That hint is close to never right. A
submission whose proof does not compile is not an error at all as far... | leanprover/lean-eval-submissions | scripts/classify_evaluate_failure.py | .py | 831f982fe799bd31 | 7.42 | 6 |
#!/usr/bin/env python3
"""Separate and canonicalize the large historical replay image layers."""
from __future__ import annotations
import argparse
import os
import pathlib
CANONICAL_MTIME_NS = 0
class LayerPreparationError(ValueError):
"""The staged runtime tree cannot be represented by the layer contract.""... | leanprover/lean-eval-submissions | scripts/prepare_historical_image_layers.py | .py | c27ba386ae791304 | 7.42 | 6 |
#!/usr/bin/env python3
"""Close `submission`-labeled issues that the Submission workflow never
responded to. See .github/workflows/submission-reconciler.yml."""
from __future__ import annotations
import datetime as dt
import json
import os
import subprocess
import sys
ORPHAN_THRESHOLD = dt.timedelta(hours=7)
BOT_AUTH... | leanprover/lean-eval-submissions | scripts/reconcile_orphan_submissions.py | .py | 08d8213c10574dab | 7.42 | 6 |
#!/usr/bin/env python3
"""PreToolUse hook: require a 🤖 AI marker in the BODY of gh commands that post
to GitHub (``gh pr|issue comment|create``, ``gh pr review``).
Hardened over the original raw-``grep`` version (PR #623 review):
* It only fires on an *actual* ``gh`` invocation, not a mention. Tokenising with
``sh... | tenax-lab/tenax | .claude/hooks/ai_comment_marker.py | .py | bd0e6fd16d9a346c | 7.45 | 7 |
"""Backend selection and configuration for Tenax benchmarks.
Must call ``configure_backend`` **before** any ``import jax``.
"""
from __future__ import annotations
import os
_BACKEND_MAP = {
"cpu": "cpu",
"cuda": "cuda",
"gpu": "cuda",
"tpu": "tpu",
"metal": "METAL",
}
def configure_backend(bac... | tenax-lab/tenax | benchmarks/backend.py | .py | 7b6778154f60394c | 7.45 | 7 |
"""Benchmark: compilation time for Python-loop CTM AD."""
from __future__ import annotations
import time
import jax
import jax.numpy as jnp
from tenax.algorithms._ctm_energy_ad import ctm_energy_implicit
from tenax.algorithms._ctm_tensor_convergence import SINGLE_SITE_NEIGHBORS
from tenax.algorithms.ipeps import he... | tenax-lab/tenax | benchmarks/bench_compile_time.py | .py | 3c2df97d5a4055eb | 7.45 | 7 |
"""DMRG benchmark cases."""
from __future__ import annotations
import jax.numpy as jnp
from tenax import (
DMRGConfig,
build_mpo_heisenberg,
build_random_symmetric_mps,
dmrg,
)
_SIZES = {
"small": {"L": 20, "chi": 32, "sweeps": 5, "init_bond_dim": 8},
"medium": {"L": 40, "chi": 64, "sweeps":... | tenax-lab/tenax | benchmarks/bench_dmrg.py | .py | 2ad04535563b2d77 | 7.45 | 7 |
#!/usr/bin/env python
"""A/B benchmark: GMRES backward with vs without diagonal scaling preconditioner.
Matches YASTN benchmark parameters: D=2, chi=16, Heisenberg.
Reports per-step wall time (forward+backward) for both configurations.
Usage:
JAX_PLATFORM_NAME=cpu python benchmarks/bench_gmres_precond.py
JAX_... | tenax-lab/tenax | benchmarks/bench_gmres_precond.py | .py | ed14f2801395a4d6 | 7.45 | 7 |
"""iPEPS AD optimization benchmark cases."""
from __future__ import annotations
import jax.numpy as jnp
from tenax import CTMConfig, iPEPSConfig, optimize_gs_ad, sublattice_rotate_gate
_SIZES = {
"small": {"D": 2, "chi_ctm": 8, "gs_steps": 20, "lr": 1e-3},
"medium": {"D": 2, "chi_ctm": 16, "gs_steps": 30, "... | tenax-lab/tenax | benchmarks/bench_ipeps_ad.py | .py | 08ddfcf2e806cded | 7.45 | 7 |
"""CLI entry point for Tenax benchmarks.
Usage::
python -m benchmarks.run --backend cpu --algorithm trg --size small --trials 1
python -m benchmarks.run --backend cuda --algorithm all --size all -o results.json
python -m benchmarks.run --list-backends
"""
from __future__ import annotations
import argpar... | tenax-lab/tenax | benchmarks/run.py | .py | 74f31d7c7a95780d | 7.45 | 7 |
"""Timing infrastructure for Tenax benchmarks."""
from __future__ import annotations
import time
import traceback
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any
import jax.numpy as jnp
@dataclass
class BenchmarkResult:
algorithm: str = ""
size_label: st... | tenax-lab/tenax | benchmarks/runner.py | .py | 452eb8103ff2f7e3 | 7.45 | 7 |
"""Re-test 2-site ``gs_stall_recovery="noise"`` on post-#494 energy (issue #520).
The ``"reset"`` default for the 2-site path was set in PR #300 (2026-04-11)
with the rationale "noise interacts pathologically with non-variational CTM
regions on 2-site, see #298". That observation was made on a 2-site bipartite
energy... | tenax-lab/tenax | benchmarks/stall_recovery_noise_vs_reset_520.py | .py | 9b173a0ea33ffb4b | 7.45 | 7 |
"""Production-scale stall-runaway regression canary (issue #456).
Runs a non-monkeypatched 2-site implicit-AD Heisenberg optimization and
asserts that the stall counter stays bounded by ``gs_stall_recovery_retries``
and wall-clock stays under a budget. Complements the structural unit tests
in ``tests/test_ipeps_stall... | tenax-lab/tenax | benchmarks/stall_runaway_canary.py | .py | bf5c373764583f74 | 7.45 | 7 |
"""F3 microbench: cold compile + 1 backward, warm 2 backwards.
Run twice — once on F2 (baseline), once on F3 (this branch). Report
JSON to stdout for easy diff.
"""
from __future__ import annotations
import json
import os
import time
import jax
import jax.numpy as jnp
# Force CPU complex128 for apples-to-apples wi... | tenax-lab/tenax | benchmarks/varipeps_compare/microbench_f3.py | .py | 34c4c70ff91252ae | 7.45 | 7 |
"""Cross-library .npz payload — init iPEPS tensor + Hamiltonian gate + metadata."""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
def save_payload(
path: Path | str, *, init: np.ndarray, gate: np.ndarray, meta: dict
) -> None:
"""Write init+gate+meta to a single... | tenax-lab/tenax | benchmarks/varipeps_compare/payload.py | .py | 182f32873b908402 | 7.45 | 7 |
"""Tenax CLI runner for the variPEPS compare benchmark.
Usage:
python -m benchmarks.varipeps_compare.run_tenax \\
--payload payload.npz --path single_site --D 2 --chi 16 \\
--tol 1e-6 --max-steps 100 --out tenax_<key>.json
"""
from __future__ import annotations
import argparse
import json
import ... | tenax-lab/tenax | benchmarks/varipeps_compare/run_tenax.py | .py | 6bcb6bad705c354d | 7.45 | 7 |
"""variPEPS 1.4.2 CLI runner for the compare benchmark.
Usage:
python -m benchmarks.varipeps_compare.run_varipeps \\
--payload payload.npz --path single_site --D 2 --chi 16 \\
--tol 1e-6 --max-steps 100 --out varipeps_<key>.json
"""
from __future__ import annotations
import argparse
import json
i... | tenax-lab/tenax | benchmarks/varipeps_compare/run_varipeps.py | .py | 1607c0160ae1c123 | 7.45 | 7 |
"""Heisenberg gate constructors + path-dependent init dispatcher.
For ``single_site`` (1×1 + sublattice-rotated gate, unconstrained tensor):
SU on the rotated gate converges to the |↑↑⟩ saddle (E=−0.5/site) which
L-BFGS cannot escape (see ``ipeps_optimize.py:1389`` reference-mode
comment). Use random init... | tenax-lab/tenax | benchmarks/varipeps_compare/su_init.py | .py | 3f6bfa35d34f963a | 7.45 | 7 |
"""Sphinx configuration for Tenax documentation."""
import logging
import warnings
from sphinx.ext import intersphinx as _intersphinx
project = "Tenax"
copyright = "2025, Tenax Contributors"
author = "Tenax Contributors"
release = "0.1.0"
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
"sphi... | tenax-lab/tenax | docs/conf.py | .py | 415dc0e18b1b672c | 7.45 | 7 |
#!/usr/bin/env python3
"""Compile-time sweep: dense vs symmetric (batched/unbatched) for #569.
The #569 timing benchmark measured *runtime* of the eager CTM-AD step and found
batching never wins -- but that path is host-dispatch-bound, so it tests the
wrong layer. The reason the code moved to the eager vjp backward in... | tenax-lab/tenax | examples/bench_compile_time_569.py | .py | c4eebd0ecfe09dd9 | 7.45 | 7 |
"""#632 shard-only reach benchmark — dense CTM-AD ``value_and_grad`` (forward CTM +
implicit-AD backward), single-GPU vs N-GPU GSPMD mesh, at large D.
This is the *shard-only* lever (rung-2 GSPMD ``device_mesh``), NOT chunking: the
#632 Increment-2 gate showed chunking the backward is a NO-GO, so the large-D
backward ... | tenax-lab/tenax | examples/bench_ctm_shard_reach_grad.py | .py | a7bdf299d88f9e85 | 7.45 | 7 |
"""Memory feasibility: dense CTM at large D, single-GPU vs N-GPU GSPMD mesh.
Usage (real GPUs):
# 1) find the single-GPU OOM ceiling (one D per process for a clean peak):
CUDA_VISIBLE_DEVICES=0 XLA_PYTHON_CLIENT_PREALLOCATE=false \
uv run python examples/bench_ctm_sharding_memory.py --D 12 --chi 24
... | tenax-lab/tenax | examples/bench_ctm_sharding_memory.py | .py | 99e6fc19243468f5 | 7.45 | 7 |
# NOTE:
# This file is intentionally duplicated in `experiments/V0_sidewalk_param.py`.
# Keeping a local copy here preserves co-design defaults while experiments can
# tune/test costs independently without touching the co-design module.
import numpy as np
import pinocchio as pin
def roundToOdd(x):
'''
Round a ... | huggingface/lerobot-humanoid-design | codesign/hip/V0_sidewalk_param.py | .py | c156b88394d67f42 | 7.45 | 7 |
# NOTE:
# This file is intentionally duplicated in `experiments/V0_walk_param.py`.
# Keeping a local copy here preserves co-design defaults while experiments can
# tune/test costs independently without touching the co-design module.
import numpy as np
import pinocchio as pin
def roundToOdd(x):
'''
Round a numbe... | huggingface/lerobot-humanoid-design | codesign/hip/V0_walk_param.py | .py | 69233534d6e3ede9 | 7.45 | 7 |
# NOTE:
# This file intentionally mirrors `codesign/hip/V0_sidewalk_param.py`.
# Experiments keep a local copy to iterate on task-cost settings without
# changing the reference co-design parameterization.
import numpy as np
import pinocchio as pin
def roundToOdd(x):
'''
Round a number to the nearest odd number... | huggingface/lerobot-humanoid-design | experiments/V0_sidewalk_param.py | .py | 584283ecba45e5d3 | 7.45 | 7 |
# NOTE:
# This file intentionally mirrors `codesign/hip/V0_walk_param.py`.
# Experiments keep a local copy to iterate on task-cost settings without
# changing the reference co-design parameterization.
import numpy as np
import pinocchio as pin
def roundToOdd(x):
'''
Round a number to the nearest odd number.
... | huggingface/lerobot-humanoid-design | experiments/V0_walk_param.py | .py | e249ddf527cc8d3a | 7.45 | 7 |
import tiktoken
import torch
import torch.nn as nn
import torch.nn.functional as F
def rms_norm(x):
"""RMS norm with no learnable params"""
return F.rms_norm(x, (x.size(-1),))
def apply_rotary_emb(x, cos, sin):
"""Utility to rotate embeddings for RoPE"""
x1, x2 = torch.chunk(x, 2, dim=-1)
... | nguyenphuminh/planckgpt | model/core.py | .py | 84e93130401fc747 | 7.45 | 7 |
import torch
from torch.optim.optimizer import Optimizer
# Coefficients for Polar Express (num_iters=5)
POLAR_EXPRESS_COEFFS = [
(8.156554524902461, -22.48329292557795, 15.878769915207462),
(4.042929935166739, -2.808917465908714, 0.5000178451051316),
(3.8916678022926607, -2.772484153217685, 0.506064... | nguyenphuminh/planckgpt | optim/muon.py | .py | a42789290a3dbc6f | 7.45 | 7 |
# -*- coding:utf-8 -*-
# !/usr/bin/env python
import pandas as pd
import requests
import instock.core.tablestructure as tbs
__author__ = 'myh '
__date__ = '2023/5/7 '
def stock_cpbd_em(symbol: str = "688041") -> pd.DataFrame:
"""
东方财富网-个股-操盘必读
https://emweb.securities.eastmoney.com/PC_HSF10/OperationsR... | Vulthen/myhhub-stock-quantitative | stock-quantitative/instock/core/crawling/stock_cpbd.py | .py | f143f911734051f0 | 7.48 | 8 |
# -*- coding:utf-8 -*-
# !/usr/bin/env python
import math
import pandas as pd
import requests
import instock.core.tablestructure as tbs
__author__ = 'myh '
__date__ = '2023/5/9 '
def stock_selection() -> pd.DataFrame:
"""
东方财富网-个股-选股器
https://data.eastmoney.com/xuangu/
:return: 选股器
:rtype: panda... | Vulthen/myhhub-stock-quantitative | stock-quantitative/instock/core/crawling/stock_selection.py | .py | 08699f481b90fd26 | 7.48 | 8 |
"""Entry point for ``python -m adversary_pursuit`` and the ``ap`` CLI."""
import sys
_HELP = """Pivotglass — AI-augmented threat hunting
Usage:
ap Launch the local Pivotglass web cockpit (default)
ap web Launch the local Pivotglass web cockpit
ap chat Launch the t... | jarocki/pivotglass | src/adversary_pursuit/__main__.py | .py | 7d456d3746ca17ec | 7.42 | 6 |
"""Periodic, local, character-voiced configuration guidance.
The advisor never calls a model or provider. It observes only masked local
configuration state, selects one actionable suggestion deterministically, and
labels the result as character narration rather than evidence.
"""
from __future__ import annotations
... | jarocki/pivotglass | src/adversary_pursuit/agent/configuration_advisor.py | .py | 7fcbb76062433e23 | 7.42 | 6 |
"""asyncio event bus for auto-pivoting (SpiderFoot pattern).
When a module discovers artifacts, the event bus can auto-trigger relevant
modules on the new indicators. The ``PivotPolicy`` module is the SOLE gate
authority: before invoking any subscribed callback ``EventBus.publish`` calls
``PivotPolicy.evaluate`` and ... | jarocki/pivotglass | src/adversary_pursuit/core/event_bus.py | .py | 0933ad7a5a43bb54 | 7.42 | 6 |
"""Versioned graph-repository boundary for local-to-Synapse migration."""
from __future__ import annotations
import hashlib
import json
from typing import Any, Literal, Protocol
from pydantic import BaseModel, ConfigDict
from adversary_pursuit.core.investigation_graph import build_investigation_graph
class GraphR... | jarocki/pivotglass | src/adversary_pursuit/core/graph_repository.py | .py | 8f4816a3ccd51e0d | 7.42 | 6 |
from pathlib import Path
import json
class EvidenceReader:
def __init__(self, root_dir="tmp"):
self.root_dir = Path(root_dir)
def _path(self, relative_path):
return self.root_dir / relative_path
def read_json(self, relative_path, optional=False):
"""
Read a JSON evidence ... | AuditOps/auditops-sdk | src/auditops/core/evidence/reader.py | .py | dc708dac1de82b4c | 7.45 | 7 |
from pathlib import Path
from zipfile import ZipFile, ZIP_DEFLATED
import mimetypes
import requests
class Publisher:
"""Uploads audit reports (JSON + PDF) or full audit package to a supported destination."""
VALID_DESTINATIONS = {"s3", "portal", "auditops"}
VALID_PACKAGES = {"full", "json", "pdf"}
d... | AuditOps/auditops-sdk | src/auditops/core/publisher.py | .py | af5baddfe1df6117 | 7.45 | 7 |
from datetime import datetime, timezone
from pathlib import Path
from reportlab.lib.pagesizes import LETTER
from reportlab.platypus import (
SimpleDocTemplate, Table, Paragraph, Spacer, PageBreak, KeepTogether, Image)
from reportlab.lib.styles import getSampleStyleSheet
from .styles import (LABEL_STYLE, VALUE_STYLE... | AuditOps/auditops-sdk | src/auditops/core/reporting/pdf_report_builder.py | .py | 6b1b1fc13fe3dceb | 7.45 | 7 |
from auditops.core.models import Test
import boto3, os, shutil, json, logging
logger = logging.getLogger(__name__)
def create_test(tester, metadata):
test = Test(**metadata)
if not tester.exclusions:
# Exclusions file was not set. Proceed with test
return test
exclusion = tester.exc... | AuditOps/auditops-sdk | src/auditops/core/utils.py | .py | f3f711bde3e1d07f | 7.45 | 7 |
from dataclasses import dataclass, field
@dataclass
class AWSConfig:
"""
Configuration options used by AWSCollector and AWSTester.
Most values represent your organization's desired security baseline.
Tests compare collected AWS evidence against these values.
"""
# Required
in_scope_region... | AuditOps/auditops-sdk | src/auditops/providers/aws/aws_config.py | .py | 8e47c266910383c0 | 7.45 | 7 |
"""Decide, per preview component, whether it needs redeploying on this push.
Everything here is driven by the GitHub API (no local git history required, so
it works with the default shallow checkout). It emits the change signals that
compute_deployment_plan.sh turns into the deploy plan:
1. Whole-PR flags (pr_backend... | abundant-ai/oddish | .github/scripts/preview/find_last_deploys.py | .py | 7f7e4aae5446703d | 7.65 | 19 |
"""Seed the preview branch DB (ODDISH_DATABASE_URL) with a prod subset.
Invoked from prepare_preview_database.sh under `uv run` in the backend
env. The seed engine lives in backend/, so we add it to sys.path here
(the script's own dir is on sys.path, not the cwd).
PREVIEW_SAMPLE_SOURCE_DB_URL (the production DB URL) ... | abundant-ai/oddish | .github/scripts/preview/seed_preview_db.py | .py | 492aa558d5c3a291 | 7.65 | 19 |
"""Create the production Vercel deployment for an exact commit and wait for it.
Why the trigger lives here instead of Vercel's git integration: see the header
of .github/workflows/modal-deploy.yml. frontend/vercel.json disables git
deploys for main, and the Production Deploy workflow runs this script after
the backend... | abundant-ai/oddish | .github/scripts/production/deploy_vercel.py | .py | 08df661cfaa7e6b2 | 7.65 | 19 |
import asyncio
import sys
from logging.config import fileConfig
from pathlib import Path
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import create_async_engine
from alembic import context
# Add src directory to path so we can import oddish
src_path = Path(__file__... | abundant-ai/oddish | backend/alembic/env.py | .py | a07f5b072a8501ec | 7.65 | 19 |
"""add quotas table (per-user daily limit overrides)
Revision ID: add_quotas_table_001
Revises: g1h2i3j4k5l6
Create Date: 2026-07-01 00:00:00.000000
Override-only table: a row overrides the read-time ``DEFAULT_DAILY_QUOTA_USD``
for a ``(org_id, user_id)`` membership; a MISSING row means the member is
enforced at that... | abundant-ai/oddish | backend/alembic/versions/add_quotas_table_001.py | .py | 8f3950701e9e6d7c | 7.65 | 19 |
"""backend-chain mirror of oddish api_key_creator_role_001
Revision ID: apk_role_backend_001
Revises: merge_quota_main_001
Create Date: 2026-07-02 00:00:00.000000
The oddish-chain revision guards on api_keys existing (OSS DBs have no
backend stack), so a fresh install migrated in the documented order (oddish
first, t... | abundant-ai/oddish | backend/alembic/versions/apk_role_backend_001_add_api_key_creator_role.py | .py | d8c3189eccd024cd | 7.65 | 19 |
"""add_clerk_user_id
Revision ID: c4d5e6f7a8b9
Revises: a1b2c3d4e5f6
Create Date: 2026-01-20 12:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "c4d5e6f7a8b9"
down_revision: Union[str, Sequence[str], None] = "a1b2c3d4e5f6"
branch_... | abundant-ai/oddish | backend/alembic/versions/c4d5e6f7a8b9_add_clerk_user_id.py | .py | 1b82358438518181 | 7.65 | 19 |
"""add api_keys.is_internal + chat_sessions.query_api_key_id
Revision ID: chatglobal001
Revises: q3r4s5t6u7v8
Create Date: 2026-06-15 00:00:00.000000
Idempotent: uses ADD COLUMN IF NOT EXISTS / DROP COLUMN IF EXISTS so this
migration is safe to re-run on a DB that already has the columns.
"""
from typing import Sequ... | abundant-ai/oddish | backend/alembic/versions/chatglobal001_chat_global_scope.py | .py | 0748f6d4f01b4c6b | 7.65 | 19 |
"""composite index for the chat-session list query
Revision ID: chatlistidx01
Revises: chatglobal001
Create Date: 2026-06-16 00:00:00.000000
The chat history list (`list_sessions`) filters by (org_id, scope_kind,
scope_id) and orders by last_activity desc. The only prior index was on
org_id alone, so for an org with ... | abundant-ai/oddish | backend/alembic/versions/chatlistidx01_chat_sessions_list_index.py | .py | f876b31a4efc3650 | 7.65 | 19 |
"""add_clerk_org_id
Revision ID: d1e2f3a4b5c6
Revises: c4d5e6f7a8b9
Create Date: 2026-01-21 01:20:00.000000
"""
from typing import Sequence, Union
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "d1e2f3a4b5c6"
down_revision: Union[str, Sequence[str], None] = "c4d5e6f7a8b9"
branch_l... | abundant-ai/oddish | backend/alembic/versions/d1e2f3a4b5c6_add_clerk_org_id.py | .py | 5974f84c9d22cccc | 7.65 | 19 |
"""drop the chat feature's tables
Revision ID: dropchat001
Revises: slack_user_daily_overage_002
Create Date: 2026-08-07 00:00:00.000000
The cc_chat feature (dashboard chat sessions backed by Daytona sandboxes) has
been removed. Drop its three tables; children first so the FK references to
chat_sessions never dangle.... | abundant-ai/oddish | backend/alembic/versions/dropchat001_drop_chat_tables.py | .py | 79617a4d919420d8 | 7.65 | 19 |
"""backfill experiment owners from the exact first trial
Revision ID: expownercreate001
Revises: dropchat001
"""
from __future__ import annotations
from collections.abc import Sequence
from alembic import op
revision: str = "expownercreate001"
down_revision: str | Sequence[str] | None = "dropchat001"
branch_labels... | abundant-ai/oddish | backend/alembic/versions/expownercreate001_backfill_creation_owner.py | .py | 6a41e514f0a29ef0 | 7.65 | 19 |
"""add_deleted_at_columns
Revision ID: f2e3d4c5b6a7
Revises: e2f3a4b5c6d7
Create Date: 2026-01-26 09:32:00.000000
Adds deleted_at columns to auth tables for soft deletes.
"""
from typing import Sequence, Union
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "f2e3d4c5b6a7"
down_revi... | abundant-ai/oddish | backend/alembic/versions/f2e3d4c5b6a7_add_deleted_at_columns.py | .py | de431488b3725cc8 | 7.65 | 19 |
"""add users.github_id"""
from typing import Sequence, Union
from alembic import op
revision: str = "g1h2i3j4k5l6"
down_revision: Union[str, Sequence[str], None] = "t6u7v8w9x0y1"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.e... | abundant-ai/oddish | backend/alembic/versions/g1h2i3j4k5l6_add_user_github_id.py | .py | 53ad1b65d914ea22 | 7.65 | 19 |
"""add_github_username
Revision ID: g3h4i5j6k7l8
Revises: f2e3d4c5b6a7
Create Date: 2026-01-27 10:15:00.000000
"""
from typing import Sequence, Union
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "g3h4i5j6k7l8"
down_revision: Union[str, Sequence[str], None] = "f2e3d4c5b6a7"
branc... | abundant-ai/oddish | backend/alembic/versions/g3h4i5j6k7l8_add_github_username.py | .py | b9fe009269b6f5f6 | 7.65 | 19 |
"""drop_unique_clerk_user_id
Revision ID: h4i5j6k7l8m9
Revises: g3h4i5j6k7l8
Create Date: 2026-01-27 11:15:00.000000
"""
from typing import Sequence, Union
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "h4i5j6k7l8m9"
down_revision: Union[str, Sequence[str], None] = "g3h4i5j6k7l8"... | abundant-ai/oddish | backend/alembic/versions/h4i5j6k7l8m9_drop_unique_clerk_user_id.py | .py | ccefb32cd12b9868 | 7.65 | 19 |
"""add_provider_slots_table
Revision ID: i5j6k7l8m9n0
Revises: h4i5j6k7l8m9
Create Date: 2026-01-30 12:15:00.000000
Creates provider_slots table for worker concurrency leases.
"""
from typing import Sequence, Union
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "i5j6k7l8m9n0"
down... | abundant-ai/oddish | backend/alembic/versions/i5j6k7l8m9n0_add_provider_slots_table.py | .py | 26fb1a6d555397a3 | 7.65 | 19 |
"""drop_experiment_name_uniqueness
Revision ID: j6k7l8m9n0p1
Revises: i5j6k7l8m9n0
Create Date: 2026-01-30 13:00:00.000000
Drop unique constraint for experiments (org_id, name).
"""
from typing import Sequence, Union
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "j6k7l8m9n0p1"
do... | abundant-ai/oddish | backend/alembic/versions/j6k7l8m9n0p1_drop_experiment_name_uniqueness.py | .py | 728481308849180a | 7.65 | 19 |
"""add_queue_slots_table
Revision ID: k7l8m9n0p1q2
Revises: j6k7l8m9n0p1
Create Date: 2026-02-25 10:15:00.000000
"""
from typing import Sequence, Union
# revision identifiers, used by Alembic.
revision: str = "k7l8m9n0p1q2"
down_revision: Union[str, Sequence[str], None] = "j6k7l8m9n0p1"
branch_labels: Union[str, Seq... | abundant-ai/oddish | backend/alembic/versions/k7l8m9n0p1q2_add_queue_slots_table.py | .py | cbbb4c1dc9a1ece3 | 7.65 | 19 |
"""add_task_link
Adds tasks.link column for storing a URL associated with a task run
(e.g. PR, issue, or CI run).
Revision ID: l8m9n0p1q2r3
Revises: k7l8m9n0p1q2
Create Date: 2026-06-02 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
revision: str = "l8m9n0p1q2r3"
down_revision: Unio... | abundant-ai/oddish | backend/alembic/versions/l8m9n0p1q2r3_add_task_link.py | .py | c742684024dc6cb1 | 7.65 | 19 |
"""add user attribution_cache
Revision ID: m9n0p1q2r3s4
Revises: l8m9n0p1q2r3
Create Date: 2026-06-10 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
revision: str = "m9n0p1q2r3s4"
down_revision: Union[str, Sequence[str], None] = "l8m9n0p1q2r3"
branch_labels: Union[str, Sequence[str],... | abundant-ai/oddish | backend/alembic/versions/m9n0p1q2r3s4_add_user_attribution_cache.py | .py | 4dae6ed8c04e7e55 | 7.65 | 19 |
"""merge alert-settings-pane + slack_alert_clerk_id heads
Revision ID: merge_alertpane_main_001
Revises: user_alert_preferences_001, slack_alert_clerk_id_001
Create Date: 2026-07-17 00:00:00.000000
Empty merge migration reconciling the two alembic heads created by merging
origin/main (the Slack outbox + Clerk-linked-... | abundant-ai/oddish | backend/alembic/versions/merge_alertpane_main_001_merge_heads.py | .py | 13f27f6e94217738 | 7.65 | 19 |
"""merge quotas + drop_user_run_probe_default heads
Revision ID: merge_quota_main_001
Revises: add_quotas_table_001, t6u7v8w9x0y1
Create Date: 2026-07-01 00:00:00.000000
Empty merge migration reconciling the two alembic heads created by merging
origin/main (``t6u7v8w9x0y1``, drop ``users.run_probe_default``) into the... | abundant-ai/oddish | backend/alembic/versions/merge_quota_main_001_merge_heads.py | .py | def41c8f714e2e9f | 7.65 | 19 |
"""add users.run_probe_default
Revision ID: o1p2q3r4s5t6
Revises: n0p1q2r3s4t5
Create Date: 2026-06-14 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
revision: str = "o1p2q3r4s5t6"
down_revision: Union[str, Sequence[str], None] = "n0p1q2r3s4t5"
branch_labels: Union[str, Sequence[str]... | abundant-ai/oddish | backend/alembic/versions/o1p2q3r4s5t6_add_user_run_probe_default.py | .py | 7783998e1f07d4d5 | 7.65 | 19 |
"""add org_quotas table (org-level aggregate MONTHLY cap overrides)
Revision ID: org_quotas_monthly_001
Revises: taskapikey_be_001
Create Date: 2026-07-06 00:00:00.000000
Override-only table: a row overrides the read-time
``default_org_monthly_quota_usd`` (``None`` = no org cap by default) for an org;
a MISSING row m... | abundant-ai/oddish | backend/alembic/versions/org_quotas_monthly_001.py | .py | 94464b372b0d5138 | 7.65 | 19 |
"""add chat_sessions, chat_session_events, chat_turns
Revision ID: p2q3r4s5t6u7
Revises: o1p2q3r4s5t6
Create Date: 2026-06-14 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
revision: str = "p2q3r4s5t6u7"
down_revision: Union[str, Sequence[str], None] = "o1p2q3r4s5t6"
branch_labels: Uni... | abundant-ai/oddish | backend/alembic/versions/p2q3r4s5t6u7_add_chat_tables.py | .py | 5fc3bbc2b79b0f6b | 7.65 | 19 |
"""add title column to chat_sessions
Revision ID: q3r4s5t6u7v8
Revises: p2q3r4s5t6u7
Create Date: 2026-06-15 00:00:00.000000
Adds a nullable ``title`` to ``chat_sessions`` (set from the first user message).
Backend tree (``alembic_version``), where the chat tables live. Idempotent:
the chat tables are created with ``... | abundant-ai/oddish | backend/alembic/versions/q3r4s5t6u7v8_add_chat_sessions_title.py | .py | de221e52b94bcb23 | 7.65 | 19 |
"""Drop the legacy ``owner`` user role.
Collapses the role model to ``admin`` / ``member``. Any existing ``owner``
rows are promoted to ``admin`` before the enum value is removed so the
column type no longer accepts ``owner``.
"""
from typing import Sequence, Union
from alembic import op
# revision identifiers, us... | abundant-ai/oddish | backend/alembic/versions/r4s5t6u7v8w9_drop_owner_userrole.py | .py | 178e31ac5f5c286e | 7.65 | 19 |
"""add submission_idempotency
Records an Idempotency-Key per (org, route) so a retried side-effecting
submission (POST /tasks/sweep) replays its stored response instead of creating
duplicate work. ``status`` is plain text + CHECK rather than a Postgres enum so
this migration downgrades cleanly.
Revision ID: s5t6u7v8w... | abundant-ai/oddish | backend/alembic/versions/s5t6u7v8w9x0_add_submission_idempotency.py | .py | c445461efad372f7 | 7.65 | 19 |
"""carry the recipient's Clerk user id on slack_expense_alerts
Lets delivery prefer the recipient's Clerk-linked Slack account over the
email-based Slack lookup. Nullable and left unbackfilled: existing pending DM
rows simply fall back to the email lookup, exactly as before.
Revision ID: slack_alert_clerk_id_001
Revi... | abundant-ai/oddish | backend/alembic/versions/slack_alert_clerk_id_001.py | .py | 5c73dcf0c9674cc7 | 7.65 | 19 |
"""turn slack_expense_alerts into a payload-carrying outbox
Adds the columns that let delivery run purely off the table: the rendered
message text, the DM recipient, and the mention emails. Pre-outbox pending
rows have no payload to deliver; the notifier settles them on sight, so no
data backfill is needed here.
Revi... | abundant-ai/oddish | backend/alembic/versions/slack_alert_outbox_001.py | .py | 34161aab15aa48dc | 7.65 | 19 |
"""add slack_alert_settings table
Revision ID: slack_alert_settings_001
Revises: slack_expense_alerts_001
Create Date: 2026-07-17
"""
from typing import Sequence, Union
from alembic import op
revision: str = "slack_alert_settings_001"
down_revision: Union[str, Sequence[str], None] = "slack_expense_alerts_001"
branc... | abundant-ai/oddish | backend/alembic/versions/slack_alert_settings_001.py | .py | 556e194b83232a27 | 7.65 | 19 |
"""add slack_expense_alerts table
Revision ID: slack_expense_alerts_001
Revises: add_quota_bumps_001
Create Date: 2026-07-09
"""
from typing import Sequence, Union
from alembic import op
revision: str = "slack_expense_alerts_001"
down_revision: Union[str, Sequence[str], None] = "add_quota_bumps_001"
branch_labels: ... | abundant-ai/oddish | backend/alembic/versions/slack_expense_alerts_001.py | .py | 58cc22d81fc1359b | 7.65 | 19 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.