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
"""Posting the bot's own crashes to a channel. Every check here is about the logger not making things worse. It is called from inside exception handlers, so anything it raises arrives while something else is already broken, and anything it repeats arrives once per occurrence of a fault that may be firing per message. ...
tetooooooooooooooooooooooooooo/danito
tests/test_errorlog.py
.py
b1bb39d82e7d14bb
7.5
0
import requests from lxml import etree from datetime import datetime, timedelta def initFile(file_name): """ 初始化文件,写入头部信息,包括文件名、总数计数器、更新时间等。 """ # 获取当前的 UTC 时间 utcTime = datetime.utcnow() # 将 UTC 时间转换为 CST (UTC+8) chinaTime = utcTime + timedelta(hours=8) # 格式化时间为字符串 localTime = chin...
iuu666/ASN.China
scripts/ChinaASN.py
.py
3c2579e3c0be4fa5
7
0
# qudas & pipline from qudas.pipeline.steps import OptimizerMixin # module from amplify import VariableGenerator, Model, FixstarsClient, solve, Poly from datetime import timedelta import numpy as np class AnnealFMQA(OptimizerMixin): """FMQAのアニーリング処理 Args: OptimizerMixin: qudasの最適化用mixinクラス """ ...
devel-system/qudas
examples/fmqa/anneal_fmqa.py
.py
ebca3524b86931ae
7.15
1
"""レガシー実験用 FMQA パイプライン(元 test/fmqa.py)。examples/fmqa/main.py とは別物。""" import numpy as np from typing import Callable, Any, Tuple import torch import torch.nn as nn from torch.utils.data import TensorDataset, DataLoader, random_split from tqdm.auto import tqdm, trange import copy from amplify import VariableGenerator, ...
devel-system/qudas
examples/fmqa/legacy_torch_fmqa_pipeline.py
.py
dc71197726e3bc28
7.15
1
from src.Machines.SmartCam.Camera import Camera from src.uploader import Uploader from datetime import datetime import timeit import os import shutil import hashlib class SmartCam: """ Iterates through the SmartCam machines in the register.txt file and processes the data. Attributes ---------- ...
SNF-Root/Smart-Lab
src/Machines/SmartCam/SmartCam.py
.py
b9ea9eaf8945e65b
7.15
1
"""Code-revision snapshot and import-time loaded-code proof for one Analysis Run. The matchup script must bind a run id to the exact analysis code Python actually loaded. A disk-only git snapshot cannot prove that: the entry script and ``code_revision`` itself are already loaded before any snapshot can be taken, so a ...
crf04/statsplus-backend
analysis/nba-archetypes/scripts/code_revision.py
.py
e84bd74c5033a40a
7
0
"""Application factory for the NBA stats backend.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from flask import Flask logger = logging.getLogger(__name__) def create_app(config_overrides: dict[str, Any] | None = None) -> "Flask": """Create a...
crf04/statsplus-backend
app/__init__.py
.py
4e9270f62e77160d
7
0
"""One authority for exact durations, time windows, and the freshness boundary. Three seams age the same observation: the provider snapshot cache decides whether a Redis value may be served, the comparison board decides whether a snapshot may enter a Comparison Group, and the configuration boundary decides which windo...
crf04/statsplus-backend
app/domain/freshness.py
.py
de3f260fbc47db46
7
0
"""Canonical classification and cohort vocabulary for matchup parity. The legacy comparator and the activation gate must agree on which findings are non-adjudicable. Keep this module dependency-free so both sides consume the same contract without importing one another. """ from __future__ import annotations CLASSI...
crf04/statsplus-backend
app/domain/matchup_parity_contract.py
.py
67a3ac5252633a79
7
0
"""Small closed NBA event facts shared by normalization and slate reads.""" from __future__ import annotations from collections.abc import Iterable, Mapping from dataclasses import dataclass from enum import IntEnum import re class NBAGameStatus(IntEnum): """Status codes published by the NBA schedule feed.""" ...
crf04/statsplus-backend
app/domain/nba_events.py
.py
91d9ef56751a7ff0
7
0
"""Canonical encoding and integrity checks for immutable publications.""" from __future__ import annotations import hashlib import hmac import json from typing import Any def canonical_publication_json(value: Any) -> str: """Encode one publication document in its persisted canonical form.""" return json.du...
crf04/statsplus-backend
app/domain/publication_integrity.py
.py
6e249aa07d0693de
7
0
"""America/New_York slate-day timestamp boundaries.""" from __future__ import annotations from datetime import date, datetime, time, timedelta, timezone from zoneinfo import ZoneInfo from app.domain.utc import assume_utc EASTERN = ZoneInfo("America/New_York") def slate_day_bounds_utc(slate_date: date) -> tuple[d...
crf04/statsplus-backend
app/domain/slate_time.py
.py
71444f0ee9cc4f2a
7
0
"""Typed, immutable statistic matching values shared by providers and services. This module deliberately has no provider or catalog imports. It owns the closed vocabularies a statistic match is built from — scoring periods, units, states, and unmapped reasons — so providers can carry a resolved match without introduc...
crf04/statsplus-backend
app/domain/statistics.py
.py
2d828e694026aa6c
7
0
"""Application errors and the public HTTP error contract. Routes and services raise the errors in this module when they can describe a failure safely. Flask converts them to one predictable JSON shape at the application boundary. The public message is deliberately separate from the optional detail so provider respon...
crf04/statsplus-backend
app/errors.py
.py
1b479d3a8378c8ff
7
0
""" SQLAlchemy models for NBA Game Logs application. This module sets up the SQLAlchemy declarative base and provides the foundation for ORM models. """ from sqlalchemy.engine import Engine from sqlalchemy.orm import declarative_base, sessionmaker import logging logger = logging.getLogger(__name__) # Create the dec...
crf04/statsplus-backend
app/models/__init__.py
.py
6e7d3a4a6dafaef5
7
0
"""Application-owned canonical athlete catalog schema. The catalog is deliberately separate from the bundled NBA demo tables. A row's identity is the provider's stable NBA player ID plus an explicit season; display names and team assignments can therefore change without rewriting historical seasons. """ from __futur...
crf04/statsplus-backend
app/models/athlete_catalog.py
.py
fbab84f32a51e820
7
0
"""Application-owned persistence models for provider athlete identity. The provider athlete ID is evidence, not a canonical identity. Mapping rows therefore retain the source labels and team facts that led to a decision while the append-only decision log records every automatic or operator action. """ from __future_...
crf04/statsplus-backend
app/models/athlete_mapping.py
.py
7eb4c3e8554ed18e
7
0
"""Durable facts for the governed Canonical Game Ledger. The ledger is deliberately additive to the ``player_game_logs`` tables from #66. A game is the unit of publication: the game identity, both team fact sets, and every participating player fact are replaced together. The tables store count primitives only; rates...
crf04/statsplus-backend
app/models/canonical_game_ledger.py
.py
eb23171ec03cd6f8
7
0
import argparse import json from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent CFG_DIR = BASE_DIR / "CFG" KEY_DIR = BASE_DIR / "KEY" RYM_DIR = BASE_DIR / "RYM" def load_json(path: Path): """Load a JSON file and return its data.""" with path.open() as f: return json.load(f) d...
SYSTEMS-OPERATOR/BOX
scripts/summary.py
.py
178886075237e3b9
7
0
"""SOPHY Hourly Recollection Harness. This deterministic harness computes a local digest, attempts to enrich context from previous recollection artifacts, and returns a strict schema payload. """ from __future__ import annotations import datetime import glob import json from typing import Any SCHEMA = { "timest...
SYSTEMS-OPERATOR/BOX
sophy_hourly_recollection/harness.py
.py
918574102c514811
7
0
#!/usr/bin/env python3 """Generate a deterministic recollection artifact in ``recollections/``.""" from __future__ import annotations import json from datetime import datetime, timezone from pathlib import Path OUTPUT_DIR = Path("recollections") def build_payload(summary: str = "Automated recollection run") -> dic...
SYSTEMS-OPERATOR/BOX
tools/recollect.py
.py
6a7c85b009c95825
7
0
"""Schreiben, das einen Stromausfall uebersteht. ``pfad.write_text(...)`` ueberschreibt die Datei an Ort und Stelle. Faellt der Strom mittendrin aus, liegt danach die halbe Datei da - genau der Fall, den Loop 13 aufraeumen musste und Loop 21 in FPM noch einmal fand. Drei Dinge gehoeren dazu, und keines allein reicht:...
sloogy/Kontaktmanager
freizeitmanager/atomic_write.py
.py
43e510a4ea6e5f47
7
0
"""Wo die Markenbilder liegen - im Quellbaum wie im gebauten Paket. Der FreizeitManager trat bis hierhin ohne Bild auf: Das Fenster trug das graue Ersatzsymbol des Fenstermanagers, die Seitenleiste den Programmnamen als fette Textzeile, und zwischen Programmstart und Hauptfenster stand nichts. Vier Programme, die eine...
sloogy/Kontaktmanager
freizeitmanager/branding.py
.py
cb3b5c37629e7215
7
0
"""Melder fuer Stellen, die scheitern duerfen - aber nicht schweigen. Es gibt Stellen, an denen ein Fehler den Ablauf nicht aufhalten darf: ein Uebersetzungslauf ueber hunderte Qt-Objekte, eine Menue-Verdrahtung, das Aufraeumen alter Dateien. Bricht dort einer ab, verliert der Nutzer mehr, als der Fehler wert ist. Bi...
sloogy/Kontaktmanager
freizeitmanager/defensive_log.py
.py
318f39b7f0b8f47a
7
0
"""Restriktive Dateirechte für sensible Dateien. Die Datenbank enthält Namen, Geburtstage, Telefonnummern und private Notizen zu anderen Menschen - personenbezogene Daten Dritter, die diese dem Programm nie selbst anvertraut haben. Erzeugt wurde sie bisher mit dem Standard-umask, auf typischen Linux-Systemen also **06...
sloogy/Kontaktmanager
freizeitmanager/file_permissions.py
.py
d14514072c0871d6
7
0
"""Uebersetzungen: laedt die Sprach-JSONs und stellt ``t()`` bereit. Aufbau bewusst wie in FPM, damit die LifePlanner-Module gleich funktionieren: Schluessel in Punktschreibweise, Deutsch als Rueckfallebene, fehlende Schluessel liefern den Schluessel selbst zurueck statt zu scheitern. Datumsformate gehoeren mit zur S...
sloogy/Kontaktmanager
freizeitmanager/i18n/translator.py
.py
49c00069a7a7f014
7
0
"""Meldungen des FreizeitManagers an das LifePlanner-Dashboard. Der Host zeigt seit LifePlanner 0.5.16 auf seiner Übersichtsseite, was die Module melden. Das Schema ``lifeplanner.notice.v1`` stammt aus genau diesem Modul: ``publish_focus`` schrieb solche Meldungen (kind, urgency, headline, detail) als einziges — nur e...
sloogy/Kontaktmanager
freizeitmanager/integration/lifeplanner_notices.py
.py
9e1adc87c78a7188
7
0
"""Modulweit gemeinsames Theme. Der Modul-Host-Vertrag verbietet den Zugriff auf fremde Datenbanken. Ein gemeinsames Erscheinungsbild fuer BudgetManager, FPM, FreizeitManager und den LifePlanner selbst darf also nicht ueber gegenseitige Settings-Zugriffe entstehen, sondern nur ueber eine versionierte Datei im Bridge-O...
sloogy/Kontaktmanager
freizeitmanager/integration/shared_theme.py
.py
9293a1e208058236
7
0
"""Import einer Personenliste aus CSV oder Excel. Der Zweck ist der Erststart: wer seine Kontakte schon in einer Tabelle hat, soll sie nicht abtippen muessen. Die Spalten werden erkannt, statt eine feste Reihenfolge zu verlangen - echte Adressbuchexporte haben nie dieselbe. Bewusste Entscheidungen: * **Lesen und Sch...
sloogy/Kontaktmanager
freizeitmanager/logic/contact_import.py
.py
56c2255dce0e3168
7
0
"""Fokus-Cockpit. Vorbild BudgetManager: Das Cockpit beantwortet nicht "wie steht alles?", sondern "was waere jetzt dran?". Vorbild FPM: leere Bereiche verschwinden, und im ruhigen Zustand erscheint eine kompakte Entwarnung statt einer leeren Tabelle. Deshalb liefert dieser Service maximal ``focus.max_suggestions`` E...
sloogy/Kontaktmanager
freizeitmanager/logic/dashboard_service.py
.py
a22b9280a0432863
7
0
"""Beziehungsfrische. Das alte Modell kannte nur ``letztes_treffen``. Damit setzt ein "Happy Birthday" per WhatsApp einen engen Freund fuer 30 Tage zurueck. Stattdessen bekommt jede Interaktion eine Wirkung zwischen 0 und 1, die mit der Zeit exponentiell abklingt. Die Halbwertszeit ist der gewuenschte Kontaktrhythmus...
sloogy/Kontaktmanager
freizeitmanager/logic/freshness.py
.py
25c1b6ad4edcdcdd
7
0
"""Nur eine Instanz je Datenordner. Zwei Instanzen auf demselben Datenordner sind kein theoretisches Problem: Die zweite liest den Stand beim Start, die erste schreibt weiter, und wer zuletzt speichert gewinnt. Der Nutzer merkt es erst, wenn Eingaben verschwunden sind. Gesperrt wird ausdruecklich nur der Datenordner,...
sloogy/Kontaktmanager
freizeitmanager/single_instance.py
.py
e953105c614e9157
7
0
"""Markenbilder als Qt-Objekte - mit Rueckfall, wenn eines fehlt. Die Regel dieses Moduls: Ein fehlendes oder unlesbares Bild darf nie eine leere Flaeche, ein Loch im Layout oder einen Absturz erzeugen. Alle Funktionen geben in diesem Fall ``None`` zurueck, und die Aufrufstellen lassen die Flaeche dann ganz weg statt ...
sloogy/Kontaktmanager
freizeitmanager/ui/branding.py
.py
946a1a0b7ef43544
7
0
"""Hilfe in der Anwendung: Themen links, Text rechts, Suche darueber. Bewusst themenbasiert und nicht als ein langer Fliesstext: Wer Hilfe oeffnet, sucht eine Antwort, nicht eine Lektuere. Das vollstaendige Handbuch liegt daneben und wird ueber den Knopf im Browser geoeffnet. Die Texte stehen in den Sprachdateien unt...
sloogy/Kontaktmanager
freizeitmanager/ui/help_dialog.py
.py
c1246bb516166bad
7
0
"""Hauptfenster mit Sidebar und Einfach-/Expertenmodus. Der FreizeitManager startet bewusst im Einfachmodus (Lehre aus FPM 0.2.76): Cockpit und Kontakte reichen fuer den Alltag. Die pruefbaren und konfigurierbaren Teile bleiben erhalten, nur nicht im Weg. """ from __future__ import annotations from PySide6.QtCore imp...
sloogy/Kontaktmanager
freizeitmanager/ui/main_window.py
.py
7938f85ccb73d91b
7
0
"""Menüleiste des Hauptfensters – Aufbau nach der BudgetManager-Vorlage. Der FreizeitManager hatte bis Loop 33 keine, genau wie FPM bis Loop 32: Alles lief über Seitenleiste und Tastenkürzel. Für sich genommen bedienbar, aber der BudgetManager ist die Design-Vorlage der Suite, und dort gibt es Datei / Ansicht / Extras...
sloogy/Kontaktmanager
freizeitmanager/ui/menu_bar.py
.py
41e06f851dc8241e
7
0
"""Farben und Knopfstile aus dem aktiven Theme. Bewusst Funktionen statt Konstanten: Ein Modul-Dict wird beim Import ausgewertet und wuerde das Theme einfrieren, das beim Programmstart aktiv war. Ein Wechsel zur Laufzeit haette dann keine Wirkung - derselbe Grund, aus dem auch die Uebersetzungen lazy aufgeloest werden...
sloogy/Kontaktmanager
freizeitmanager/ui/theme.py
.py
ebc2f88673cee1ef
7
0
#!/usr/bin/env python3 """FreizeitManager - Einstiegspunkt. Laeuft eigenstaendig und als LifePlanner-Modul. Im Modulbetrieb gibt der Host den Datenordner ueber Umgebungsvariablen vor (siehe freizeitmanager/paths.py). """ from __future__ import annotations import logging import os import sys from pathlib import Path ...
sloogy/Kontaktmanager
main.py
.py
95fa93fbab64fbf3
7
0
"""Schreiben, das einen Stromausfall uebersteht. Loop 13 raeumte kaputte Einstellungsdateien auf, Loop 21 fand denselben Fall in FPM noch einmal. Loop 27 geht an die Ursache: Wer eine Datei an Ort und Stelle ueberschreibt, hinterlaesst bei einem Absturz die halbe. Alle vier Programme der Suite fuehren diesen Test unt...
sloogy/Kontaktmanager
tests/test_atomic_write.py
.py
2e2a6cfc04fa5111
7.5
0
"""Anstehende Geburtstage im Cockpit. Die Raender sind hier die eigentliche Arbeit: der Jahreswechsel, der 29. Februar und der Fall ohne Jahrgang, in dem es kein Alter zu nennen gibt. """ from __future__ import annotations from datetime import date from freizeitmanager.database.models import STATUS_ARCHIVED from fre...
sloogy/Kontaktmanager
tests/test_birthdays.py
.py
ac5b541368653126
7.5
0
import albumentations as A import numpy as np from utils import overlap_with_alpha class RandomDust(A.RandomFog): ''' Наложение пылевой взвеси на изображение. Действует по аналогии с аlbumentations.RandomFog, но имеет доп. параметр (цвет пыли) и не размывает изображение. ''' def __init__(self...
NikitaShubin/dl_utils
alb_utils.py
.py
4c202d1f4e4678ac
7
0
#!/usr/bin/env python3 """set_symbolic_flag.py - нейтрализация конфликта двойных LLVM/MLIR. Колёса triton и tensorflow статически линкуют собственные копии LLVM/MLIR и экспортируют её символы наружу. Кто из них загрузился в процесс первым - занимает глобальное пространство имён, после чего статические инициализаторы в...
NikitaShubin/dl_utils
docker/set_symbolic_flag.py
.py
1fae429091ab34d3
7
0
"""Тесты для модуля pt_utils.py.""" import tempfile from collections.abc import Iterator from pathlib import Path from unittest.mock import patch import cv2 import numpy as np import pytest import torch from pt_utils import ( AutoDevice, Receiver, SegDataset, Sender, get_redused_shape, has_va...
NikitaShubin/dl_utils
tests/test_pt_utils.py
.py
64cf68ec7e35f577
7.5
0
# Для того, чтобы модуль keras_utils использовал именно tf_keras, а не keras: import os os.environ['KERAS_MODULE'] = 'tf_keras' #os.environ['KERAS_MODULE'] = 'tf_keras' from functools import partial import tensorflow_model_optimization as tfmot from inspect import getcallargs from keras_utils import keras, get_keras_...
NikitaShubin/dl_utils
tfmot_utils.py
.py
dd4f8b8ee7bb4f93
7
0
"""REST-callable wrappers for cleanup executor patches. Sridhar 2026-06-03 — the cleanup patches (A3 negative-batch Repack and B3 Ghost Voucher repost) are `execute()` functions in patch modules, not @frappe.whitelist()'d, so they can't be triggered via /api/method. This module exposes thin whitelisted wrappers so th...
Avientek/avientek
avientek/api/cleanup_runner.py
.py
8f96784cf2aaff31
7
0
"""Ghost Voucher diagnostics & export. A "ghost voucher" is a submitted document (docstatus=1) that has no corresponding GL Entry (for financial docs) or Stock Ledger Entry (for inventory docs). They look submitted in list view but are invisible to accounting/stock reports. This module scans for them across all finan...
Avientek/avientek
avientek/api/ghost_vouchers.py
.py
64faab5e3e9b7414
7
0
""" Role-aware Number Card counters for Quotation workspace cards. Cancelled Quotations / Quotes Requested For Update on the Sales Team workspace used to count globally (~811 cancelled for everyone), which is noisy for a sales rep who only cares about their own pipeline. Per Jithin 2026-05-18: regular users should se...
Avientek/avientek
avientek/api/quotation_cards.py
.py
30dc7d58adf1b2c5
7
0
# Copyright (c) 2026, Avientek and contributors # For license information, please see license.txt import frappe from frappe.model.document import Document class AvientekSettings(Document): def on_update(self): """Rahul 2026-05-22: when the Issued Bank Edit Roles table changes, regenerate the Payment Request For...
Avientek/avientek
avientek/avientek/doctype/avientek_settings/avientek_settings.py
.py
bd6c86de7194619f
7
0
# Copyright (c) 2026, Avientek and contributors # For license information, please see license.txt import frappe from frappe import _ from frappe.model.document import Document class DemoUnitRequest(Document): def before_submit(self): self.status = "Approved" def on_cancel(self): self.db_set("status", "Cancell...
Avientek/avientek
avientek/avientek/doctype/demo_unit_request/demo_unit_request.py
.py
1d2936c84233321a
7
0
# _utils/dedup.py from ._record_types import RecordStream, RecordUniqueKeyExtractor, UniqueRecordStream def deduplicate_records(extract_key: RecordUniqueKeyExtractor) -> UniqueRecordStream: """ Build a deduplicator for an async record stream, keyed by an extracted value. Returns a coroutine that consum...
gregorykelleher/equity-aggregator
src/equity_aggregator/adapters/data_sources/_utils/dedup.py
.py
46be2e240f48ef6b
7.24
2
# lseg/lseg.py import logging from equity_aggregator.adapters.data_sources._utils import make_client from equity_aggregator.adapters.data_sources._utils._record_types import ( EquityRecord, RecordStream, ) from equity_aggregator.storage import load_cache, save_cache from ._utils import parse_response from .s...
gregorykelleher/equity-aggregator
src/equity_aggregator/adapters/data_sources/discovery_feeds/lseg/lseg.py
.py
f13936b362dd794a
7.24
2
# sec/sec.py import logging from httpx import AsyncClient from equity_aggregator.adapters.data_sources._utils import ( deduplicate_records, make_client, ) from equity_aggregator.adapters.data_sources._utils._record_types import ( EquityRecord, RecordStream, ) from equity_aggregator.storage import loa...
gregorykelleher/equity-aggregator
src/equity_aggregator/adapters/data_sources/discovery_feeds/sec/sec.py
.py
4ac728959eb17ee6
7.24
2
# stock_analysis/stock_analysis.py import logging from httpx import AsyncClient from equity_aggregator.adapters.data_sources._utils import ( deduplicate_records, make_client, ) from equity_aggregator.adapters.data_sources._utils._record_types import ( EquityRecord, RecordStream, ) from equity_aggrega...
gregorykelleher/equity-aggregator
src/equity_aggregator/adapters/data_sources/discovery_feeds/stock_analysis/stock_analysis.py
.py
93b18bf1b7b424af
7.24
2
# tradingview/tradingview.py import logging import math from httpx import AsyncClient from equity_aggregator.adapters.data_sources._utils import make_client from equity_aggregator.adapters.data_sources._utils._record_types import ( EquityRecord, RecordStream, ) from equity_aggregator.storage import load_cach...
gregorykelleher/equity-aggregator
src/equity_aggregator/adapters/data_sources/discovery_feeds/tradingview/tradingview.py
.py
e15f70f1f0d608fb
7.24
2
# xetra/xetra.py import asyncio import logging from httpx import AsyncClient from equity_aggregator.adapters.data_sources._utils import ( deduplicate_records, make_client, ) from equity_aggregator.adapters.data_sources._utils._record_types import ( EquityRecord, RecordStream, ) from equity_aggregator...
gregorykelleher/equity-aggregator
src/equity_aggregator/adapters/data_sources/discovery_feeds/xetra/xetra.py
.py
e7ef9013471ca5d0
7.24
2
# gleif/gleif.py import asyncio import logging from collections.abc import AsyncIterator, Callable from contextlib import asynccontextmanager import httpx from equity_aggregator.storage import load_cache, save_cache from .download import download_and_build_index logger = logging.getLogger(__name__) @asynccontext...
gregorykelleher/equity-aggregator
src/equity_aggregator/adapters/data_sources/enrichment_feeds/gleif/gleif.py
.py
df6510b0e7649dd3
7.24
2
# _utils/fuzzy.py import logging from rapidfuzz import fuzz, utils logger: logging.Logger = logging.getLogger(__name__) def rank_all_symbols( quotes: list[dict], *, name_key: str, expected_name: str, expected_symbol: str, min_score: int = 0, ) -> list[str]: """ Rank all matching sym...
gregorykelleher/equity-aggregator
src/equity_aggregator/adapters/data_sources/enrichment_feeds/yfinance/_utils/fuzzy.py
.py
f61e02c9ae4dd23f
7.24
2
# api/quote_summary.py import logging from collections.abc import Iterable, Mapping import httpx from .._utils import safe_json_parse from ..session import YFSession logger = logging.getLogger(__name__) async def get_quote_summary( session: YFSession, ticker: str, modules: Iterable[str] | None = None,...
gregorykelleher/equity-aggregator
src/equity_aggregator/adapters/data_sources/enrichment_feeds/yfinance/api/quote_summary.py
.py
756ddfa503c17749
7.24
2
# yfinance/ranking.py from ._utils import rank_all_symbols def filter_equities(quotes: list[dict]) -> list[dict]: """ Filter out any quotes lacking a longname or symbol. Note: The Yahoo Finance search quote query endpoint returns 'longname' and 'shortname' fields in lowercase. Args:...
gregorykelleher/equity-aggregator
src/equity_aggregator/adapters/data_sources/enrichment_feeds/yfinance/ranking.py
.py
bfb05eecd16d1602
7.24
2
# yfinance/transport.py import asyncio import logging from collections.abc import Callable import httpx from equity_aggregator.adapters.data_sources._utils import make_client logger: logging.Logger = logging.getLogger(__name__) # Type aliases OnResetFn = Callable[[], None] ClientFactory = Callable[[], httpx.AsyncC...
gregorykelleher/equity-aggregator
src/equity_aggregator/adapters/data_sources/enrichment_feeds/yfinance/transport.py
.py
55d2221b736117c0
7.24
2
""" Simple function-style cache middleware factory for FastAPI/Starlette. Usage: from api.middleware.cache_middleware import create_cache_middleware app.middleware("http")(create_cache_middleware(cache_methods={"GET"}, default_ttl=5)) This middleware is typically added to the FastAPI app with the function-sty...
cubismod/inky-mbta-tracker
inky-mbta-tracker/api/middleware/cache_middleware.py
.py
ec334c0ece76089a
7.3
3
from functools import wraps from inspect import iscoroutinefunction from typing import Awaitable, Callable, ParamSpec, TypeVar from fastapi import Request, Response from slowapi.util import get_remote_address from starlette.middleware.base import BaseHTTPMiddleware from api.core import logger class HeaderLoggingMid...
cubismod/inky-mbta-tracker
inky-mbta-tracker/api/middleware/header_middleware.py
.py
a26ef97cd9701bf8
7.3
3
""" Transaction ID middleware for FastAPI. Automatically generates user query transaction IDs for all incoming requests and ensures they propagate through the request lifecycle. """ import logging import time from typing import Awaitable, Callable from fastapi import Request, Response from opentelemetry import trace...
cubismod/inky-mbta-tracker
inky-mbta-tracker/api/middleware/transaction_middleware.py
.py
aae6fd604e000fa7
7.3
3
#!/usr/bin/env python3 """ Script to compute SHA256 hashes of each class in shared_types.py and set variables for those hashes. """ import ast import hashlib from pathlib import Path from typing import List import click from pydantic import BaseModel def extract_class_source(file_path: str, class_name: str) -> str:...
cubismod/inky-mbta-tracker
inky-mbta-tracker/compute_class_hashes.py
.py
94387d25ec3d6354
7.3
3
#!/usr/bin/env python3 """ Healthcheck script for Docker container health monitoring. This script checks Redis connectivity and verifies that the main process is writing regular heartbeats. Exit code 0 indicates healthy, non-zero indicates unhealthy. """ import json import logging import os import sys from datetime i...
cubismod/inky-mbta-tracker
inky-mbta-tracker/healthcheck.py
.py
336945e0ff80d213
7.3
3
import json import logging import os import re from datetime import UTC, datetime from opentelemetry import trace from opentelemetry.trace import format_span_id, format_trace_id class TraceContextFilter(logging.Filter): """Filter that injects OpenTelemetry trace context and business transaction IDs into log reco...
cubismod/inky-mbta-tracker
inky-mbta-tracker/logging_setup.py
.py
c229f4abd90075f7
7.3
3
""" OpenTelemetry utilities for trace context propagation and span management. This module provides helpers for working with OTEL in anyio concurrent contexts, including context serialization for queue-based trace propagation, decorators for common tracing patterns, and business transaction ID management. """ import ...
cubismod/inky-mbta-tracker
inky-mbta-tracker/otel_utils.py
.py
42bc360877710768
7.3
3
"""Sentry SDK initialization and configuration.""" import logging import os from typing import Optional import sentry_sdk from sentry_sdk.integrations.aiohttp import AioHttpIntegration from sentry_sdk.integrations.logging import LoggingIntegration from sentry_sdk.integrations.redis import RedisIntegration logger = l...
cubismod/inky-mbta-tracker
inky-mbta-tracker/sentry_config.py
.py
9c34e8ac26a48ba3
7.3
3
''' Leetcode 1011. Capacity To Ship Packages Within D Days Given a series of weights and D days to ship them out, find the min capacity of the ship. Weights should be loaded by their given order in any day. Similar CodeSignal question: Given a series of 1*width blocks, put them by given order into k*width1 box layer b...
YL159/blog_app
problems/1011_Cap_Ship_Within_D_Days.py
.py
44106f81ae4295bd
7
0
''' Leetcode 1014. Best Sightseeing Pair Given an array of site arr of sightseeing values pick 2 different idx sites that maximize (value[i] + value[j] - (j-i)) Method 1: Rearrange the target criteria = (value[i] - (j-i)) + value[j] Thus for each later idx j, find the max (value[i] - (j-i)) => it is distance downgrad...
YL159/blog_app
problems/1014_Best_Sightseeing_Pair.py
.py
126a905108eb5ac8
7
0
''' Leetcode 1015. Smallest Integer Divisible by K Find the length of some decimal int 1...1 that is divisible by k. If no such int, return -1 Method 1 Try from 1, 11, 111, ... but this method actually test each 1...1 and divides k, storing bigger numbers in memory Method 2 Let 1[n] be 1...1 int having n*1s Let k = 7...
YL159/blog_app
problems/1015_Smallest_Int_Div_K.py
.py
efd5feafad12f535
7
0
''' Leetcode 1019. Next Greater Node In Linked List Given a linked list, return an array, arr[i] = next greater node value of the node at index i Use monotonically decreasing stack to record (node value, position) see so far. If current node value is greater than top of stack, pop it and update arr. ''' from typing im...
YL159/blog_app
problems/1019_Next_Greater_Node_Linked_List.py
.py
1a183bea021fddb3
7
0
''' Leetcode 1020. Number of Enclaves In a matrix of 1/0, find the total of lands(1) completely surrounded by sea(0) Use BFS on any land reaching the edge of matrix, and label them 0 Then sum the matrix to get the total of remaining lands. ''' from typing import List class Solution: def numEnclaves(self, grid: Li...
YL159/blog_app
problems/1020_Number_of_Enclaves.py
.py
b9d2e04ff84800a7
7
0
''' Leetcode 1024. Video Stitching Given the (start, end) series of clips, find the min # of clips that can cover [0, time] interval Here provides a state machine greedy solution. Decides a current holding end time, check how far away other clips can make while 'hooking' up with current clip Implicitly select the hook...
YL159/blog_app
problems/1024_Video_Stitching.py
.py
d894b07246689eb8
7
0
''' Leetcode 1027. Longest Arithmetic Subsequence Given a list of ints, len >= 2 Find the longest subseq that is an arithmetic sequence. Method 1, incremental, group difference and update each tail's length For each new int, it may produce some new difference d with previous ints => that d may be the d of answer subs...
YL159/blog_app
problems/1027_Longest_Arith_Subseq.py
.py
4eb878fcd640805b
7
0
''' Leetcode 1031. Maximum Sum of Two Non-Overlapping Subarrays Given a number list and 2 segment length, find the max sum of 2 non-overlapping subarrays of the num list, each of given length. Use prefix sum to get the candidate subarray sums of 2 lengths. Loop on 1 length, find the max sum of the other length's subar...
YL159/blog_app
problems/1031_Maxi_Sum_Two_Subarr.py
.py
efbd2d8635b0049c
7
0
''' Leetcode 1038. Binary Search Tree to Greater Sum Tree Given a BST, return the tree where each node value = sum(all values in the BST that >= node value) 1. Intuitively, we can extract the in-order # array from BST, the sum of all greater values are just suffix sum of the array Then make a node value -> suffix sum ...
YL159/blog_app
problems/1038_BST_Greater_Sum_Tree.py
.py
f554588ffec398af
7
0
''' Leetcode 1039. Minimum Score Triangulation of Polygon Given a list of n vertices of a convex polygon in clock-wise, each with a positive weight. The ploygon can be divided into n-2 triangles without intersectiong each other, each using 3 of the vertices. The weight of a triangle is the product of vertices' weight, ...
YL159/blog_app
problems/1039_Min_Score_Triangu_of_Polygon.py
.py
bd3b0e5516548464
7
0
''' Leetcode 1043. Partition Array for Maximum Sum Partition an array into contiguous subarrays with max length k, replace each subarray with its max value, get the max sum of array Use DP[i] to remember the max result of arr[:i]. Each new result comes from the max of k calculations: DP[i-j] + max(arr[i-j+1:i+1])*j, f...
YL159/blog_app
problems/1043_Partition_Arr_for_Max_Sum.py
.py
f7fae87a3c4beb87
7
0
''' Leetcode 1048. Longest String Chain Find longest string chain where each is a predecessor of its next. Reduce from longest words, check if any predecessor exists in next layer. Record the length of the chain a word can form. ''' from typing import List import collections class Solution: def longestStrChain(se...
YL159/blog_app
problems/1048_Longest_Str_Chain.py
.py
007a09114e13c71f
7
0
''' Leetcode 1061. Lexicographically Smallest Equivalent String Consider an edge between s1[i] -- s2[i]. Based on above graph, find given baseStr's smallest lexicographically equivalent string Find the graph's connected components and their smallest char respectively. Each baseStr letter, if in the graph, would then b...
YL159/blog_app
problems/1061_Lexico_Smallest_Str.py
.py
40fc752ac4f215cc
7
0
''' Leetcode 1079. Letter Tile Possibilities Given a series of letter tiles, find ways to arrange them. From 1 to all tiles There are 26 different tiles. Arrangements are different if letters are different at some idx. Thus we can fix each position with different letters, by back tracking in recursive calls: For ABCDD...
YL159/blog_app
problems/1079_Letter_Tile.py
.py
e0a3819375bc02c8
7
0
''' Leetcode 1089. Duplicate Zeros Insert one additional 0 after each 0 in arr in place. Discard any element in result that exceeds arr length. Method 1: Queuing all insertion elements using deque, work from left. Time O(n), Space O(n) Method 2: Count elements that can enter final arr, work from right. Each original ...
YL159/blog_app
problems/1089_Duplicate_Zeros.py
.py
d293e4340be0cafd
7
0
''' Leetcode 1110. Delete Nodes And Return Forest Delete some nodes from a binary tree, return the remaining forest as list Use DFS to check each root and children, recursively return the remaining valid roots Be sure to ignore the propagated 'roots' if it has an ancestor ''' from typing import Optional, List # Defin...
YL159/blog_app
problems/1110_Delete_Nodes_Get_Forest.py
.py
589e91fb22c1ac7f
7
0
''' Leetcode 1123. Lowest Common Ancestor of Deepest Leaves Find the neareast common ancestor of all deepest leaves of a BT Method 1, dfs post-order find paths to deepest nodes, compare them for LCA DFS recursively dig for the deepest leaves and their paths, should be of the same length Then find the farthest common n...
YL159/blog_app
problems/1123_Lowest_Common_Anc_Deepest.py
.py
e5a4caf6d066ccb3
7
0
''' Leetcode 1130. Minimum Cost Tree From Leaf Values Given an in-order traversal list of leaf node values, for all the trees from it, get the min sum of non-leaf nodes Here is a memo brutal solution of all possible trees. Extracted max matrix out from the main dp loop to reduce main loop time complexity from O(n^4) t...
YL159/blog_app
problems/1130_Min_Cost_Tree_From_Leaf.py
.py
d9608042bde3f3c5
7
0
''' Leetcode 1143. Longest Common Subsequence Find the longest common subseq between 2 strings. New lcs is built on existing lcs of smaller prefix substrings. Make a DP matrix of lcs that keeps the lcs of text1[:i] and text2[:j]. ''' class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> in...
YL159/blog_app
problems/1143_Longest_Common_Subseq.py
.py
c4405404e2b4673f
7
0
''' Leetcode 1155. Number of Dice Rolls With Target Sum Given n dice ordered, each rolls [1...k] points. Find ways of dice rolls that sum up to target. f(n, k, t) = sum(f(n-1, k, t-i) for i in [1...k]) Thus build DP array as result array from 1 dice to n dice for possible sums respectively. And a prefix sum array is n...
YL159/blog_app
problems/1155_Num_Dice_Rolls_Target_Sum.py
.py
3d41f86a5570e23a
7
0
''' Leetcode 115. Distinct Subsequences Given str s and target str t, find # of all distinct index-wise subsequence of s that equals t Traverse s from left to right (or reverse) e.g. s = babgag, t = bag At 1st 'g': needed by prev 'ba', thus # of 'bag' should increase # of cur 'ba' (cur 1) At 2nd 'g': needed by 'ba' ag...
YL159/blog_app
problems/115_Distinct_Subseq.py
.py
b1208378b342e1da
7
0
''' Leetcode 1170. Compare Strings by Frequency of the Smallest Character Given a word list, f(word) = freq(min char of word) For each query str, find # of words that f(word) > f(query) Each word & query str can be precomputed into an int => Find # of int in word list, that w_int > q_int Thus we get the result int li...
YL159/blog_app
problems/1170_Compare_Str_Freq_of_Smallest_Char.py
.py
6ce35899823b54f8
7
0
''' Leetcode 1171. Remove Zero Sum Consecutive Nodes from Linked List Given the head of a linked list, recursively remove any sub linked list that sum(node.val) = 0 Return 1 of valid result Idea is to regard the list as a list of numbers, make prefix sum at each idx. A prefix sum that was seen before, indicates the su...
YL159/blog_app
problems/1171_Remove_0_Sum_Consec_Nodes.py
.py
fff712b4a4f0cf37
7
0
''' Leetcode 117. Populating Next Right Pointers in Each Node II For each node in a binary tree, populate 'next' pointer to its right neighbor in the same layer Other than BFS using O(n) space, here keep finished layer's head reference and O(1) space generate current layer's pointers ''' # Definition for a Node. clas...
YL159/blog_app
problems/117_Tree_Next_Right_II.py
.py
4d060ec5ebbe4c32
7
0
''' Leetcode 1190. Reverse Substrings Between Each Pair of Parentheses Given a string with valid parentheses, expand parentheses by reversing each pair's content. Use stack to record the current depth and buffered chars of the same depth Eventually make stack[0] looks the same as the given string s if printed out. The...
YL159/blog_app
problems/1190_Reverse_Substr_Between_Pair_Paren.py
.py
97cfd42ae988adbb
7
0
''' Leetcode 11. Container With Most Water Given a list of bar heights, spanning across x-axis [0, len(height)-1] int points. Any 2 bars and space in between forms a container. Find the max volume of those containers. Observation: Combination of all 2 bars is of O(n^2) order But if 2 bars are taller than some bars wit...
YL159/blog_app
problems/11_Container_With_Most_Water.py
.py
3e588717dff600e8
7
0
''' Leetcode 1202. Smallest String With Swaps Given a string, and a list of swappable pairs of idx. Can swap between the idx pairs any # of times. Find the lexicographically smallest string after swap. Basically, if we have pair [0, 3], [3, 2], [2, 6], we can swap [0, 2, 3, 6] letters for any target sequence. Thus the...
YL159/blog_app
problems/1202_Smallest_Str_With_Swaps.py
.py
072b3128c37158c9
7
0
''' Leetcode 1219. Path with Maximum Gold Find the max gold of any non-0 path in a grid. DFS back track on each non-0 cell. But some path may be traversed twice. ''' from typing import List class Solution: def getMaximumGold(self, grid: List[List[int]]) -> int: self.grid = grid self.m, self.n = le...
YL159/blog_app
problems/1219_Path_Max_Gold.py
.py
c46308dbdbfd186e
7
0
''' Leetcode 1233. Remove Sub-Folders from the Filesystem Given a list of folders, remove the path that is a sub folder of some other path in the list. Build a dict of dict as Trie. parent: dict(sub folder) If a path reaches its end in the Trie, record its idx in list. If the Trie gives idx value instead of dict while...
YL159/blog_app
problems/1233_Remove_SubFolders.py
.py
0f39b9d84d9f3795
7
0
''' Leetcode 1235. Maximum Profit in Job Scheduling Given (start, end, profit) triples as jobs, find max profit from taking non-overlapping jobs # same as #2008. Maximum Earnings From Taxi Use incremental DP on the end points of all these jobs. Max profit at end x = max(max(profit of taking 1 job ends at x + dp[right ...
YL159/blog_app
problems/1235_Max_Profit_Job_Schedule.py
.py
7a0f5c998a8de508
7
0
''' Leetcode 1247. Minimum Swaps to Make Strings Equal Given 2 equal length string of only 'x' and 'y' 1 operation: swap a char from str1 with some char from str2 Find min # of operations to make them equal, otherwise return -1 As example suggests, case 1, 'xx' 'yy' takes 1 op, so as 'yy' 'xx' case 2, 'xy' 'yx' take...
YL159/blog_app
problems/1247_Min_Swaps_to_Make_Str_Equal.py
.py
0482379dceaccd95
7
0
''' Leetcode 1248. Count Number of Nice Subarrays Get the number of subarrays containing exactly k odd numbers Get the indices of these odd numbers, pairwise find their left and right count of even numbers + 1, multiply ''' from typing import List class Solution: def numberOfSubarrays(self, nums: List[int], k: i...
YL159/blog_app
problems/1248_Count_Nice_Subarr.py
.py
91c3640fba4aee0c
7
0