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
""" Tests for analyzer modules. """ import pytest from unittest.mock import MagicMock, patch from datetime import datetime, timezone from src.analyzers.commit_analyzer import CommitAnalyzer from src.analyzers.work_habit_analyzer import WorkHabitAnalyzer from src.analyzers.code_quality_analyzer import CodeQualityAnaly...
ProjectZeroDays/FreeAI_AI-Inference-Workstation
.agents/skills/code-analysis/tests/test_analyzers.py
.py
c939f2e686db1462
7.74
2
""" Tests for the repository scanner. """ import os import tempfile import pytest from unittest.mock import patch, MagicMock from src.scanner import RepoScanner class TestRepoScanner: """Tests for RepoScanner class.""" def test_scan_single_valid_repo(self, tmp_path): """Test scanning a valid Git re...
ProjectZeroDays/FreeAI_AI-Inference-Workstation
.agents/skills/code-analysis/tests/test_scanner.py
.py
deae14f6f8a92f79
7.74
2
""" Desktop Control - Advanced Mouse, Keyboard, and Screen Automation The best ever possible responsive desktop control for OpenClaw """ import pyautogui import time import sys from typing import Tuple, Optional, List, Union from pathlib import Path import logging # Configure PyAutoGUI pyautogui.MINIMUM_DURATION = 0 ...
ProjectZeroDays/FreeAI_AI-Inference-Workstation
.agents/skills/desktop-control/__init__.py
.py
db927d6a121ec770
7.24
2
""" Desktop Control Demo - Quick examples and tests """ import sys import time from pathlib import Path # Add skills to path sys.path.insert(0, str(Path(__file__).parent)) from desktop_control import DesktopController def demo_mouse_control(): """Demo: Mouse movement and clicking""" print("\n🖱️ === MOUSE ...
ProjectZeroDays/FreeAI_AI-Inference-Workstation
.agents/skills/desktop-control/demo.py
.py
3ac6a0218ad10657
7.24
2
import os import time from logging.config import fileConfig from alembic import context from alembic.operations import ops from dotenv import load_dotenv from sqlalchemy import engine_from_config, pool from app.core.base_model import Base from app.core.models import * # noqa target_metadata = Base.metadata # Load e...
rajath-raman/potpie
app/alembic/env.py
.py
ce357be97ff37062
7
0
"""Initial migration Revision ID: 20240812184546_6d16b920a3ec Revises: Create Date: 2024-08-12 18:45:46.599604 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision: str = "20240812184546_6d...
rajath-raman/potpie
app/alembic/versions/20240812184546_6d16b920a3ec_initial_migration.py
.py
d494be98ff0c3128
7
0
"""Adding support for projects Revision ID: 20240812190934_5ceb460ac3ef Revises: 20240812184546_6d16b920a3ec Create Date: 2024-08-12 19:09:34.063355 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alemb...
rajath-raman/potpie
app/alembic/versions/20240812190934_5ceb460ac3ef_adding_support_for_projects.py
.py
fd2fb06506a5cf7c
7
0
"""UTC Timestamps and Indexing Revision ID: 20240812211350_bcc569077106 Revises: 20240812190934_5ceb460ac3ef Create Date: 2024-08-12 21:13:50.136975 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alemb...
rajath-raman/potpie
app/alembic/versions/20240812211350_bcc569077106_utc_timestamps_and_indexing.py
.py
c8c324da127d15e1
7
0
"""Add ON DELETE CASCADE to Message.conversation_id Revision ID: 20240813145447_56e7763c7d20 Revises: 20240812211350_bcc569077106 Create Date: 2024-08-13 14:54:47.718210 """ from typing import Sequence, Union from alembic import op # revision identifiers, used by Alembic. revision: str = "20240813145447_56e7763c7d...
rajath-raman/potpie
app/alembic/versions/20240813145447_56e7763c7d20_add_on_delete_cascade_to_message_.py
.py
6a31051a0b678a17
7
0
"""search index Revision ID: 20240826215938_3c7be0985b17 Revises: 20240823164559_05069444feee Create Date: 2024-08-26 21:59:38.638095 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "20240826215938_3c7be0985b17" down_rev...
rajath-raman/potpie
app/alembic/versions/20240826215938_3c7be0985b17_search_index.py
.py
3fbaa6008539fec1
7
0
"""Add agent id support in conversation table Revision ID: 20240828094302_48240c0ce09e Revises: 20240826215938_3c7be0985b17 Create Date: 2024-08-28 09:43:02.922148 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "2024082...
rajath-raman/potpie
app/alembic/versions/20240828094302_48240c0ce09e_add_agent_id_support_in_conversation_.py
.py
905edb617ce61ef3
7
0
"""Prompt Tables Revision ID: 20240902105155_6b44dc81d95d Revises: 20240828094302_48240c0ce09e Create Date: 2024-09-02 10:51:55.205130 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "20240902105155_6b44dc81d95d" down_re...
rajath-raman/potpie
app/alembic/versions/20240902105155_6b44dc81d95d_prompt_tables.py
.py
190047b1057ef53b
7
0
"""Add user preferences table Revision ID: 20240905144257_342902c88262 Revises: 20240902105155_6b44dc81d95d Create Date: 2024-09-05 14:42:57.885405 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "20240905144257_342902c8...
rajath-raman/potpie
app/alembic/versions/20240905144257_342902c88262_add_user_preferences_table.py
.py
4a0495a8cd28b358
7
0
"""Support for citations in backend Revision ID: 20240927094023_fb0b353e69d0 Revises: 20240905144257_342902c88262 Create Date: 2024-09-27 09:40:23.874379 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "20240927094023_fb...
rajath-raman/potpie
app/alembic/versions/20240927094023_fb0b353e69d0_support_for_citations_in_backend.py
.py
cc25f548318d89fb
7
0
"""add shared with email to the conversation model Revision ID: 20241003153813_827623103002 Revises: 20240927094023_fb0b353e69d0 Create Date: 2024-10-03 15:38:13.436502 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "20...
rajath-raman/potpie
app/alembic/versions/20241003153813_827623103002_add_shared_with_email_to_the_.py
.py
bb3af63c2a60ab03
7
0
"""New migration Revision ID: 20241028204107_684a330f9e9f Revises: 20241003153813_827623103002 Create Date: 2024-10-28 20:41:07.469748 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "20241028204107_684a330f9e9f" down_re...
rajath-raman/potpie
app/alembic/versions/20241028204107_684a330f9e9f_new_migration.py
.py
2ab1e020fbb998b6
7
0
"""Support for repo path Revision ID: 20241127095409_625f792419e7 Revises: 20241028204107_684a330f9e9f Create Date: 2024-11-27 09:54:09.683918 """ from typing import Sequence, Union from alembic import op # revision identifiers, used by Alembic. revision: str = "20241127095409_625f792419e7" down_revision: Union[st...
rajath-raman/potpie
app/alembic/versions/20241127095409_625f792419e7_support_for_repo_path.py
.py
a7d3a386b9271d88
7
0
import hashlib import os import secrets from typing import Optional from fastapi import HTTPException from google.cloud import secretmanager from sqlalchemy import text from sqlalchemy.orm import Session from app.modules.users.user_preferences_model import UserPreferences class APIKeyService: SECRET_PREFIX = "s...
rajath-raman/potpie
app/modules/auth/api_key_service.py
.py
30696534828c3a17
7
0
from typing import List from fastapi import HTTPException from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from app.modules.conversations.conversation.conversation_model import ( Conversation, Visibility, ) class ShareChatServiceError(Exception): """Base exception class for S...
rajath-raman/potpie
app/modules/conversations/access/access_service.py
.py
fd4d80f307cf7eff
7
0
"""Styled per-module runtime-breakdown chart for the baseline sweep. The baseline figure: one stacked bar per compute block, its runtime split into compute / overlap / memory / stall, each scaled by the block's whole-model repeat count. Styled like the hand-built reference (``baseline_prefill_chart_updated.xlsx``): l...
jeffreyyu0602/voyager-compiler
benchmarks/per_module_latency_chart.py
.py
8636cefd47bae1e8
7.39
5
"""Plot the model-size sweep against parameter count, not the model's name. ``plot_results_mpl`` draws the sweep the way the workbook does: five bars over the labels 1B / 3B / 7B / 8B / 13B, evenly spaced, which says nothing about how far apart those designs actually are. This plots the same two metrics -- latency an...
jeffreyyu0602/voyager-compiler
benchmarks/plot_model_size_scaling.py
.py
688c6f62b5898a49
7.39
5
"""Unified design-space sweep: every axis in one run, one aggregate workbook. Replaces the individual ``sweep_context / sweep_model_size / sweep_quant / sweep_family / sweep_hardware`` scripts. All of them radiate from the same baseline design point (Llama-3.1-8B, 64x64 PE, 2 MB SRAM, W8A8, length 1024), so run separ...
jeffreyyu0602/voyager-compiler
benchmarks/runner.py
.py
2c63204a4cb775b3
7.39
5
import argparse import copy import hashlib import logging import os import random import re from random import randint import evaluate import librosa import numpy as np import torch import torch.nn as nn import torch.ao.nn.intrinsic as nni from datasets import DatasetDict, Dataset, load_dataset from scipy.fftpack impo...
jeffreyyu0602/voyager-compiler
examples/audio_classification/honk_train.py
.py
1078f26e5dfbd6a9
7.39
5
from collections import deque class Cache(object): """ Helper class for cache computed values to reduce runtime """ def __init__(self, num_levels, size): self.num_levels = num_levels self.cache_map = [dict() for x in range(num_levels)] self.cache_queue = [deque() for i in rang...
jeffreyyu0602/voyager-compiler
src/interstellar/cache.py
.py
0b216530c7a7e7a2
7.39
5
""" Layer specification. """ class Layer(object): """ NN layer parameters. nifm: ifmap channels. nofm: ofmap channels. wifm: ifmap width. hifm: ifmap height. wofm: ofmap width. hofm: ofmap height. wfil: weight filter width. hfil: weight filter height. nimg: input images (b...
jeffreyyu0602/voyager-compiler
src/interstellar/layer.py
.py
adfee9ff7d7ef240
7.39
5
""" Top level function of optimization framework """ import logging from . import mapping_point_generator from . import cost_model from . import loop_enum as le from . import buffer_enum as be logger = logging.getLogger(__name__) def opt_optimizer( resource, layer, hint=None, runtime_calc_func=Non...
jeffreyyu0602/voyager-compiler
src/interstellar/optimizer.py
.py
cc90fb33a6e16d6b
7.39
5
""" Schedule hint """ from . import loop_enum as le class Schedule(object): """ schedule_hint: {loop index:[[loop order,loop blocking,loop partitioning @ 1st level mem],[@ 2nd level mem],[3rd .]]} loop blocking -> temporal loop size loop partitioning -> spatial loop size (spatial unroll...
jeffreyyu0602/voyager-compiler
src/interstellar/schedule.py
.py
27aaa45e7be9943b
7.39
5
"""Collapse a ``while_loop``'s steady-state iterations. After scheduling, a software-pipelined loop's middle iterations become structurally identical: the same events with the same durations and the same intra-iteration offsets, differing only in absolute time. Only the fill (prologue) and drain (epilogue) iterations...
jeffreyyu0602/voyager-compiler
src/voyager_compiler/codegen/reporting/compress.py
.py
e2b15499a17a53d4
7.39
5
"""The recursive scheduler: walk a bufferized FX graph and emit timing. A lightweight interpreter (modeled on ``shape_prop.ShapeProp``'s node loop, but specialized) keeps an ``env`` of concrete **scalar** values and evaluates only the scalar / control sublanguage — index math, predicates, counters — which is all that ...
jeffreyyu0602/voyager-compiler
src/voyager_compiler/codegen/reporting/interpret.py
.py
0a2dd01617a69303
7.39
5
"""Data structures shared across the reporting stages. The estimator runs three separate stages over a bufferized FX graph: scheduling (``interpret`` + ``scheduler``), repeated-pattern compression (``compress``), and reporting (``excel`` / ``perfetto``). These dataclasses are the contract between them. """ import ma...
jeffreyyu0602/voyager-compiler
src/voyager_compiler/codegen/reporting/model.py
.py
9b0dfbe9f1852649
7.39
5
"""Chrome / Perfetto trace export (``chrome://tracing`` JSON). Emits the full, uncompressed event stream so the exact schedule can be inspected: compute split onto a Matrix (systolic array) and a Vector (vector unit) track, the DRAM interface on another, control (waits) on a third. A fused pass that runs vector ops a...
jeffreyyu0602/voyager-compiler
src/voyager_compiler/codegen/reporting/perfetto.py
.py
68de9b4490eab391
7.39
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Figure 2, reproduced in the supplement as Figure S10. Per-sample imputation accuracy of a cohort-specific model against the model trained on the whole admixed LOS cohort, for the African American and Caucasian cohorts of chromosome 22 at three masking rates. Each coho...
learnslowly/BiU-Net
Results/Figure_S10.py
.py
ea51dccd771585e6
7
0
import pandas as pd import numpy as np # horizontally split version def calculate_maf(df): """ Calculate Minor Allele Frequency (MAF ≤ 0.5) for each row (SNP) in a genotype dataframe, where rows are SNPs and columns are samples. Genotype encoding: 1 = A|A (0 minor alleles), 2 = A|a (1 minor allele), 3 ...
learnslowly/BiU-Net
data/metrics.py
.py
dd67e8e59c90f391
7
0
import re import numpy as np import os import pandas as pd from typing import List, Tuple, Optional from data.metrics import calculate_maf import h5py from config.modelconfig import ModelConfig def prepare_target_snps(config: ModelConfig, bin_range: str): print("Calculating MAF from complete training set...") ...
learnslowly/BiU-Net
data/segmentation.py
.py
984a827d40f3e0e4
7
0
"""Locate benchmark cell CSVs under analysis/, across their filename spellings. benchmark.py tags our own model's cells with the checkpoint epoch (`{runId}_epoch{E}_phased_...`). Cells written before 2026-08-24, and every external-imputer cell, carry the plain `{runId}_phased_...` name. A run also wrote its cells unde...
learnslowly/BiU-Net
scripts/analysis_cells.py
.py
e4367cb000fe9d75
7
0
"""Classify the target markers Beagle drops when a reference panel is supplied. Beagle 5.5 keeps a target VCF record only when the reference stream holds a marker for which Marker.equals() is true (vcf/RefTargSlidingWindow.readWindow, vcf/Marker.equals): same chromosome, same position, same allele list, same INFO/END....
learnslowly/BiU-Net
scripts/beagle_excluded_markers.py
.py
0088c4be3be64443
7
0
"""Aggregate revision-2 genome-wide benchmark results into summary tables. Reads the per-cell CSVs benchmark.py writes to analysis/: 1KGP_genomewide_phased_{biunet|beagle}_BAT_rand{RS}_1KGP_chr{C}_ALL_seg1024_overlap128_missing{M}.csv (columns: MAF_bin, Num_SNPs, Bin_Acc, Bin_R2, Bin_Precision, Bin_Recall, Bin_F1,...
learnslowly/BiU-Net
scripts/build_per_chromosome_tables.py
.py
eea29f025abdf6d1
7
0
#!/usr/bin/env python3 """Generate the uniform job/*.batch set for the 7 reported datasets. Every batch: sources configs/credentials.sh, calls $PYBIN, writes to logs/%x_%j.log, and omits private SLURM directives (--account/--mail-user) — those are injected by ./submit.sh. Re-run any time to regenerate. """ import os ...
learnslowly/BiU-Net
scripts/gen_job_batches.py
.py
cd5850e51b0d2fac
7
0
"""Write the per-chromosome fine-tuning configs for both datasets. The genome-wide model trained on merged reference and target data is fine-tuned on one chromosome at a time for 30 epochs. Everything except the chromosome restriction is inherited from the anchor config that was already run and reported (chr22 for 1KG...
learnslowly/BiU-Net
scripts/make_finetune_configs.py
.py
e17d0c1bfd24bad3
7
0
"""Seed a fine-tuning run with the weights of the genome-wide model. train.py resumes from the newest checkpoint whose name matches the run it is about to perform, and a run's name is built from its own runId. A fine-tuning run therefore never sees the genome-wide checkpoint: the two carry different runIds, the glob f...
learnslowly/BiU-Net
scripts/prebake_finetune_checkpoint.py
.py
c45943dfb29d4abc
7
0
import multiprocessing import time import pandas as pd import h5py import numpy as np import os import glob from typing import Tuple, List, Optional, Dict from functools import partial from concurrent.futures import ProcessPoolExecutor import argparse import re from config.modelconfig import ModelConfig from data.segme...
learnslowly/BiU-Net
segmenting.py
.py
863906ab9cb431e8
7
0
"""cron 任务的确定性北京时间计划计算。""" from __future__ import annotations from datetime import datetime, timedelta, timezone from typing import Any from zoneinfo import ZoneInfo from run.scheduler import CronValidationError BEIJING = ZoneInfo("Asia/Shanghai") def _as_beijing(value: datetime | None = None) -> datetime: i...
kesepain-KE/kemo-agent
cron/schedule.py
.py
9923d245de686536
7.39
5
"""kemo-agent Web API 的带会话代理客户端。""" from __future__ import annotations import asyncio import os from contextlib import asynccontextmanager from typing import Any, AsyncIterator from urllib.parse import urlsplit import httpx _DEFAULT_UPSTREAM = "http://127.0.0.1:1357" _RUNTIME_WEB_ENDPOINT_ENV = "KEMO_AGENT_WEB_BAS...
kesepain-KE/kemo-agent
global_expand/kemo_app/upstream.py
.py
9f8dfc876f65b684
7.39
5
"""Response-safe errors for the Kemo Graph sidecar extension.""" from __future__ import annotations class GraphExpandError(RuntimeError): """A validation or local operation error safe to return to the caller.""" class GraphAPIError(GraphExpandError): def __init__(self, status: int, code: str, message: str)...
kesepain-KE/kemo-agent
global_expand/kemo_graph/errors.py
.py
c221002a66802463
7.39
5
"""Resolved URLs and credentials for ``tokensaver route``.""" from __future__ import annotations import os from dataclasses import dataclass from urllib.parse import urlparse PROD_API_HOST = "https://api.tokensaver.fr" PROD_MCP_URL = "https://mcp.tokensaver.fr/mcp" PROD_GATEWAY_URL = "https://gateway.tokensaver.fr/m...
tokensaver-ai/tokensaver-cli
src/tokensaver_cli/config.py
.py
d652553a4360d59a
7
0
"""Install the bundled Claude Code plugin into ``~/.claude/skills/``.""" from __future__ import annotations import shutil from importlib import resources from pathlib import Path PLUGIN_SKILL_NAME = "tokensaver-router" def plugin_install_dir() -> Path: return Path.home() / ".claude" / "skills" / PLUGIN_SKILL_...
tokensaver-ai/tokensaver-cli
src/tokensaver_cli/plugin_install.py
.py
cca484b7bc5ea4e1
7
0
"""Model profiles for ``tokensaver route claude --profile``.""" from __future__ import annotations import json from pathlib import Path from typing import Any from tokensaver_cli.state import route_state_dir # Paid / BYOK defaults (catalogue provider/model_id). BUILTIN_PROFILES: dict[str, str] = { "cheap": "ope...
tokensaver-ai/tokensaver-cli
src/tokensaver_cli/profiles.py
.py
e276cd4adc42b994
7
0
"""Banner tests.""" from tokensaver_cli.banner import banner_enabled, print_banner def test_banner_enabled_default(monkeypatch) -> None: monkeypatch.delenv("TOKENSAVER_NO_BANNER", raising=False) assert banner_enabled() is True def test_banner_disabled(monkeypatch) -> None: monkeypatch.setenv("TOKENSAVE...
tokensaver-ai/tokensaver-cli
tests/test_banner.py
.py
116cb95e5277ce3b
7.5
0
import requests import base64 import logging import re import socket import os # Logging configuration logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) # URL for fetching configurations URL = "https://raw.githubusercontent.com/3...
3yed-61/Shadowsocks
config-cleaner.py
.py
1a2b7b3a08afa713
7
0
#!/usr/bin/env python3 """ Cross-host comparison — merges per-host runs into a single side-by-side table and figures. Reads every host under results/: - prefers results/<host>/results.json + capabilities.json (rich), else - parses the embedded JSON summary inside a final_report.md (so a single report file from...
balkeumlabs/Cap-over-TFLOPS
compare.py
.py
6c0d8efad6dd8996
7
0
""" E1 - Capacity over TFLOPS (headline result). Demonstrates the study's central claim on a single machine: (a) the INT4 model's serving state loads into SYSTEM RAM and occupies a measured, stable footprint with ample headroom; while (b) the same weights CANNOT fit in the detected consumer GPU's VRAM -> an ...
balkeumlabs/Cap-over-TFLOPS
src/experiments/e1_capacity.py
.py
047f7d679e14a2bc
7
0
""" E4 - Communication efficiency (analytical, no model download required). Quantifies the bandwidth claim: federated nodes share only the LoRA adapters (q_proj, v_proj) instead of full parameter sets. We compute exact adapter parameter counts from the Gemma-2 architecture and compare against the full model, for LoRA ...
balkeumlabs/Cap-over-TFLOPS
src/experiments/e4_comms.py
.py
826b76bc5ab761ce
7
0
#!/usr/bin/env python3 """ Model fetcher — downloads ungated community GGUF files (no HF token needed). Open Gemma-2 stand-ins for MedGemma. Files come from community GGUF repos that do NOT require license acceptance, so downloads work unauthenticated. python src/fetch_models.py --tier edge # ~1.7 GB, validat...
balkeumlabs/Cap-over-TFLOPS
src/fetch_models.py
.py
ea07d3fb02d1f3db
7
0
import base64 from pathlib import Path from typing import Optional import pytest import requests class TestConfig: BASE_URL = 'http://localhost:8000' TEST_REQUEST_ID = 'test_request_001' # Validation constants REQUIRED_TECHNICAL_INDICATORS = {'macd', 'rsi', 'mfi', 'stochastic', 'volume', 'current_price', '...
rajath-raman/pixeltable
docs/sample-apps/ai-based-trading-insight-chrome-extension/tests/test.py
.py
0aa941a87f4128c0
7.5
0
from datetime import datetime import discord class MessageFormatter: """Helper class for consistent Discord message formatting""" # Discord color constants BLUE = discord.Color.blue() GREEN = discord.Color.green() RED = discord.Color.red() @staticmethod def create_search_embed(results: ...
rajath-raman/pixeltable
docs/sample-apps/context-aware-discord-bot/message_formatter.py
.py
36bf660f75518e57
7
0
""" JFK Files Data Loader Tutorial ============================= This script demonstrates how to build a semantic search system for JFK document files using Pixeltable. It shows how to: 1. Set up a Pixeltable table with computed columns for document summaries 2. Scrape PDF links from the National Archives website 3. G...
rajath-raman/pixeltable
docs/sample-apps/jfk-files-mcp-server/load_data.py
.py
12902a1c237343f6
7
0
# This is a MCP-based server that provides an interface to query JFK files using SSE (Server-Sent Events) # It demonstrates how to set up a real-time communication channel between the client and server import argparse import uvicorn from initialize import mcp from mcp.server import Server from mcp.server.sse import S...
rajath-raman/pixeltable
docs/sample-apps/jfk-files-mcp-server/server.py
.py
963f125251a84323
7
0
from typing import Dict, List, Optional import yfinance as yf from duckduckgo_search import DDGS import pixeltable as pxt @pxt.udf() def run_duckduckgo_search(query: str, max_results: int = 5) -> List[Dict] | None: """Performs a DuckDuckGo search and returns results as a list of dicts.""" # print(f"Performi...
rajath-raman/pixeltable
docs/sample-apps/reddit-agentic-bot/functions.py
.py
96675d4647088c5c
7
0
from __future__ import annotations import logging import warnings from textwrap import dedent from typing import TYPE_CHECKING, Any import sqlalchemy as sql import pixeltable.exceptions as excs import pixeltable.exprs as exprs import pixeltable.type_system as ts from pixeltable.env import Env from pixeltable.metadat...
rajath-raman/pixeltable
pixeltable/catalog/column.py
.py
c6fd9224b82d400c
7
0
from __future__ import annotations import dataclasses import json import logging from uuid import UUID import sqlalchemy as sql from pixeltable.env import Env from pixeltable.metadata import schema from .schema_object import SchemaObject _logger = logging.getLogger('pixeltable') class Dir(SchemaObject): def ...
rajath-raman/pixeltable
pixeltable/catalog/dir.py
.py
5584ec70f94a47a5
7
0
from __future__ import annotations import json import logging from uuid import UUID import sqlalchemy as sql from pixeltable.env import Env from pixeltable.metadata import schema from .schema_object import SchemaObject _logger = logging.getLogger('pixeltable') class NamedFunction(SchemaObject): """ Conta...
rajath-raman/pixeltable
pixeltable/catalog/named_function.py
.py
bd9fa3ecfe07ba05
7
0
from abc import abstractmethod from typing import TYPE_CHECKING from uuid import UUID if TYPE_CHECKING: from pixeltable import catalog class SchemaObject: """ Base class of all addressable objects within a Db. Each object has an id, a name and a parent directory. """ _id: UUID _name: str...
rajath-raman/pixeltable
pixeltable/catalog/schema_object.py
.py
5f36b1fec1a9bc7c
7
0
from __future__ import annotations import logging from dataclasses import dataclass from typing import TYPE_CHECKING from uuid import UUID from pixeltable import exceptions as excs from .table_version import TableVersion if TYPE_CHECKING: from pixeltable.catalog import Column _logger = logging.getLogger('pixel...
rajath-raman/pixeltable
pixeltable/catalog/table_version_handle.py
.py
28fdfe0271cff4b0
7
0
from __future__ import annotations import logging from uuid import UUID from pixeltable.env import Env from pixeltable.metadata import schema from .column import Column from .globals import MediaValidation from .table_version import TableVersion from .table_version_handle import TableVersionHandle _logger = logging...
rajath-raman/pixeltable
pixeltable/catalog/table_version_path.py
.py
fe299989e5d80eb1
7
0
"""版本号更新脚本。 用法: python scripts/bump_version.py <major|minor|patch|版本号> [--commit] [--dry-run] - 以 pyproject.toml 的 [project].version 为唯一事实来源,同步 src/oce/__init__.py 的 __version__。 - 采用行级替换而非完整 TOML 重写,避免破坏 pyproject.toml 中的注释。 """ from __future__ import annotations import argparse import re import subprocess imp...
oce-ai/oce
scripts/bump_version.py
.py
0701d0e368ba0681
7.24
2
"""add_symbol_occurrences_table Revision ID: 2eebb4028c7f Revises: d48cee59fb24 Create Date: 2026-08-20 18:14:59.710515 """ from typing import Sequence, Union from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision: str = '2eebb4028c7f' down_revision: Union[str, None] = 'd4...
oce-ai/oce
src/oce/alembic/versions/2eebb4028c7f_add_symbol_occurrences_table.py
.py
7bd217d696033cb2
7.24
2
"""应用层消息总线 - CommandBus / QueryBus 简单注册分发:消息类型 → handler 的 dict 映射。 - CommandBus.execute: 执行写命令(可批量) - QueryBus.ask: 执行读查询 未注册的消息抛 ApplicationError 系异常(COMMAND_NOT_REGISTERED / QUERY_NOT_REGISTERED),由 API 层统一转 HTTP 500。 """ from __future__ import annotations from typing import Any from oce.shared.errors impor...
oce-ai/oce
src/oce/application/bus.py
.py
3c50f75ae6fc616a
7.24
2
"""Embedding credential runtime commands.""" from __future__ import annotations from dataclasses import dataclass from typing import Protocol from oce.application.messages import Command from oce.shared.errors import ServiceNotReadyError class ReloadableEmbeddingRuntime(Protocol): async def reload(self) -> int...
oce-ai/oce
src/oce/application/commands/credentials.py
.py
2797e4f4cbca50e5
7.24
2
"""队列运维命令:对齐队列与 DB 待办,或整体清空。 队列是 DB 待办的投影,不是权威。两者会漂移:blob 被删除或重建后旧消息仍在飞, worker 取到只能白跑;更糟的是 pending 哨兵里的残留会让同名 blob 再也无法入队。 `ResetQueueCommand` 提供两档处置: - mode="sync"(默认):以 DB 的 pending blob 为准剔除队列里的无效项,并补投漏投项 - mode="purge":清空队列再按 DB 全量重投 两者都要求 worker 已停;handler 不会替调用方停 worker,因为 worker 生命周期 由 composition root 持有。 "...
oce-ai/oce
src/oce/application/commands/queue_admin.py
.py
526fbb4eef86b1d1
7.24
2
"""应用层消息 - Command / Query 标记基类 CQRS 约定: - Command(命令):写操作,改变系统状态,经 CommandBus.execute 分发 - Query(查询):读操作,不改变状态,经 QueryBus.ask 分发 具体消息一律用 frozen dataclass 定义(不可变,天然线程安全), handler 以 Protocol 约束,由应用层组装(composition root)注册。 """ from __future__ import annotations from typing import Any, Protocol class Command: ""...
oce-ai/oce
src/oce/application/messages.py
.py
6d59727a2dcbf39d
7.24
2
"""查询对象与处理器 - 检索读路径 SearchQuery: 一次代码检索(向量召回 + 精确标识符召回 + 重排 + 覆盖度选择)。 """ from __future__ import annotations from dataclasses import dataclass, field from oce.application.messages import Query from oce.domain.services.retrieval import RetrievalPipeline from oce.domain.services.search import SearchHit @dataclass(f...
oce-ai/oce
src/oce/application/queries/search.py
.py
3a54d979d4fd2fe5
7.24
2
"""HTTP Bearer 鉴权。""" import hmac from fastapi import Header, HTTPException from oce.shared.config import get_settings def _unauthorized(message: str) -> HTTPException: return HTTPException( status_code=401, detail={ "error": { "message": message, "ty...
oce-ai/oce
src/oce/auth.py
.py
1f3ba6bcc8560a87
7.24
2
"""Command-line entry points for the local OCE distribution.""" from __future__ import annotations import argparse import os import sys from pathlib import Path from dotenv import load_dotenv from oce import __version__ _DEFAULT_DATA_DIR = Path.home() / ".oce" / "data" # -v 次数 → loguru / uvicorn 级别;默认 WARNING 避免...
oce-ai/oce
src/oce/cli.py
.py
1e765119fd1f830f
7.24
2
"""Blob 聚合根 - 文件抽象 Blob 是文件的领域抽象,职责: - 管理文件元数据(path/status/last_seen) - 管理关联的 Chunk 列表 - 状态转换(pending -> ready/error) - 过期判定 不变量: - blob_name 必须是有效的 SHA256 - status 状态机:pending -> ready/error - 空文本或二进制文件可以没有 chunk 并直接标记 ready """ from __future__ import annotations from dataclasses import dataclass, field from datet...
oce-ai/oce
src/oce/domain/blob/blob.py
.py
cd9baa7112fed259
7.24
2
"""Chain 聚合根 - 工作集抽象 Chain 是客户端工作集的领域抽象,职责: - 管理 Blob 成员列表 - 实现 Checkpoint 版本控制 - 支持增量更新(added/deleted) 不变量: - chain_id 必须是有效的 UUID - version 必须单调递增 - members 集合去重 """ from __future__ import annotations import uuid from dataclasses import dataclass, field from datetime import datetime, timezone @dataclass class C...
oce-ai/oce
src/oce/domain/chain/chain.py
.py
e3a4dc90e9e16cd2
7.24
2
"""Code chunking protocols.""" from __future__ import annotations from typing import Protocol, runtime_checkable from oce.domain.chunk.types import Chunk @runtime_checkable class Chunker(Protocol): """Minimum interface consumed by the indexing pipeline.""" def chunk(self, content: str, path: str) -> list[...
oce-ai/oce
src/oce/domain/chunk/protocols.py
.py
c7f26ae602fd76d5
7.24
2
"""RecursiveChunker — 基于 LangChain RecursiveCharacterTextSplitter 的智能兜底切块器。 用于: 1. 无法识别语言的文件(无扩展名、未知格式) 2. 各专用 chunker 的 fallback(当 AST 解析失败时) 相比 FixedChunker 的优势: - 递归尝试分隔符:优先在段落边界(\n\n)切分,其次行边界(\n),最后空格和字符 - 语言感知:支持 Python/JS/Go/Rust 等语言的特定分隔符 The splitter decides where boundaries fall; the text of a chunk is alwa...
oce-ai/oce
src/oce/domain/chunk/recursive_chunker.py
.py
1a62f113cfb677d3
7.24
2
"""Language-aware chunker dispatch.""" from __future__ import annotations from collections.abc import Iterable from types import MappingProxyType from typing import Mapping from oce.domain.chunk.lang import SUPPORTED_LANGUAGES, detect_language from oce.domain.chunk.protocols import Chunker, LanguageChunker from oce....
oce-ai/oce
src/oce/domain/chunk/router.py
.py
d001060fda3a3ced
7.24
2
"""Line-span helpers shared by the chunkers. A span is a 1-based inclusive line range paired with the exact text of those lines. Keeping text and range in one value makes the invariant checkable: a chunk must render at the line numbers it claims, because the formatter prints ``start_line + offset`` for each of its lin...
oce-ai/oce
src/oce/domain/chunk/spans.py
.py
805cd5e7b0d642e1
7.24
2
"""统一的 LLM 客户端协议。 三个 LLM 消费者(reranker / rewriter / intent classifier)共享同一个 chat 协议。 此前该协议在 llm_reranker 与 query_rewriter 中各定义一份,此处收敛为单一来源, 避免重复。基础设施层的 OpenAI 兼容客户端实现它。 """ from __future__ import annotations from typing import Protocol class LLMClient(Protocol): """LLM 聊天客户端协议。 额外参数(model / temperature / ma...
oce-ai/oce
src/oce/domain/services/llm/client.py
.py
b8ba2e070ecaa43e
7.24
2
"""Fetching the attachments themselves, so a text one is greppable like any other file. Lark never reports an attachment's size until it has been downloaded -- the message body carries only a key and a filename -- so the size limit is enforced after the fact and the kind whitelist is what actually bounds the request c...
CNSeniorious000/lark-fs
src/lark_fs/attachments.py
.py
7764e27e3e514f58
7.15
1
"""Thin async wrapper around the `lark-cli` binary.""" from asyncio import CancelledError, Semaphore, create_subprocess_exec, create_task, gather, shield, sleep, subprocess from collections import defaultdict, deque from collections.abc import Awaitable, Callable, Collection from contextlib import suppress from contex...
CNSeniorious000/lark-fs
src/lark_fs/cli.py
.py
2a52a5fe9d999aa2
7.15
1
"""Keep the mirror fresh in the background. Feishu offers no update feed a personal account can consume -- the event bus is bot-scoped and exclusive, and one connection is typically already claimed by another tool. So this polls, but pays for freshness only where it is cheap: - messages: forward from the cursor every...
CNSeniorious000/lark-fs
src/lark_fs/daemon.py
.py
81c11e4f78655018
7.15
1
"""lark-fs CLI entrypoint.""" from argparse import ArgumentParser from asyncio import run from os import environ from pathlib import Path from signal import SIGINT, SIGTERM, signal from sys import stderr from .cli import Aborted, SyncAbortedError from .daemon import Schedule, watch from .reindex import reindex from ....
CNSeniorious000/lark-fs
src/lark_fs/main.py
.py
49557adbb68efb75
7.15
1
"""Rebuild derived indexes from messages already on disk, without touching the network. `users/` and each chat's `media.yaml` are both projections of the message files, so a store synced before those projections existed (or after their extraction rules changed) can be brought up to date locally instead of re-fetching ...
CNSeniorious000/lark-fs
src/lark_fs/reindex.py
.py
32a66a5de49bb23a
7.15
1
"""On-disk layout + incremental-sync bookkeeping. Everything is one entity per file, named by its Lark ID, so `fd om_xxx` and `rg 'oc_xxx'` are the primary query interface. Cross-entity references are always raw IDs, never paths -- so a grep for an ID finds every mention of it. Structured data is rendered as readable...
CNSeniorious000/lark-fs
src/lark_fs/store.py
.py
3319d928763102e4
7.15
1
"""pnpm-style inline progress: a few lines redrawn in place, no alternate screen.""" from asyncio import CancelledError, Event, Future, create_task, gather, sleep from contextlib import suppress from itertools import cycle from re import compile from sys import stderr from xml.sax.saxutils import escape from prompt_t...
CNSeniorious000/lark-fs
src/lark_fs/tui.py
.py
6afbfbf6b3a64d27
7.15
1
from re import IGNORECASE, VERBOSE, compile type JSON = dict[str, JSON] | list[JSON] | tuple[JSON, ...] | str | int | float | bool | None # A literal block cannot carry these: YAML forbids the C0 and C1 control ranges outright, # and reads U+0085/2028/2029 as line breaks, which would silently restructure the documen...
CNSeniorious000/lark-fs
src/lark_fs/yaml.py
.py
f3b447ff37c1d816
7.15
1
""" datacenter/scale_up.py — Part ii proof-of-concept (RQ4): turn one Orin's measured power trace into a facility-scale power profile. Two paths, matching the proposal: * OpenG2G (arXiv:2605.05519): the intended tool. It replays real GPU power traces through a data-center + grid model. This module EXPORTS your O...
Adraxem/thesis_experiment
datacenter/scale_up.py
.py
ef8632f130834e3d
7
0
""" models/base.py — a uniform runner interface so the sweep driver treats every model the same: load once, then run N inference iterations while the PowerLogger records. Each concrete runner tries the real backend (torch / TensorRT / transformers) and falls back to a timing-only stub if the dependency or hardware is ...
Adraxem/thesis_experiment
models/base.py
.py
583848459ef149d2
7
0
""" power/waveform_features.py — turn a PowerTrace into the scalar features that are the *object of study* in this thesis (RQ1): peak, transient sharpness, thermal ramp, and energy-per-inference — not just average power. These are exactly the targets the predictor (RQ2) learns and the optimizer (RQ3) constrains. """ f...
Adraxem/thesis_experiment
power/waveform_features.py
.py
c26d1cb5cfcadc6d
7
0
"""TelegramNotifier — реализация NotifierPort через обычные HTTPS-вызовы к Telegram Bot API (``httpx``), НЕ через aiogram. Осознанное решение: aiogram заточен под асинхронный long-polling/webhook цикл самого бота (bot/main.py), а этот адаптер нужен и синхронному CLI (cli/main.py, флаг ``--notify-telegram``) — тащить ту...
Nergan/cutaway
another/control-plane-admin/another_admin/adapters/telegram_notifier.py
.py
30baad050eb2efc3
7
0
"""Фабрика FastAPI-приложения: Worker REST-прокси + админ-API + статическая админка.""" from __future__ import annotations import mimetypes from contextlib import asynccontextmanager from pathlib import Path from fastapi import FastAPI from fastapi.responses import FileResponse from fastapi.staticfiles import Static...
Nergan/cutaway
another/control-plane-admin/another_admin/api/app.py
.py
a824fdc5f1bc73db
7
0
"""Загрузка конфигурации из переменных окружения — единая точка входа для CLI и Telegram-бота (два driving-адаптера одного и того же domain-слоя, см. §12 архитектурной спецификации). """ from __future__ import annotations import os from dataclasses import dataclass, field class MissingConfigError(RuntimeError): ...
Nergan/cutaway
another/control-plane-admin/another_admin/config.py
.py
a8ac29512c7a8ca2
7
0
"""DeviceProvisioningService — прямой перенос псевдокода §12 архитектурной спецификации (``create_invite``/``revoke_device``) в рабочий код. Не знает ничего про Mongo/Telegram/CLI/Typer/aiogram — только через UserRepositoryPort. """ from __future__ import annotations import hashlib import secrets from dataclasses imp...
Nergan/cutaway
another/control-plane-admin/another_admin/domain/device_provisioning_service.py
.py
b6f71ceca63e811b
7
0
"""Domain-модели. Ничего не знают про MongoDB/Telegram — только форма данных и её инварианты. Зеркалят исправленную схему §10 архитектурной спецификации (без HWID/MAC — идентичность только через public_key, проставляемый устройством при онбординге, см. edge/src/handlers/enroll.ts). """ from __future__ import annotatio...
Nergan/cutaway
another/control-plane-admin/another_admin/domain/models.py
.py
c8db5286e8caaef4
7
0
"""QuotaReportService — сводка по использованию квоты трафика (§8.4 спецификации: поле quota_limit_bytes/bytes_used без этого сервиса было бы "мёртвыми" данными, которые некому смотреть).""" from __future__ import annotations from dataclasses import dataclass from another_admin.domain.models import QuotaReportRow fr...
Nergan/cutaway
another/control-plane-admin/another_admin/domain/quota_report_service.py
.py
5c20af001b3db432
7
0
"""NotifierPort — доставка приглашения адресату. В v1 единственная реализация — Telegram (adapters/telegram_notifier.py), но порт намеренно не называется TelegramNotifierPort: смена канала (Matrix/Signal-бот и т.п., см. §19 архитектурной спецификации) — это замена одного адаптера, а не переписывание domain-слоя.""" fr...
Nergan/cutaway
another/control-plane-admin/another_admin/ports/notifier_port.py
.py
a1d98e56237382fe
7
0
"""UserRepositoryPort — доступ к источнику истины (MongoDB Atlas, §10 спецификации). Используется typing.Protocol (структурная типизация), а не abc.ABC — идиоматичнее для Python и не требует явного наследования от адаптеров и тестовых fake-реализаций (см. tests/test_device_provisioning_service.py). """ from __future__...
Nergan/cutaway
another/control-plane-admin/another_admin/ports/user_repository_port.py
.py
5c4cc4b1c7a3ba01
7
0
""" core/hydrodynamic_forces.py Calcolo Carichi Ambientali (Vento e Corrente) OCIMF MEG4. Convenzione Angoli: 0° = PRUA, 90° = DRITTA, 180° = POPPA, 270° = SINISTRA. """ import numpy as np def get_ocimf_wind_coefficients(angle_deg: float) -> tuple: """ Curve trasversali, longitudinali e di momento del vento ...
PANORAMA2026/moor2.0
core/hydrodynamic_forces.py
.py
bc6f78e7c6cdeeca
7
0