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 |
|---|---|---|---|---|---|---|
"""
AI Recommendation Engine (Sprint 8).
Tổng hợp các yếu tố kỹ thuật thành một điểm TIN CẬY (0-100%) + lý do.
Không phải machine learning; đây là hệ thống chấm điểm theo trọng số
(rule-based scoring), minh bạch và dễ kiểm chứng.
Trọng số:
Trend (EMA alignment) : 25
ADX (độ mạnh xu hướng): 25
Pullback về ... | cuongnt-2026/Trading-Assistant-AI | src/ai_review/recommender.py | .py | 3d632baac9e5703f | 7 | 0 |
"""
Application configuration.
Doc cau hinh tu file .env (neu co) + bien moi truong.
"""
import os
def load_env_file(path: str = ".env") -> None:
if not os.path.exists(path):
return
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line ... | cuongnt-2026/Trading-Assistant-AI | src/core/config.py | .py | d0bb7d7f8b5d5219 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
WebData - lay nen OHLC tu Twelve Data (API free) thay cho MT5.
Dung cho ban chay tren cloud (GitHub Actions), khong can MT5/Windows.
"""
import os
import time
import json
import urllib.request
import urllib.parse
from datetime import datetime
from src.market.candle import Candle
_TF_MAP = ... | cuongnt-2026/Trading-Assistant-AI | src/data/webdata.py | .py | 9bfdb86fbb1e7cba | 7 | 0 |
from typing import List
import pandas as pd
from ta.trend import ADXIndicator as TaADXIndicator
from src.market.candle import Candle
class ADXIndicator:
"""
Average Directional Index (ADX) Indicator.
"""
@staticmethod
def calculate(
candles: List[Candle],
period:... | cuongnt-2026/Trading-Assistant-AI | src/indicators/adx.py | .py | 862deff5ab04fd24 | 7 | 0 |
from typing import List
import pandas as pd
from ta.volatility import AverageTrueRange
from src.market.candle import Candle
class ATRIndicator:
"""
Average True Range (ATR) Indicator.
Đo độ biến động (volatility). Dùng để tham chiếu độ rộng SL/TP.
"""
@staticmethod
def calculate(
c... | cuongnt-2026/Trading-Assistant-AI | src/indicators/atr.py | .py | 6957ca6c3f959525 | 7 | 0 |
from typing import List
import pandas as pd
from src.market.candle import Candle
class BollingerBandsIndicator:
"""
Bollinger Bands (bien EMA): mid = EMA(period), bien = mid +/- mult * do lech chuan(period).
Tra ve (upper, mid, lower) tai nen cuoi cung.
"""
@staticmethod
def calculate(candl... | cuongnt-2026/Trading-Assistant-AI | src/indicators/bollinger.py | .py | 67f0e052e9af9ab7 | 7 | 0 |
from typing import List
import pandas as pd
from src.market.candle import Candle
class EMAIndicator:
"""
EMA (Exponential Moving Average) Indicator.
"""
@staticmethod
def calculate(
candles: List[Candle],
period: int,
) -> float:
"""
Calcula... | cuongnt-2026/Trading-Assistant-AI | src/indicators/ema.py | .py | 40286de419c59169 | 7 | 0 |
from typing import List
from src.market.candle import Candle
from src.indicators.ema import EMAIndicator
from src.indicators.adx import ADXIndicator
from src.indicators.atr import ATRIndicator
from src.indicators.rsi import RSIIndicator
from src.indicators.bollinger import BollingerBandsIndicator
class IndicatorServ... | cuongnt-2026/Trading-Assistant-AI | src/indicators/indicator_service.py | .py | 3e84d96227c66516 | 7 | 0 |
from typing import List
import pandas as pd
from ta.momentum import RSIIndicator as TaRSIIndicator
from src.market.candle import Candle
class RSIIndicator:
"""
Relative Strength Index (RSI) Indicator.
Đo động lượng (momentum), thang 0-100.
> 70 quá mua, < 30 quá bán.
"""
@staticmethod
... | cuongnt-2026/Trading-Assistant-AI | src/indicators/rsi.py | .py | ccdb1a10c4ed7350 | 7 | 0 |
import time
from datetime import datetime, timedelta
import MetaTrader5 as mt5
from src.market.candle import Candle
from src.market.timeframe import to_mt5
class MarketData:
"""Market data service for MetaTrader 5."""
# cache ten symbol da resolve de khoi do lai moi lan
_resolved = {}
@staticmetho... | cuongnt-2026/Trading-Assistant-AI | src/market/market_data.py | .py | 8f96e7e97e5e3148 | 7 | 0 |
import MetaTrader5 as mt5
TIMEFRAME_MAP = {
"M1": mt5.TIMEFRAME_M1,
"M5": mt5.TIMEFRAME_M5,
"M15": mt5.TIMEFRAME_M15,
"M30": mt5.TIMEFRAME_M30,
"H1": mt5.TIMEFRAME_H1,
"H4": mt5.TIMEFRAME_H4,
"D1": mt5.TIMEFRAME_D1,
}
def to_mt5(timeframe: str):
"""
Convert timefr... | cuongnt-2026/Trading-Assistant-AI | src/market/timeframe.py | .py | 4e7b99809035e241 | 7 | 0 |
"""
Notifier base class.
Định nghĩa interface chung cho mọi kênh thông báo.
Nhờ lớp trừu tượng này, sau này thêm Telegram / Zalo / SMS
chỉ cần tạo class mới kế thừa Notifier, không phải sửa Monitor.
"""
from abc import ABC, abstractmethod
class Notifier(ABC):
"""
Kênh thông báo trừu tượng.
"""
@abs... | cuongnt-2026/Trading-Assistant-AI | src/notifier/base.py | .py | 196671ca45a1e882 | 7 | 0 |
"""
Email notifier - gửi thông báo qua Gmail SMTP (App Password).
Dùng thư viện chuẩn của Python (smtplib, ssl, email) nên không cần
cài thêm gì. Chạy độc lập trên máy bạn hoặc trên VPS đều được.
"""
import smtplib
import ssl
from email.message import EmailMessage
from src.notifier.base import Notifier
class Email... | cuongnt-2026/Trading-Assistant-AI | src/notifier/email_notifier.py | .py | 64d5ef082e9a92c5 | 7 | 0 |
"""
Notifier factory.
Xây dựng notifier theo cấu hình. Hỗ trợ NHIỀU kênh cùng lúc
(NOTIFIER_CHANNEL = "email,ntfy,telegram").
Kênh thiếu cấu hình sẽ bị bỏ qua kèm cảnh báo, không làm dừng chương trình.
"""
from src.notifier.email_notifier import EmailNotifier
from src.notifier.telegram_notifier import TelegramNotifie... | cuongnt-2026/Trading-Assistant-AI | src/notifier/factory.py | .py | fbfd276860e86ae7 | 7 | 0 |
"""
MultiNotifier - gửi thông báo qua NHIỀU kênh cùng lúc (email + telegram + ntfy).
"""
from src.notifier.base import Notifier
class MultiNotifier(Notifier):
"""
Bọc nhiều notifier, gửi tới tất cả.
"""
def __init__(self, notifiers):
# notifiers: list các tuple (tên_kênh, notifier)
s... | cuongnt-2026/Trading-Assistant-AI | src/notifier/multi_notifier.py | .py | 867fee171d0fc084 | 7 | 0 |
"""
ntfy.sh notifier - báo tín hiệu về điện thoại qua app ntfy (MIỄN PHÍ).
Không cần tài khoản. Chỉ cần cài app "ntfy" và đăng ký 1 topic.
Dùng urllib (thư viện chuẩn) nên không cần cài thêm gì.
Cách dùng:
1. Cài app "ntfy" (Android/iOS) hoặc mở https://ntfy.sh
2. Đăng ký (subscribe) 1 topic tên khó đoán, ví ... | cuongnt-2026/Trading-Assistant-AI | src/notifier/ntfy_notifier.py | .py | d9dffb67e8b50065 | 7 | 0 |
"""
Telegram notifier - báo tín hiệu về điện thoại qua Telegram (MIỄN PHÍ).
Dùng urllib (thư viện chuẩn) nên không cần cài thêm gì.
Cách lấy TELEGRAM_BOT_TOKEN và TELEGRAM_CHAT_ID:
Xem docs/HUONG_DAN_BAO_DIEN_THOAI.md
"""
import urllib.parse
import urllib.request
from src.notifier.base import Notifier
class T... | cuongnt-2026/Trading-Assistant-AI | src/notifier/telegram_notifier.py | .py | 373099eafcfc9431 | 7 | 0 |
#!/usr/bin/env python3
"""
Multi-provider AI text extraction module.
Supports Anthropic, OpenAI, and Google AI for structured data extraction
from PDF text or any unstructured document content.
Usage:
from ai_extract import extract_fields
fields = extract_fields(
text="...raw PDF text...",
sc... | cardelljo/civic-dashboard-kit | src/toolkit/ai_extract.py | .py | 16a3352a2e94d19e | 7 | 0 |
"""
Generic ArcGIS Feature Service client.
Consolidates the per-script `arcgis_query()` helpers that 901justice duplicated
across fetch_crime_data.py, fetch_traffic_stops.py, and fetch_traffic_citations.py.
Prefers server-side aggregation (outStatistics + groupByFieldsForStatistics) so
callers never download full rec... | cardelljo/civic-dashboard-kit | src/toolkit/arcgis.py | .py | 3bb4f24154373642 | 7 | 0 |
"""
U.S. Bureau of Economic Analysis (BEA) Regional API client.
Same shape as toolkit.census.AcsClient / toolkit.fred.FredClient: a thin,
free-key-based client for the Regional dataset's GDP-by-area tables
(CAGDP1 nominal GDP, CAGDP9 real/chained GDP, CAGDP2 GDP by industry) --
the tables 901economy's GRP section need... | cardelljo/civic-dashboard-kit | src/toolkit/bea.py | .py | da50ee6e14b5906b | 7 | 0 |
"""
U.S. Census Bureau ACS and BLS API clients.
Generalized from 901justice's fetch_community_data.py: the Shelby County
constants become parameters so any dashboard (education, economic development)
can pull ACS variables for any geography without re-learning the API quirks —
detail vs. subject-table endpoints, heade... | cardelljo/civic-dashboard-kit | src/toolkit/census.py | .py | b5a88686db284e0b | 7 | 0 |
#!/usr/bin/env python3
"""
Publication eligibility gate.
Encodes a guardrail every dashboard using this toolkit should apply before a
figure leaves the dashboard as a standalone persuasive claim:
No sample, estimated, or unresolved-gap metric is packaged as a
persuasive standalone claim.
Every comms artifact... | cardelljo/civic-dashboard-kit | src/toolkit/eligibility.py | .py | 1d9044fda1223598 | 7 | 0 |
"""
Federal Reserve Economic Data (FRED) API client.
Same shape as toolkit.census.AcsClient: a thin, free-key-based series-fetch
client so any dashboard can pull a FRED series for any geography (a metro's
FRED series ID, e.g. Memphis MSA unemployment) without re-learning FRED's
response quirks -- the "." sentinel for ... | cardelljo/civic-dashboard-kit | src/toolkit/fred.py | .py | 72ada1ac03080587 | 7 | 0 |
"""
Append-only observations store: the source of truth ETL pipelines write to.
See docs/OBSERVATIONS_STORE_DESIGN.md for the full design and rationale. In
short: pipelines append `Observation` rows to a per-source NDJSON ledger under
data/observations/ (never rewritten — a re-fetch that revises a value just
appends a... | cardelljo/civic-dashboard-kit | src/toolkit/observations.py | .py | 7139ea75f1397961 | 7 | 0 |
"""
Postgres-backed indicators store for 901economy (or any future higher-volume dashboard).
Same design as toolkit/observations.py -- append-only, "newest row wins per
logical cell" -- ported to a live Postgres connection instead of git-committed
NDJSON materialized into an in-memory sqlite3 db at build time. The sch... | cardelljo/civic-dashboard-kit | src/toolkit/postgres_store.py | .py | 98d391ed859608f1 | 7 | 0 |
"""
Data snapshot contract helpers: the `_meta` provenance block.
Implements the writer and validator side of DATA_SNAPSHOT_CONTRACT.md. Every
data/*.json the dashboard publishes carries a `_meta` block declaring where the
data came from, when, by which script, and whether it is live or sample data.
The frontend's Dat... | cardelljo/civic-dashboard-kit | src/toolkit/snapshot.py | .py | 15048edd245e8905 | 7 | 0 |
"""
Integration tests for toolkit.boundaries against a real Postgres + PostGIS.
Same fixture pattern as test_postgres_store.py: skips entirely without
TOOLKIT_TEST_DATABASE_URL (see tests/test_ci_guards.py for the guard that
keeps an all-skipped run from reading as a pass). Needs PostGIS specifically
(ST_GeomFromGeoJS... | cardelljo/civic-dashboard-kit | tests/test_boundaries.py | .py | 72cf61a3b088994b | 7.5 | 0 |
"""
Guards against a green build that verified nothing.
`pytest` exits 0 when every test in `tests/test_postgres_store.py` skips for
want of `TOOLKIT_TEST_DATABASE_URL`, so a broken service container, a renamed
env var, or a dropped `env:` block in the workflow all read as a passing build.
That has already happened in... | cardelljo/civic-dashboard-kit | tests/test_ci_guards.py | .py | df65122c14fc7112 | 7.5 | 0 |
"""
The two halves of this package must agree on `DataStatus`.
docs/ARCHITECTURE.md §7 justifies shipping a Python distribution and a
TypeScript package from one repo partly on the grounds that it keeps the
`DataStatus` union next to the Python that reasons about the same values. This
test is what makes that a mechani... | cardelljo/civic-dashboard-kit | tests/test_data_status_union.py | .py | d4f2f6a0a6f89451 | 7.5 | 0 |
"""Unit tests for toolkit.geo's dashboard-agnostic helpers."""
from __future__ import annotations
from toolkit.geo import filter_by_name, nest_rings, point_in_ring, signed_area
def _feature(name: str) -> dict:
return {"type": "Feature", "geometry": None, "properties": {"NAME": name}}
def test_filter_by_name_k... | cardelljo/civic-dashboard-kit | tests/test_geo.py | .py | 4dec82737f72ee17 | 7.5 | 0 |
"""Offline fixtures for shared toolkit clients; no test performs network I/O."""
from datetime import datetime
from urllib.parse import parse_qs
from toolkit.arcgis import FeatureService, date_where
from toolkit.bea import BeaClient
from toolkit.census import AcsClient, bls_monthly_series
from toolkit.fred import Fred... | cardelljo/civic-dashboard-kit | tests/test_toolkit_clients.py | .py | 446ba59f3cee8da9 | 7.5 | 0 |
"""OwnVoice hook: identity injection.
Runs `own-voice.py` as a subprocess to verify two contracts:
1. Missing notes/self/ -> exit 0 with empty or minimal output (graceful no-op).
2. beliefs.md + focus.md present -> stdout carries an [OwnVoice] block.
`own-voice.py` honors `OPENCODE_MEMORY_NOTES_DIR` (Task 3.4) and f... | enkinvsh/crystallized | memory/tests/test_own_voice.py | .py | 2f256a94a86c72ab | 7.8 | 3 |
#!/usr/bin/env python3
"""
Apply docker/lake/ddl/lake.sql through the `lake` catalog. The `lake-ddl`
one-shot compose service runs this; it is idempotent, so a re-run on a live
warehouse is a no-op.
docker exec k2-spark-iceberg python3 /home/iceberg/lake/apply_ddl.py
docker exec k2-spark-iceberg python3 /home/... | rjdscott/k2-market-data-platform | docker/lake/apply_ddl.py | .py | 2352a30f0c5dd095 | 7.15 | 1 |
"""
Event bars — gold.bars: tick, volume and dollar bars over gold.trades at the
one canonical threshold per symbol in config/bars.yaml (ADR-029).
The bar is a *cumulative bucket*: for kind K with threshold T, a trade belongs
to bar k of its UTC day when k*T <= (cumulative K-total of the day's earlier
trades) < (k+1)*... | rjdscott/k2-market-data-platform | docker/lake/bars.py | .py | bb31081381656bb5 | 7.15 | 1 |
#!/usr/bin/env python3
"""
An L2 order book replayed from venue frames, with Kraken's CRC32 verification —
the pure core of the silver/gold book layers. No Spark, no pandas; the Spark
side (books.py) streams frames through it one connection at a time.
Everything is 1e-8 fixed point (int), exactly as services/capture-r... | rjdscott/k2-market-data-platform | docker/lake/book.py | .py | 3aeaa91b259ff55d | 7.15 | 1 |
#!/usr/bin/env python3
"""
Catalog-side helpers shared by every lake writer: snapshot bookkeeping, the
registry fetch, and the one way an audit row gets filed from a running job.
Split out of ingest.py when bronze.py (the per-venue decode) needed the same
five functions and importing ingest.py for them would have been... | rjdscott/k2-market-data-platform | docker/lake/catalog.py | .py | 2973781e0d16f432 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Prefect flows for the v3 lake: `lake-ingest-5min` and `lake-maintenance-daily`.
Both dispatch the same way v2's offload flows do — `docker exec
k2-spark-iceberg python3 …` over the mounted Docker socket — rather than
running Spark inside the worker. That keeps one Spark image, one set of jar... | rjdscott/k2-market-data-platform | docker/lake/flows/lake_flows.py | .py | e6dcdfa20304a570 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Gold — the canonical cross-venue surface, derived from silver only (ADR-026).
gold.trades silver.trades_<venue> WHERE NOT venue_replay, one schema, 1e-8 fixed point
gold.dim_instrument config/instruments.yaml, rewritten every run
gold.dim_venue one row per venue, ... | rjdscott/k2-market-data-platform | docker/lake/gold.py | .py | 8e7ce08b82a8c61a | 7.15 | 1 |
#!/usr/bin/env python3
"""
The instrument registry (config/instruments.yaml) as silver needs it: the
native -> canonical symbol map per venue, and nothing else.
Pure — no Spark. `canonical()` raises on an unknown native symbol on purpose:
the registry's own contract (its header comment) is that a loader which cannot
f... | rjdscott/k2-market-data-platform | docker/lake/instruments.py | .py | d3b3ff5cdcbf7309 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Offset bookkeeping for docker/lake/ingest.py. Pure functions — no Spark, no
network, no clock. tests/test_lake_offsets.py runs against this file directly.
**The exactly-once contract lives here.** There is no watermark table. The Kafka
offsets a run consumed are written into the Iceberg snap... | rjdscott/k2-market-data-platform | docker/lake/offsets.py | .py | 36f6f96cd658fa48 | 7.15 | 1 |
#!/usr/bin/env python3
"""
Silver per venue — bronze frames typed, annotated and flattened to one row per
trade, every delivery kept (ADR-026, plan 004). Trades in this module; books
follow once Kraken's checksum verification has the `instrument` frames beside
the book frames.
silver.trades_binance <- bronze.bi... | rjdscott/k2-market-data-platform | docker/lake/silver.py | .py | c1e5b6a207f63e3c | 7.15 | 1 |
#!/usr/bin/env python3
"""
Degradation demo script.
Demonstrates graceful degradation under load by:
1. Starting at NORMAL
2. Increasing load to trigger degradation
3. Showing metrics and behavior at each level
4. Recovering back to NORMAL
Usage:
python scripts/demo_degradation.py
python scripts/demo_degradat... | rjdscott/k2-market-data-platform | legacy/v1/demos/scripts/resilience/demo_degradation.py | .py | 39a62ffb917e3b75 | 7.15 | 1 |
"""Clean all demo data from K2 platform while keeping Docker containers running.
This script removes:
- All data from Iceberg tables (trades_v2, quotes_v2)
- All Kafka messages from topics
- Keeps Docker containers, schemas, and table definitions intact
Use this to get a clean slate without restarting the entire infr... | rjdscott/k2-market-data-platform | legacy/v1/demos/scripts/utilities/clean_demo_data.py | .py | 39cb8f735c79bb20 | 7.15 | 1 |
#!/usr/bin/env python3
"""Initialize infrastructure for E2E crypto streaming demo.
This script sets up:
1. V2 crypto schemas in Schema Registry
2. Kafka topics for crypto trades
3. Iceberg trades_v2 table
4. Validates all components are ready
Run this after starting Docker Compose services.
Usage:
python scripts... | rjdscott/k2-market-data-platform | legacy/v1/demos/scripts/utilities/init_e2e_demo.py | .py | 5ad4808c99033c3c | 7.15 | 1 |
#!/usr/bin/env python3
"""Pre-demo validation script for K2 platform.
Run this script 30 minutes before demo to catch issues early.
Usage:
uv run python scripts/pre_demo_check.py
uv run python scripts/pre_demo_check.py --full # Includes backup material checks
"""
import subprocess
from pathlib import Path
... | rjdscott/k2-market-data-platform | legacy/v1/demos/scripts/validation/pre_demo_check.py | .py | ab1c94166d4f0ffc | 7.15 | 1 |
#!/usr/bin/env python3
"""Binance streaming service - production daemon.
This service connects to Binance WebSocket API, streams live trades,
converts them to v2 schema format, and publishes to Kafka.
Architecture:
Binance WebSocket → on_message → MarketDataProducer → Kafka
Features:
- Real-time trade streaming ... | rjdscott/k2-market-data-platform | legacy/v1/scripts/binance_stream.py | .py | c36402a7dcbc2314 | 7.15 | 1 |
#!/usr/bin/env python3
"""Binance streaming service - RAW data to Bronze.
This service connects to Binance WebSocket API, streams live trades,
and publishes RAW data to Kafka (no V2 conversion).
Architecture:
Binance WebSocket → on_message → RawBinanceProducer → Kafka (raw)
This implements industry best practice... | rjdscott/k2-market-data-platform | legacy/v1/scripts/binance_stream_raw.py | .py | 099d28d4d25e1790 | 7.15 | 1 |
#!/usr/bin/env python3
"""Kafka → Iceberg Consumer for Cryptocurrency Trades (v2 Schema).
This script consumes trade messages from the market.crypto.trades Kafka topic
and writes them to the Iceberg trades_v2 table. Designed for production use
with the Binance WebSocket streaming service.
Features:
- Consumes from ma... | rjdscott/k2-market-data-platform | legacy/v1/scripts/consume_crypto_trades.py | .py | 442e210bd64bce7a | 7.15 | 1 |
#!/usr/bin/env python3
"""
Create sample dataset for K2 Market Data Platform.
Extracts a time-based subset of the raw Australian equity data to create
a manageable sample dataset suitable for GitHub distribution and demos.
Strategy: Keep 5 complete trading days (March 10-14, 2014) of tick-level data
to demonstrate se... | rjdscott/k2-market-data-platform | legacy/v1/scripts/create_sample_dataset.py | .py | ab8bbe6af72c5c18 | 7.15 | 1 |
import logging
from typing import Any, Literal, NotRequired, TypedDict
type Color = Literal[
"green", # completado
"yellow", # pausado
"red", # error
"blue", # en proceso
"gray", # cancelado
"orange", # error parcial
"purple", # esperando selección
"cyan", # extrayendo informaci... | chomusuke-mk/vidra-backend | src/tipos.py | .py | 5a509686a3ea0399 | 7 | 0 |
"""Derive every fixture from the per-deploy FLAG_SEED.
Nothing in this problem ships a committed constant a learner could memorize. Same
seed, same fixtures (so a session is reproducible and debuggable); different seed,
different fixtures (so a hard-coded answer from someone else's run does not carry).
Parameters sta... | susumutomita/TenkaCloudChallenge | challenges/ac26-bridge-experiment/local/fixtures/generate.py | .py | 4c5719f422d1a6d6 | 7.15 | 1 |
"""Public Participant Workbench: the Portal editor API, a fail-closed verifier proxy,
and nothing that can derive an answer.
This process never grades a checkpoint locally -- every `/verify` request is forwarded
to the Compose-internal verifier, and any missing or invalid verifier response becomes
a canonical `correct... | susumutomita/TenkaCloudChallenge | challenges/ac26-bridge-experiment/local/participant/server.py | .py | f442c09a811c78d3 | 7.15 | 1 |
"""`make inspect` — show the worked example and the list with one number out of place.
Everything here is derived from FLAG_SEED, so what you see is yours: copying
another learner's numbers will not help you.
The command is called `inspect`; none of the boxes you fill in are. It only shows
evidence, and it never prod... | susumutomita/TenkaCloudChallenge | challenges/ac26-bridge-experiment/local/show.py | .py | 3f82db875d090f79 | 7.15 | 1 |
"""Hidden tests. Run by /verify against a copy of the learner's file, never shown to them.
Three jobs:
1. Parameters the public tests never use (several moduli, negative step, zero step,
start >= modulus, zero rounds).
2. Metamorphic properties, so memorizing one output cannot pass.
3. Negative properties, ... | susumutomita/TenkaCloudChallenge | challenges/ac26-bridge-experiment/local/tests/hidden/check_counter.py | .py | 877593a9f30c35eb | 7.65 | 1 |
"""Public tests: they show you the shape of the answer. They do not prove it.
Read them, then read `misconception.public-tests-are-complete` in the README. These
tests pass for at least one implementation that the hidden tests reject.
"""
from __future__ import annotations
import json
import os
import sys
from pathl... | susumutomita/TenkaCloudChallenge | challenges/ac26-bridge-experiment/local/tests/public/test_counter.py | .py | af65ca73e94244ed | 7.65 | 1 |
"""Both sides of the calt sweep's depth-2 question, measured identically so they can be compared.
For each pair the sweeps guard, and for each side (prefix / suffix), collect the set of renderings OF THE PAIR ITSELF (the shaped glyphs whose HarfBuzz clusters fall inside the pair's two input codepoints) reachable when ... | adiabatic/abbots-morton-spaceport | bench-the-rebuild/cut-the-work/depth2_states.py | .py | f8430cefe94ed1b1 | 7.24 | 2 |
"""Utility helpers shared across modules."""
from __future__ import annotations
import os
import re
import shutil
from pathlib import Path
DEFAULT_SEGMENT_MINUTES = 30
DEFAULT_AUDIO_QUALITY = "8" # yt-dlp uses 0(best) to 10(worst); low is fine for speech-only audiobooks
def ensure_dependency(binary: str) -> None:... | kabirnayeem99/YtdlAudioBookScrapper | ytdl_audiobook_scraper/utils.py | .py | 6827f81a0def541b | 7 | 0 |
#!/usr/bin/env python3
from __future__ import annotations
import json
import os
import random
import re
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from itertools import combinations
from pathlib import Path
from typing import Any
from tqdm import tqdm
from openai_chat import APIConnec... | realyoume/title_it_right | src/judge/compare.py | .py | a3565a9c0f5d8eae | 7 | 0 |
"""
Seed data for the Tea Auction app, sourced from real, publicly reported
Mombasa Tea Auction (EATTA) figures — not synthetic/fabricated records.
Sources (fetched 26 Aug 2026):
- EATTA "Mombasa Tea Auction Performance 2026" Sale 17 report
https://eatta.co.ke/documents/Sale%2017%202026%20auction%20report.pdf
... | OmoroJr/tea_auction | tea_auction/seed/seed_eatta_data.py | .py | 6bee41d24a9be2e9 | 7 | 0 |
from typing import Any, Dict
import pandas as pd
def _is_id_like(col_name: str, series: pd.Series) -> bool:
"""Check if a column is likely an identifier column."""
name_lower = col_name.lower()
if any(
keyword in name_lower
for keyword in ["id", "code", "key", "number"]
):
ret... | nitin28061999/AI_DATA_ANALYST | data_profile.py | .py | d1f061d3de5ab389 | 7 | 0 |
"""record item creation source
Revision ID: 0002
Revises: 0001
Create Date: 2026-08-21 18:00:00.000000
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0002"
down_revision: str | None = "0001"
branch_labels: str | Sequence[str] | None = None
depends_on: str | ... | jinsoowhang/dofus-touch-economy-analytics | migrations/versions/0002_item_creation_source.py | .py | 6bc8079151646755 | 7 | 0 |
"""track active and completed sale listings
Revision ID: 0003
Revises: 0002
Create Date: 2026-08-21 17:00:00.000000
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0003"
down_revision: str | None = "0002"
branch_labels: str | Sequence[str] | None = None
depen... | jinsoowhang/dofus-touch-economy-analytics | migrations/versions/0003_sale_listings.py | .py | 923eaa55d162de83 | 7 | 0 |
"""add editable sale asking prices
Revision ID: 0004
Revises: 0003
Create Date: 2026-08-21 17:30:00.000000
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0004"
down_revision: str | None = "0003"
branch_labels: str | Sequence[str] | None = None
depends_on: st... | jinsoowhang/dofus-touch-economy-analytics | migrations/versions/0004_sale_asking_price.py | .py | 6d31cbd0b4a059cf | 7 | 0 |
"""record locally cached item icon sources
Revision ID: 0005
Revises: 0004
Create Date: 2026-08-21 18:00:00.000000
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0005"
down_revision: str | None = "0004"
branch_labels: str | Sequence[str] | None = None
depend... | jinsoowhang/dofus-touch-economy-analytics | migrations/versions/0005_item_icon_source.py | .py | 6615baebab45e7aa | 7 | 0 |
"""record Dofus Touch item weight
Revision ID: 0006
Revises: 0005
Create Date: 2026-08-22 20:30:00.000000
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0006"
down_revision: str | None = "0005"
branch_labels: str | Sequence[str] | None = None
depends_on: str... | jinsoowhang/dofus-touch-economy-analytics | migrations/versions/0006_item_weight.py | .py | aef74b49163c597f | 7 | 0 |
"""record authoritative Dofus Touch catalog status
Revision ID: 0007
Revises: 0006
Create Date: 2026-08-23 21:45:00.000000
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0007"
down_revision: str | None = "0006"
branch_labels: str | Sequence[str] | None = Non... | jinsoowhang/dofus-touch-economy-analytics | migrations/versions/0007_touch_catalog_status.py | .py | 0841ecf7e7bba1c8 | 7 | 0 |
"""snapshot recipe cost when a listing is sold
Revision ID: 0008
Revises: 0007
Create Date: 2026-08-24 20:00:00.000000
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0008"
down_revision: str | None = "0007"
branch_labels: str | Sequence[str] | None = None
de... | jinsoowhang/dofus-touch-economy-analytics | migrations/versions/0008_sale_recipe_cost_snapshot.py | .py | 4cf88ddf2c5722e2 | 7 | 0 |
from sqlalchemy import or_
from sqlalchemy.sql.elements import ColumnElement
TOUCH_CATALOG_VERIFIED = "verified"
TOUCH_CATALOG_EXCLUDED = "excluded"
TOUCH_CATALOG_EXCLUSION_REASON = (
"Normalized item name absent from Ankama's live Dofus Touch item catalog."
)
def active_catalog_item_clause(item_model) -> Column... | jinsoowhang/dofus-touch-economy-analytics | src/dofus_touch_economy/catalog_scope.py | .py | cea6c53cda9535c7 | 7 | 0 |
"""Launch the ToolRGS real-world grasp GUI."""
import argparse
from pathlib import Path
from deployment.config import load_deployment_config
from deployment.gui import run_gui
DEFAULT_SAMPLE_IMAGE = "assets/grasp_tools/graspall/000000000000.jpg"
GI_REALSENSE_PIPELINE = (
"shmsrc socket-path=/home/raico-hri/v1/k... | mengyuanuom/ToolRGS | deploy_gui.py | .py | f01b0313064246d0 | 7 | 0 |
"""Launch ToolRGS with the lab GI/GStreamer RealSense shared-memory stream."""
from deploy_gui import apply_camera_preset, apply_runtime_overrides, parse_args
from deployment.config import load_deployment_config
from deployment.gui import run_gui
def prepare_gi_config(config):
"""Apply the designed GI transport ... | mengyuanuom/ToolRGS | deploy_gui_gi.py | .py | 6db5a072c1158b40 | 7 | 0 |
"""Launch the safe RealSense-only ToolRGS demo (no GI and no robot output)."""
from deploy_gui import apply_camera_preset, apply_runtime_overrides, parse_args
from deployment.config import load_deployment_config
from deployment.gui import run_gui
def prepare_realsense_demo_config(config):
"""Open RealSense direc... | mengyuanuom/ToolRGS | deploy_gui_realsense.py | .py | 76727633f31147ba | 7 | 0 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwightma... | mengyuanuom/ToolRGS | model/dinov2/layers/block.py | .py | 55f5db571c61cf6b | 7 | 0 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwightma... | mengyuanuom/ToolRGS | model/dinov2/layers/drop_path.py | .py | b9f8236e86054b9d | 7 | 0 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
# https://github.com/rwightma... | mengyuanuom/ToolRGS | model/dinov2/layers/patch_embed.py | .py | 40da6add3d811198 | 7 | 0 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the Apache License, Version 2.0
# found in the LICENSE file in the root directory of this source tree.
# References:
# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
# https://github.com/rwightman/... | mengyuanuom/ToolRGS | model/dinov2/models/vision_transformer.py | .py | 2008a1382d49f035 | 7 | 0 |
"""Backward-compatible DrogOff with optional Offset-Transport routing."""
from .drogoff import DROGOFF as BaseDROGOFF
from .transport_projector import OffsetTransportProjector
class DROGOFFTransport(BaseDROGOFF):
"""Enable grasp-only geometric routing through configuration.
With ``offset_transport_enabled``... | mengyuanuom/ToolRGS | model/drogoff_transport.py | .py | 92cd719d35b81361 | 7 | 0 |
"""Dependency-injected service contract for graph nodes."""
from __future__ import annotations
from typing import Protocol
from bms_agent.control import (
ControlProposal,
FallbackDecision,
ObservationEnvelope,
ValidationResult,
)
from bms_agent.graph.state import (
AppliedAction,
CompletionR... | pragadesh113/eco-loop-autonomous-bms | src/bms_agent/graph/runtime.py | .py | d1321d8d68173302 | 7 | 0 |
"""Model-independent synchronous chat boundary for advisory providers."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Literal, Protocol
@dataclass(frozen=True, slots=True)
class ChatMessage:
role: Literal["system", "user"]
content: str
@dataclass(frozen=Tru... | pragadesh113/eco-loop-autonomous-bms | src/bms_agent/llm/client.py | .py | fb51541efbaceb49 | 7 | 0 |
"""
Framework code for the Berkeley CS168 Distance Vector router project
Authors:
zhangwen0411, MurphyMc, lab352
"""
# NOTE: This file is written in POX style.
import sim.api as api
# Host discovery packets are treated as an implementation detail --
# they're how we know when to call add_static_route(). Thus, ... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/cs168/dv.py | .py | 0ca60a6c1ab99812 | 7 | 0 |
import sim.api as api
from sim.basics import *
class Hub(api.Entity):
"""
A dumb hub.
This just sends every packet it gets out of every port. On the plus side,
if there's a way for the packet to get to the destination, this will find it.
On the down side, it's probably pretty wasteful. On the *... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/examples/hub.py | .py | e389c1ec5d72f9c8 | 7 | 0 |
"""
This adds a utility for NetVis
If you run this module and set MegaHost to be the default host type, you get
a new feature. Select a host and press Shift-1 (by default), and all other
hosts will send a ping to it simultaneously.
In order for this to work, the hosts need to be MegaHosts, so you probably
want to pu... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/examples/megaping.py | .py | aeeef34d2e3b95d5 | 7 | 0 |
"""
A simple test of a learning switch
Creates some hosts connected to a single central switch.
Sends some pings.
Makes sure the expected number of pings and pongs arrive.
"""
import sim
import sim.api as api
import sim.basics as basics
class TestHost(basics.BasicHost):
"""
A host that counts pings and pong... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/examples/test_learning.py | .py | 243988f16f105243 | 7.5 | 0 |
"""
A simple test for routers
Creates some hosts connected to a single central router.
Sends some pings.
Makes sure the right number of pings reach expected destinations and no pings
reach unexpected destinations.
"""
import sim
import sim.api as api
import sim.basics as basics
class GetPacketHost(basics.BasicHost)... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/examples/test_simple.py | .py | 70886595473c3e07 | 7.5 | 0 |
"""
Your learning switch warm-up exercise for CS-168
Start it up with a commandline like...
./simulator.py --default-switch-type=learning_switch topos.rand --links=0
"""
import sim.api as api
import sim.basics as basics
class LearningSwitch(api.Entity):
"""
A learning switch
Looks at source addresse... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/learning_switch.py | .py | 6c6337a5239cdabb | 7 | 0 |
# ######################### LICENSE ############################ #
# Copyright (c) 2005-2018, Michele Simionato
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# Redistributions of so... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/lib/decorator.py | .py | 1f04da0fc8ebf658 | 7 | 0 |
# -*- coding: utf-8 -*-
# Copyright (C) 2011-2018 by
# Nicholas Mancuso <nick.mancuso@gmail.com>
# All rights reserved.
# BSD license.
# Copyright 2016-2018 NetworkX developers.
# NetworkX is distributed under a BSD license
#
# Authors: Nicholas Mancuso (nick.mancuso@gmail.com)
# Jeffery Fink... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/lib/networkx/algorithms/approximation/clique.py | .py | 5eeac6cba8a4aaf9 | 7 | 0 |
# -*- coding: utf-8 -*-
# Copyright (C) 2011-2012 by
# Nicholas Mancuso <nick.mancuso@gmail.com>
# All rights reserved.
# BSD license.
"""Functions for finding node and edge dominating sets.
A `dominating set`_ for an undirected graph *G* with vertex set *V*
and edge set *E* is a subset *D* of *V* such that ev... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/lib/networkx/algorithms/approximation/dominating_set.py | .py | 9d0b1a6e61b3023f | 7 | 0 |
""" Fast approximation for k-component structure
"""
# Copyright (C) 2015 by
# Jordi Torrents <jtorrents@milnou.net>
# All rights reserved.
# BSD license.
import itertools
from collections import defaultdict, Mapping
import networkx as nx
from networkx.exception import NetworkXError
from networkx.utils imp... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/lib/networkx/algorithms/approximation/kcomponents.py | .py | 0583cf50c544336b | 7 | 0 |
from itertools import combinations, chain
from networkx.utils import pairwise, not_implemented_for
import networkx as nx
__all__ = ["metric_closure", "steiner_tree"]
@not_implemented_for("directed")
def metric_closure(G, weight="weight"):
"""Return the metric closure of a graph.
The metric closure of a gra... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/lib/networkx/algorithms/approximation/steinertree.py | .py | 2c628d72ac45416b | 7 | 0 |
# test_clique.py - unit tests for the approximation.clique module
#
# Copyright 2015 NetworkX developers.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
"""Unit tests for the :mod:`networkx.algorithms.approximation.clique`
module.
"""
from __... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/lib/networkx/algorithms/approximation/tests/test_clique.py | .py | 7b3853fa44934268 | 7.5 | 0 |
#!/usr/bin/env python
from nose.tools import ok_
from nose.tools import eq_
import networkx as nx
from networkx.algorithms.approximation import min_weighted_dominating_set
from networkx.algorithms.approximation import min_edge_dominating_set
class TestMinWeightDominatingSet:
def test_min_weighted_dominating_set(s... | durgesh-k-sharma/cs168-fa26-proj2-routing | simulator/lib/networkx/algorithms/approximation/tests/test_dominating_set.py | .py | c56326fe66190ea5 | 7.5 | 0 |
"""Endpoint приёма ANPR-событий: POST /api/v1/access/camera-events/anpr (§13.1).
Принимает ANPR-DTO от edge/камеры, вызывает идемпотентный ingestion и возвращает
решение (+ команду для allow — fast-path заготовка §9.2). Публичного
``/access-decisions`` нет (§13.2): решение принимается ВНУТРИ ingestion, нельзя
вызвать ... | a-afanasyev/Infrasafe_bot | access_control/api/camera_events.py | .py | a28b4173e20e98ad | 7 | 0 |
"""Durable channel barrier_commands: long-poll lease + compare-and-set ACK (§9.2, §13.1).
Endpoints (edge ↔ backend, пилот — durable доставка команд шлагбаума):
* ``GET /api/v1/access/edge/{controller_id}/commands/next`` — атомарно лизит ОДНУ
pending-команду ТОЛЬКО этого контроллера (``FOR UPDATE SKIP LOCKED``); l... | a-afanasyev/Infrasafe_bot | access_control/api/commands.py | .py | 2c5b90a060388ab9 | 7 | 0 |
"""ADMIN-эндпоинт диагностики точки въезда: синтетический ANPR через Decision Engine.
Замена камеры для приёмки (§6.1, §7, §11, §15): ``system_admin`` шлёт синтетическое
ANPR-событие на контроллер серверно (без device-auth — это аутентифицированное
admin-действие), оно проходит ТОТ ЖЕ Decision Engine, что и реальное с... | a-afanasyev/Infrasafe_bot | access_control/api/diagnostics.py | .py | b3538f04d0d083dd | 7 | 0 |
"""WRITE-эндпоинты менеджера (§13.2, §6.2, §4 п.7).
Менеджерские операции записи поверх общей базы access_control (USER-API, JWT/
cookie — ``require_approved_roles``, НЕ device-auth):
* ``POST /api/v1/access/vehicles`` — создать постоянный авто (+ привязка/правило);
* ``PATCH /api/v1/access/vehicles/{id}/status`` — ... | a-afanasyev/Infrasafe_bot | access_control/api/management.py | .py | f51941496acbfe99 | 7 | 0 |
"""Health/latency metrics endpoints (§10.2, §14.2 п.17).
Два эндпоинта:
* ``GET /metrics`` — текстовый формат Prometheus (scrape). Латентность по фазам
(ingestion/decision/db/relay) + gauge'и очереди barrier_commands.
* ``GET /api/v1/access/metrics`` — JSON-сводка: перцентили задержки по фазам,
бюджет §10.2 (deci... | a-afanasyev/Infrasafe_bot | access_control/api/metrics.py | .py | 8c26c6fe7ac82572 | 7 | 0 |
"""Operator/Admin API резолюции и ручного открытия (§13.2, §6.3).
Endpoints (USER-API, существующая JWT/cookie-аутентификация, НЕ device-auth):
* ``POST /api/v1/access/events/{event_id}/resolve`` — резолюция manual_review
(manual_open | deny), идемпотентна по event/decision (§9.5);
* ``POST /api/v1/access/barriers/... | a-afanasyev/Infrasafe_bot | access_control/api/operator.py | .py | d38965d292858214 | 7 | 0 |
"""Общие хелперы api-роутеров access_control (A6-P2-50).
До дедупа эти определения были посимвольно скопированы по роутерам:
``DEFAULT_LIMIT``/``MAX_LIMIT`` ×4 (equipment, parking_admin, registry,
resident), ``_limit``/``_limit_q`` ×4, ``_raise_404`` ×2, ``_Frozen`` ×3.
Роутеры импортируют отсюда под привычными приват... | a-afanasyev/Infrasafe_bot | access_control/api/pagination.py | .py | 1f4ee15f20813572 | 7 | 0 |
"""WebSocket-панель охраны: live-трансляция событий доступа (§9.6, §15.13).
Endpoint ``/ws/v1/access/security`` принимает (§9.6):
* защищённую httpOnly cookie существующей web-сессии (``uk_access``); ИЛИ
* JWT в ПЕРВОМ WS-сообщении для cookieless-клиента (``{"token": "<jwt>"}``).
JWT в query string ЗАПРЕЩЁН (§9.6): ... | a-afanasyev/Infrasafe_bot | access_control/api/ws_security.py | .py | 723be5c2b666407a | 7 | 0 |
"""Сборка FastAPI-приложения сервиса контроля доступа (ТЗ §1).
Фабрика ``create_app()`` строит приложение и подключает все пилотные роутеры
(§13): health, ingestion, edge long-poll/ack, edge equipment, operator/admin,
WS-панель охраны и health/latency-метрики (§10.2). Swagger (`/docs`,
`/openapi.json`) по умолчанию **... | a-afanasyev/Infrasafe_bot | access_control/app/main.py | .py | 20f389265a0e5e01 | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.