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
""" Portfolio-Service: Berechnet strukturierte Portfolio-Daten für das Web-Dashboard. Logik extrahiert aus prompt.py:build_portfolio_summary(), aber als Dicts statt Strings. """ import json import logging from pathlib import Path logger = logging.getLogger(__name__) CONFIG_DIR = Path(__file__).parent.parent.parent.p...
waterbruh/Velora
src/web/services/portfolio_service.py
.py
8f14cd154d3b614f
7.15
1
"""Short-index cache: persist the last displayed tweet list for quick `show` access.""" from __future__ import annotations import json import logging import time from pathlib import Path from typing import List, Optional, Tuple from .models import Tweet logger = logging.getLogger(__name__) _CACHE_DIR = Path.home()...
warlockoussama/twitter-cli
twitter_cli/cache.py
.py
3baa7a5bd5c1316e
7.39
5
"""Shared constants for twitter-cli.""" import os import re import sys BEARER_TOKEN = ( "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs" "%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA" ) # Default Chrome version — updated by _best_chrome_target() at runtime _DEFAULT_CHROME_VERSION = "133" _chrom...
warlockoussama/twitter-cli
twitter_cli/constants.py
.py
88c944e8f17a35f7
7.39
5
"""Custom exceptions for twitter-cli. Provides a structured exception hierarchy for categorized error handling: - Authentication failures - API errors (rate-limit, not-found, forbidden) - Network errors - Query ID resolution failures Modeled after bilibili-cli/xiaohongshu-cli exception patterns. """ from __future__ ...
warlockoussama/twitter-cli
twitter_cli/exceptions.py
.py
a52a8b4494b7b977
7.39
5
"""Tweet filtering and engagement scoring. Scores tweets by a weighted engagement formula and filters by configurable rules (topN, min score, language, etc.). """ from __future__ import annotations from dataclasses import replace import math from typing import Any, Dict, List, Mapping, Optional, Sequence from .conf...
warlockoussama/twitter-cli
twitter_cli/filter.py
.py
cc5edb6e6a2d9384
7.39
5
"""Tweet formatter for terminal output (rich) and JSON export.""" from __future__ import annotations from typing import List, Optional from rich.console import Console from rich.markdown import Markdown from rich.panel import Panel from rich.table import Table from .models import Tweet, UserProfile from .timeutil i...
warlockoussama/twitter-cli
twitter_cli/formatter.py
.py
b12f5abd3e9e1e9b
7.39
5
"""Shared structured output helpers for twitter-cli.""" from __future__ import annotations import json import os import sys from typing import Any, Callable import click import yaml _OUTPUT_ENV = "OUTPUT" _SCHEMA_VERSION = "1" def default_structured_format(*, as_json: bool, as_yaml: bool) -> str | None: """Re...
warlockoussama/twitter-cli
twitter_cli/output.py
.py
b061de992a7671e9
7.39
5
"""Serialization helpers for Tweet and UserProfile models.""" from __future__ import annotations import json from typing import Any, Dict, Iterable, List, Optional from .models import Author, Metrics, Tweet, TweetMedia, UserProfile from .timeutil import format_local_time def tweet_to_dict(tweet: Tweet) -> Dict[str...
warlockoussama/twitter-cli
twitter_cli/serialization.py
.py
aa99d4ea396086c4
7.39
5
"""Time formatting utilities for twitter-cli. Converts Twitter API timestamps (e.g. "Sat Mar 08 12:00:00 +0000 2026") into human-friendly local time and relative time strings. """ from __future__ import annotations import logging from datetime import datetime, timezone from typing import Optional logger = logging.g...
warlockoussama/twitter-cli
twitter_cli/timeutil.py
.py
844c5cac927a5305
7.39
5
#!/usr/bin/env python3 """Log Claude Code tool operations for pattern analysis. PostToolUse hook - receives event JSON via stdin, appends a summary line to a JSONL log file. Large values (file contents, diffs) are truncated to keep logs compact. The log auto-rotates when it exceeds 10 MB (keeps the newer half). v2 ...
NaghamYehya/claude-recall
hooks/log-operations.py
.py
78d1629848ccc207
7.15
1
import logging import os from neo4j import GraphDatabase, Driver from typing import Dict, Any, List, Optional logger = logging.getLogger(__name__) class GraphLayer: NARRATIVE = "NARRATIVE" SEMANTIC = "SEMANTIC" EPISODIC = "EPISODIC" SOCIAL = "SOCIAL" SYSTEM = "SYSTEM" PROCEDURAL = "PROCEDURAL"...
juliofernandes/NeuroForm
neuroform/memory/graph.py
.py
2014430b95ba4283
7.24
2
import logging from typing import Dict, Any, List, Optional import json import ollama from neuroform.memory.graph import KnowledgeGraph from neuroform.memory.amygdala import Amygdala logger = logging.getLogger(__name__) class AutonomousNeuroplasticity: """Uses LLM reasoning to determine memory strengthening, deca...
juliofernandes/NeuroForm
neuroform/memory/neuroplasticity.py
.py
b65d4515d202248c
7.24
2
import subprocess from neuroform.tools.manager import tool_registry def _osascript(script: str) -> str: """Executes pure AppleScript code via osascript.""" try: result = subprocess.run( ['osascript', '-e', script], capture_output=True, text=True, timeout=...
juliofernandes/NeuroForm
neuroform/tools/apple_script.py
.py
c33208d6d2ad5575
7.24
2
import os import shutil from pathlib import Path from neuroform.tools.manager import tool_registry # Safe bound to prevent reading enormous files or outputting too much MAX_BYTES = 100 * 1024 def read_file(path: str) -> str: """Reads the contents of a file.""" try: p = Path(path).resolve() if ...
juliofernandes/NeuroForm
neuroform/tools/filesystem.py
.py
c3a2a167c3481619
7.24
2
import urllib.request import urllib.parse from bs4 import BeautifulSoup from neuroform.tools.manager import tool_registry def duckduckgo_search(query: str, max_results: int = 3) -> str: """Performs a web search using DuckDuckGo HTML and returns snippets.""" try: url = "https://html.duckduckgo.com/html/...
juliofernandes/NeuroForm
neuroform/tools/web.py
.py
c3d85f293491e3cf
7.24
2
"""Tests for ContextStream — Token-based persistent conversation memory.""" import json import os import tempfile import pytest from neuroform.memory.context_stream import ( ContextStream, Turn, CompactionSummary, estimate_tokens, estimate_turn_tokens, COMPACTION_KEEP_RECENT, ) class TestTurn: def tes...
juliofernandes/NeuroForm
tests/test_context_stream.py
.py
36952587dee37656
7.74
2
#!/usr/bin/env python3 """ Test suite for Genesis Kernel — verifies all baked kernels and base kernel produce correct results against the Python reference implementation. Tests: 1. All 4 baked evolved kernels (1024x2048, 2048x512, 3072x2048, 2048x1536) 2. Base kernel fallback for non-baked dimensions (256x128) 3...
MEXIHACKER/genesis-kernel
tests/test_kernels.py
.py
4738aeba23728d1f
7.5
0
""" GenAI Travel Assistant - FastAPI Backend This module provides a REST API for interacting with a travel assistant AI agent. It uses Google's Agent Development Kit (ADK) with Vertex AI (Gemini) to process user queries and provide travel-related assistance. The backend exposes two main endpoints: - POST /chat: Proce...
denmatrix02/travelbot-genai-gke
src/backend/main.py
.py
d836f7e72b68f56c
7.15
1
""" 位置合わせプロセッサー AKAZE/ORB特徴点マッチングで画像の位置ずれを補正 """ import cv2 import numpy as np from typing import Optional, Tuple from dataclasses import dataclass @dataclass class AlignConfig: """位置合わせ設定""" # AKAZEパラメータ akaze_threshold: float = 0.001 akaze_n_octaves: int = 4 akaze_n_octave_layers: int = 4 ...
SalmonSlapper/EasyPNGTuber
aligner.py
.py
6a713f4ddc6d1196
7.3
3
""" 画像合成プロセッサー マスク適用・フェザリング・合成処理を提供 """ import cv2 import numpy as np from dataclasses import dataclass @dataclass class CompositeConfig: """合成設定""" feather_width: int = 10 # フェザリング幅(ピクセル) class Compositor: """画像合成クラス(BGRA専用、ストレートアルファ)""" def __init__(self, config: CompositeConfig = None)...
SalmonSlapper/EasyPNGTuber
compositor.py
.py
355ac9a5306a2038
7.3
3
""" OpenCVユーティリティ """ import cv2 import numpy as np from pathlib import Path from typing import Optional, Tuple, List def load_image_as_bgra(path: str) -> np.ndarray: """画像をBGRAとして読み込み(アルファなしは255で補完) Args: path: 画像ファイルパス Returns: BGRA画像 (uint8) """ # 日本語パス対応: np.fromfile + imdeco...
SalmonSlapper/EasyPNGTuber
cv2_utils.py
.py
300cbaccbf8c7b25
7.3
3
#!/usr/bin/env python3 """ Grid Tiler - 画像タイリングツール 1枚の画像をNxNグリッドに並べて1枚の画像として出力する。 """ import sys import cv2 import numpy as np from pathlib import Path from typing import Optional from PySide6.QtWidgets import ( QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QFileDialog, QM...
SalmonSlapper/EasyPNGTuber
grid_tiler.py
.py
e13194b87cf0ef60
7.3
3
""" マスク描画キャンバスウィジェット """ import cv2 import numpy as np from PySide6.QtWidgets import QWidget from PySide6.QtCore import Qt, Signal, QPoint from PySide6.QtGui import QPainter, QPen, QBrush, QColor, QImage, QPixmap from cv2_utils import bgra_to_qimage class MaskCanvas(QWidget): """マスク描画キャンバス""" maskChanged = ...
SalmonSlapper/EasyPNGTuber
mask_canvas.py
.py
8d949bbd55521f06
7.3
3
""" プレビューウィジェット 画像表示とマスク編集 """ import cv2 import numpy as np from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel, QScrollArea from PySide6.QtCore import Qt, Signal, QRect, QPoint from PySide6.QtGui import QImage, QPixmap, QPainter, QColor, QMouseEvent from cv2_utils import convert_to_qimage, create_checkerboard...
SalmonSlapper/EasyPNGTuber
preview_widget.py
.py
5b8df8c224ec1be6
7.3
3
"""Diff a tracked file's stored snapshot against the live file, or against another stored snapshot. Usage: python diff.py <name> <version> # diff snapshot vs. live file python diff.py <name> <version1> <version2> # diff snapshot vs. snapshot python diff.py <name> <version> -c # char...
archau-51/version.1
diff.py
.py
4539c4d24a69789b
7
0
"""Scans the parent directory and snapshots any changed files into versions/<version>/. Run directly (`python main.py`) to perform a single scan, or import `track()` to call it from other tools (run.py, cli.py, tests). """ import glob import os import shutil from typing import Optional from versioning import incremen...
archau-51/version.1
main.py
.py
65340739d1a90036
7
0
"""Restore a file to a previous version, discarding any later snapshots of it. Usage: python restore.py <name> <version> """ import argparse import os import shutil from versioning import load_versions, save_versions, version_sort_key THIS_DIR = os.path.dirname(os.path.abspath(__file__)) VERSIONS_DIR = os.path.j...
archau-51/version.1
restore.py
.py
ee710fa792810384
7
0
"""Polls the parent directory for changes by re-running main.py on an interval. Usage: python run.py # check every 150 seconds (default) python run.py --interval 30 # check every 30 seconds """ import argparse import subprocess import sys import time def watch(interval: float) -> None: ""...
archau-51/version.1
run.py
.py
bb4cb004ca019b36
7
0
"""Tests for the pure version-number and versions.json helpers in versioning.py.""" import os from versioning import increment_version, load_versions, save_versions def test_increment_simple_patch_bump(): assert increment_version("0.0.1") == "0.0.2" def test_increment_handles_multi_digit_patch(): # This is...
archau-51/version.1
test_versioning.py
.py
561ca2557d506e0b
7.5
0
from textual.app import App, ComposeResult from textual.widgets import Header, Footer, Button, Static import glob import os import subprocess import sys # Only keep actual version folders - versions.json lives alongside them in # versions/ but isn't itself a version, so filtering by isdir() (rather than # a hardcoded ...
archau-51/version.1
tui.py
.py
1d3e6bafeb362dc9
7
0
"""Pure, testable helpers for dotted version numbers and the versions.json store. These are kept free of filesystem-scanning side effects (that lives in main.py) so they're easy to unit test. """ import json import os # A segment (major/minor/patch) rolls over into the next-more-significant # segment once it reaches ...
archau-51/version.1
versioning.py
.py
810b83dabc022cfc
7
0
from __future__ import annotations import threading import time from typing import Callable def show_startup_progress( preload_func: Callable[[], None], estimate_seconds: int = 120, ) -> tuple[bool, str | None]: """使用 tkinter 显示现代风格的启动进度窗口""" import tkinter as tk from tkinter import ttk resu...
Jnewton-lab/JianYan
ui/startup_win32.py
.py
8567ace4b3519c08
7.24
2
from __future__ import annotations import sys import tempfile from pathlib import Path def _get_app_root() -> Path: """获取应用根目录,兼容打包和开发环境""" if getattr(sys, 'frozen', False): # PyInstaller 打包后,使用 EXE 所在目录 return Path(sys.executable).parent else: # 开发环境,使用源码目录 return Path(__...
Jnewton-lab/JianYan
utils/paths.py
.py
0ba97f44e936cb13
7.24
2
#!/usr/bin/env python3 import json import os import random import numpy as np from datetime import datetime from flask import Flask, render_template, request, jsonify from flask_cors import CORS import pickle from collections import deque os.makedirs('training/models', exist_ok=True) app = Flask(__name__, ...
shreyashreddy/Block-Reign
game_server.py
.py
6881aa1ef4212d18
7
0
# -*- coding: utf-8 -*- import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from pathlib import Path from tqdm import tqdm import matplotlib # 強制使用 Agg 後端以確保在 GitHub Actions 等無界面環境穩定執行 matplotlib.use('Agg') # 字體設定 (支援中日韓字元,確保簡繁中、日、韓文顯示正常) plt.rcParams['font.sans-serif'] = ['N...
Idkunku/taiwan-stock-monitor
analyzer.py
.py
83da9fa25bf7c8d6
7
0
# -*- coding: utf-8 -*- import os, time, random, json, subprocess import pandas as pd import yfinance as yf from datetime import datetime from concurrent.futures import ThreadPoolExecutor, as_completed from tqdm import tqdm from pathlib import Path # ========== 核心參數與路徑 ========== MARKET_CODE = "cn-share" DA...
Idkunku/taiwan-stock-monitor
downloader_cn.py
.py
ef59efe50d47bc46
7
0
# -*- coding: utf-8 -*- import os, io, time, random, sqlite3, requests import pandas as pd import yfinance as yf from io import StringIO from datetime import datetime from concurrent.futures import ThreadPoolExecutor, as_completed from tqdm import tqdm import urllib3 # 忽略 SSL 警告 (港交所官網有時會報憑證錯誤) urllib3.disa...
Idkunku/taiwan-stock-monitor
downloader_hk.py
.py
4bb1b439f193589c
7
0
# -*- coding: utf-8 -*- import os, sys, time, random, subprocess, sqlite3 import pandas as pd import yfinance as yf from datetime import datetime from concurrent.futures import ThreadPoolExecutor, as_completed from tqdm import tqdm # ====== 自動安裝必要套件 ====== def ensure_pkg(pkg_install_name, import_name): t...
Idkunku/taiwan-stock-monitor
downloader_jp.py
.py
81d04d6f681c322e
7
0
# -*- coding: utf-8 -*- import os, sys, time, random, logging, warnings, subprocess, json from pathlib import Path from concurrent.futures import ThreadPoolExecutor, as_completed from tqdm import tqdm import pandas as pd import yfinance as yf # ====== 自動安裝必要套件 ====== def ensure_pkg(pkg: str): try: ...
Idkunku/taiwan-stock-monitor
downloader_kr.py
.py
732c409b22d31c45
7
0
# -*- coding: utf-8 -*- import os import time import random import requests import pandas as pd import yfinance as yf from io import StringIO from concurrent.futures import ThreadPoolExecutor, as_completed from tqdm import tqdm from pathlib import Path # ========== 核心參數設定 ========== MARKET_CODE = "tw-shar...
Idkunku/taiwan-stock-monitor
downloader_tw.py
.py
1bb77d055df5c15e
7
0
# -*- coding: utf-8 -*- import os import time import random import json import requests import pandas as pd import yfinance as yf from datetime import datetime from io import StringIO from concurrent.futures import ThreadPoolExecutor, as_completed from tqdm import tqdm from pathlib import Path # ========...
Idkunku/taiwan-stock-monitor
downloader_us.py
.py
a16860b80e08bf67
7
0
# -*- coding: utf-8 -*- import os import time import argparse import traceback from datetime import datetime, timedelta # 導入自定義模組 import downloader_tw import downloader_us import downloader_hk import downloader_cn import downloader_jp import downloader_kr import analyzer import notifier def run_marke...
Idkunku/taiwan-stock-monitor
main.py
.py
fce3b5f92854a529
7
0
# -*- coding: utf-8 -*- import os import requests import resend import pandas as pd from datetime import datetime, timedelta class StockNotifier: def __init__(self): # 從環境變數讀取金鑰與 ID self.tg_token = os.getenv("TELEGRAM_BOT_TOKEN") self.tg_chat_id = os.getenv("TELEGRAM_CHAT_ID") ...
Idkunku/taiwan-stock-monitor
notifier.py
.py
fb7819fed3ebac2b
7
0
import re import builtins from canvas_sak.core import * # Safe functions allowed in formulas - explicitly from builtins SAFE_FUNCTIONS = { 'min': builtins.min, 'max': builtins.max, 'sum': builtins.sum, 'abs': builtins.abs, 'round': builtins.round, } SAFE_FUNCTION_NAMES = set(SAFE_FUNCTIONS.keys())...
SJSU-CS-systems-group/canvas_sak
canvas_sak/commands/derive_assignment_score.py
.py
34f1a404a2d83c23
7.24
2
from canvas_sak.core import * def format_date(dt_str): """Convert ISO date string to YYYY-MM-DD-hh:mm format in local timezone""" if not dt_str: return None dt = datetime.datetime.fromisoformat(dt_str.replace('Z', '+00:00')) local_dt = dt.astimezone() return local_dt.strftime('%Y-%m-%d-%H:...
SJSU-CS-systems-group/canvas_sak
canvas_sak/commands/list_due_dates.py
.py
47829ee0773c23f0
7.24
2
from canvas_sak.core import * def student_matches(login_id, name, name_filter, id_filter): """Return True if the student passes the --name and --id filters. name_filter is a case-insensitive substring match against the user's name. id_filter is an exact match against the user's login_id. Either may b...
SJSU-CS-systems-group/canvas_sak
canvas_sak/commands/list_grades.py
.py
466b3ee2eca44680
7.24
2
from canvas_sak.core import * def parse_date(date_str): """Convert YYYY-MM-DD-hh:mm format (local time) to ISO format for Canvas API""" if not date_str: return None dt = datetime.datetime.strptime(date_str, '%Y-%m-%d-%H:%M') local_dt = dt.astimezone() return local_dt.isoformat() def pars...
SJSU-CS-systems-group/canvas_sak
canvas_sak/commands/set_due_dates.py
.py
83d26013a3f28431
7.24
2
import click from canvas_sak.core import * # Navigation tabs that Canvas does not allow to be hidden or moved. UNHIDEABLE_TAB_IDS = {"home", "settings"} def _get_tabs(course): """Return the course navigation tabs sorted by their current position.""" tabs = list(course.get_tabs()) tabs.sort(key=lambda t:...
SJSU-CS-systems-group/canvas_sak
canvas_sak/commands/settings_navigation.py
.py
e306d5f898117319
7.24
2
from canvas_sak.core import * def process_assignment(assignment, update_kwargs, group_names=None, quizzes=None): """Update a single assignment and display its attributes.""" quiz_id = getattr(assignment, 'quiz_id', None) submission_types = getattr(assignment, 'submission_types', []) is_quiz = quiz_id ...
SJSU-CS-systems-group/canvas_sak
canvas_sak/commands/update_assignment.py
.py
ddb0635955ac52f6
7.24
2
from canvas_sak.core import * def parse_groups_file(f): """Parse assignment groups file. Format: GROUP_NAME: WEIGHT% assignment1 assignment2 ANOTHER_GROUP: WEIGHT% assignment3 Returns list of (group_name, weight, [assignment_names]) """ groups = [] cu...
SJSU-CS-systems-group/canvas_sak
canvas_sak/commands/update_assignment_groups.py
.py
95b05823636c78fe
7.24
2
from canvas_sak.core import * def process_quiz(quiz, update_kwargs): """Update a single quiz and display its attributes.""" # Update the quiz if there are changes if update_kwargs: info(f"updating quiz '{quiz.title}' with: {update_kwargs}") quiz = quiz.edit(quiz=update_kwargs) outp...
SJSU-CS-systems-group/canvas_sak
canvas_sak/commands/update_quiz.py
.py
8ee2f8fe5f031ed7
7.24
2
from collections import Counter from urllib.parse import urlparse import requests from bs4 import BeautifulSoup import canvas_sak.core as core from canvas_sak.core import * def parse_iso_date(dt_str): """Convert ISO date string to datetime object.""" if not dt_str: return None return datetime.da...
SJSU-CS-systems-group/canvas_sak
canvas_sak/commands/validate_course_setup.py
.py
d0e7954184164fe7
7.24
2
import re import markdownify import markdown def html2mdstr(html_str: str): """Converts html in string form to markdown""" md_str = markdownify.markdownify(html_str) return md_str def html2mdlist(html_list: list): """Converts html as a list of strings to markdown""" html_str = '\n'.join(html_li...
SJSU-CS-systems-group/canvas_sak
canvas_sak/md2fhtml.py
.py
32f2bcf27eae5b0d
7.24
2
"""Tests for extract_options in upload_canvas_course.""" from canvas_sak.commands.upload_canvas_course import extract_options class TestExtractOptions: def test_simple_key_value(self): assert extract_options("k=v") == {"k": "v"} def test_value_contains_equals_sign(self): """Bug repro: split(...
SJSU-CS-systems-group/canvas_sak
tests/test_extract_options.py
.py
5df98228dfccd237
7.74
2
"""Tests for letter-grade helpers in core.""" import pytest from canvas_sak.core import to_letter_grade, points_to_letter, letter_grades class TestPointsToLetter: def test_zero_returns_F_not_WU(self): """Bug repro: a literal 0 used to return 'WU' (withdrew unauthorized) because of the `if not po...
SJSU-CS-systems-group/canvas_sak
tests/test_letter_grades.py
.py
e526eab696c2a94f
7.74
2
"""Tests for header parsing in upload_canvas_course.py""" import pytest from canvas_sak.commands.upload_canvas_course import ( parse_headers, PAGE_KEYWORDS, DISCUSSION_KEYWORDS, ) class TestParseHeaders: """Test cases for the parse_headers function.""" def test_valid_keywords_parsed_correctly(se...
SJSU-CS-systems-group/canvas_sak
tests/test_parse_headers.py
.py
c0aa3620c510049f
7.74
2
"""Build cpv-viz data assets from the literature compilation table.""" from __future__ import annotations import csv import json from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable import numpy as np from astropy.time import Time ROOT_DIR = Path(__file__).resolve().parents[...
lgbouma/cpv
apps/cpv-viz/scripts/build_data.py
.py
a2c2dd2679ca7a54
7
0
"""Build a manifest of CPV vetter PDFs for cpv-viz.""" from __future__ import annotations import argparse import json from datetime import datetime from pathlib import Path from typing import Dict, List, Tuple ROOT_DIR = Path(__file__).resolve().parents[3] DEFAULT_OUTPUT = ROOT_DIR / "apps/cpv-viz/data/cpv_pdf_manif...
lgbouma/cpv
apps/cpv-viz/scripts/build_pdf_manifest.py
.py
b3d8d6c3dbc100b5
7
0
"""Refresh TESS sector coverage columns for the CPV concat table.""" from __future__ import annotations import argparse import logging import shutil from datetime import datetime from pathlib import Path from typing import Iterable import numpy as np import pandas as pd from astropy.time import Time ROOT_DIR = Path...
lgbouma/cpv
apps/cpv-viz/scripts/update_tess_sectors.py
.py
8900ac0bde214679
7
0
#!/usr/bin/env python """Export red_aware digitized points to fit-dips-ready CSVs. Writes one CSV per (CSV-epoch, band) for the 9 Tanimoto+2020 epochs that overlap Table 3 (18 datasets: I_C + one IR band each) into the shared literature-curve directory the fit-dips app reads from: <repo>/data/photometry/literature_...
lgbouma/cpv
apps/extract-points/export_to_fitdips.py
.py
0d255eaeaf0c4b22
7
0
"""Pixel <-> data calibration from detected major tick marks. Major ticks point inward from the spines. We read the x-tick pixel columns just inside the flux box's bottom (BJD) axis and the y-tick pixel rows just inside the left (relative flux) axis, then fit a linear pixel->data transform. The BJD tick values come fr...
lgbouma/cpv
apps/extract-points/extract_points/calibrate.py
.py
df61dfd5bd72099e
7
0
"""Separate the black data markers from the red model curve. Markers are black (low R,G,B); the model is red (high R, low G,B). JPEG compression leaves a reddish halo around the model, so the red mask is dilated a little before being subtracted from the black mask. """ from __future__ import annotations import numpy ...
lgbouma/cpv
apps/extract-points/extract_points/color_masks.py
.py
d87e2220e5bddee6
7
0
"""Orchestrate digitization: panels -> calibration -> markers -> data points. Produces, for every flux panel, the per-band digitized (BJD-offset, relative flux) points, plus a tidy long-form table across all panels. Note on the IR bands: Tanimoto et al. plot the IR series (K_s/J/H) with an arbitrary downward display ...
lgbouma/cpv
apps/extract-points/extract_points/extract.py
.py
12fa320a5a89e107
7
0
"""Image loading and basic color/grayscale helpers.""" from __future__ import annotations import os import numpy as np from PIL import Image HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) FIGURES = { "f12": os.path.join(HERE, "pasj_72_2_23_f12.jpeg"), "f13": os.path.join(HERE, "pasj_72_2_...
lgbouma/cpv
apps/extract-points/extract_points/image_io.py
.py
0fe08fc0c00753a9
7
0
"""Locate axes frames and isolate the flux subpanel of each panel. The figures are regular grids. Each panel is a tall 'Relative flux' box stacked over a short 'Residuals' box that share left/right spines. We detect spine lines as long continuous runs of dark pixels, reconstruct the grid, and return the flux box (the ...
lgbouma/cpv
apps/extract-points/extract_points/panels.py
.py
fc9ddb4b0a4b87ca
7
0
#!/usr/bin/env python """Digitize the Tanimoto et al. 2020 PTFO 8-8695 light-curve panels. Runs the full pipeline with BOTH extraction methods and writes results into separate subdirectories under output/ so they can be compared: output/per_marker/ Option 1: matched-filter per-marker detection output/cadence...
lgbouma/cpv
apps/extract-points/run_extract.py
.py
730a485e8f23a076
7
0
"""Smoke tests for the digitization pipeline. Run: python -m pytest tests/ (or) python tests/test_pipeline.py """ import os import sys import numpy as np sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from extract_points.image_io import load_rgb, dark_mask from extract_points.pa...
lgbouma/cpv
apps/extract-points/tests/test_pipeline.py
.py
4e3c1790d6c71840
7.5
0
""" Light-curve loaders for the heterogeneous CPV photometry formats. Every loader returns (t, flux, flux_err) as finite numpy arrays with the flux normalized to a median of 1. flux_err is the instrument-provided error if any (else None); note the fitting pipeline uses p2p_rms by default regardless. Patterns mirror ...
lgbouma/cpv
apps/fit-dips/fit_dips/loaders.py
.py
2775c69fa0e117ef
7
0
""" Render the measured dip depths into Table 3 ("Dip depths by bandpass", tab:dipdepths in papers/Bouma_2026_cgcd/ms.tex). We generate the FULL data-row body of that table -- both the "This work" rows and the refitted-literature rows -- in the exact column format: Star & Date (UT) & Band & $\\delta$ (\\%) & Ref....
lgbouma/cpv
apps/fit-dips/fit_dips/make_table.py
.py
919bfdc646377512
7
0
""" Dip + baseline models for CPV dimming events. The combined model evaluated over the non-flare points is F(t) = B(t; theta_b) - sum_i D_i(t; profile) where B is one of the baseline families (polynomial or Fourier) and D_i is a dip profile. Two dip profiles are supported and compared by BIC: "sech" : A * ...
lgbouma/cpv
apps/fit-dips/fit_dips/models.py
.py
c6ab589986f2aee0
7
0
""" Per-dataset JSON registry and processing-status tracking. One JSON file per dataset lives in apps/fit-dips/datasets/<id>.json and holds metadata, the data pointer, the user's labels, and the results of *all* fitted models plus the preferred model. """ import json import os from datetime import datetime, timezone ...
lgbouma/cpv
apps/fit-dips/fit_dips/registry.py
.py
9edbe5a8d3aad60b
7
0
"""Tests for the cross-band shared-duration joint dip fit. The physical constraint: for a given dip the total duration T14 = 2W and the mid-time t0 are IDENTICAL across bands, while depth A and ingress/egress fraction r = tau/W vary per band. These exercise fitting.fit_group_shared_dip on synthetic trapezoids and the ...
lgbouma/cpv
apps/fit-dips/tests/test_joint.py
.py
75640283c16971c3
7.5
0
"""Smoke tests for the N-panel shared-window labeler and epoch grouping. These exercise the GUI plumbing headlessly (Agg backend): a window dragged in one panel must propagate to all panels' spans, and each panel must classify its own points from the shared windows. We also check the (star, date_ut) + time-overlap gro...
lgbouma/cpv
apps/fit-dips/tests/test_multilabeler.py
.py
574ec34113ce8f53
7.5
0
"""Shared persistence for coincidence labels. A *label* marks an x-location in one mosaic column where a feature is judged to coincide in BOTH the Hα-EW (top) and Δflux (bottom) panels: kind='dip' local minima coincide -> drawn as a '|' tick kind='flare' local maxima coincide -> drawn as a 'v' tick Labels ...
lgbouma/cpv
apps/label-coincidences/label_coincidences/labels.py
.py
0a64b64d3897b133
7
0
#!/usr/bin/env python """Smoke tests for label-coincidences. Run: python tests/test_labels.py (with the cpv env) """ import os import sys import tempfile import matplotlib matplotlib.use("Agg") HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.dirname(HERE)) from label_coincidences imp...
lgbouma/cpv
apps/label-coincidences/tests/test_labels.py
.py
326c2e53bdbcd9a9
7.5
0
""" 1-d comet model CITE: * Zieba+2019 (actual portions of code directly copied!) * Brogi+2012 (original 1d formalism) Contents: | vcirc | P_to_a | rc_hat | disk_intensity | rho | impact_param | rchordit """ import numpy as np, matplotlib.pyplot as plt from astropy import units as u from ...
lgbouma/cpv
complexrotators/cometmodel.py
.py
507b8cfd0899af97
7
0
""" Tools when interpolating against isochrones. | get_Feiden2016 | get_PARSEC | nn_PARSEC_interpolator | PARSEC_interpolator """ import os from os.path import join from glob import glob from complexrotators.paths import DATADIR import pandas as pd, numpy as np, matplotlib.pyplot as plt from astropy import units as u,...
lgbouma/cpv
complexrotators/isochroneinterp.py
.py
ddb6cfdf4cc2465a
7
0
# __init__.py from typing import Dict, Tuple, Optional, List from starlette.responses import HTMLResponse, JSONResponse, Response from starlette.types import ASGIApp, Scope, Receive, Send import redis.asyncio as redis from .strategies import FixedWindowStrategy, MovingWindowStrategy STRATEGY_MAP = { "fixed": Fixed...
mongosh2006/fastapi-easylimiter
fastapi_easylimiter/middleware.py
.py
5fb390b15d189b94
7
0
# test_walletcore.py """ Tests for WalletCore module. """ import unittest from walletcore import WalletCore class TestWalletCore(unittest.TestCase): """Test cases for WalletCore class.""" def test_initialization(self): """Test class initialization.""" instance = WalletCore() self....
kiwiloveseth/WalletCore
test_walletcore.py
.py
c358b717ebe9966f
7.5
0
# walletcore.py """ Main module for WalletCore application. """ import argparse import logging import sys from typing import Optional class WalletCore: """Main class for WalletCore functionality.""" def __init__(self, verbose: bool = False): """Initialize with verbosity setting.""" self.v...
kiwiloveseth/WalletCore
walletcore.py
.py
1403e02d10b60870
7
0
#!/usr/bin/env python3 """ scrape_bensinpriser.py - Strict caps enforcement with pending counts tracked per (fuel, date) — this is the only way the cap can be enforced consistently, since the existing-row counts loaded from the CSV are also per (fuel, date). (An earlier version tracked pending counts per-fuel on...
FastAndFunky/gaspricescraper
scrapebensinpriser.py
.py
b1b710831626ea1c
7
0
#!/usr/bin/env python3 """ scrapebensinstation.py - Scrapes https://www.bensinstation.nu/ priceTable - Enforces CSV schema: Bolag,Bensinpris,Dieselpris,Etanol,Datum,ScrapeDate - Normalizes Datum universally to ISO YYYY-MM-DD (handles 'Idag','Igår','i förrgår', dd/mm, dd.mm, dd-mm, Swedish month names, ISO, etc.) - N...
FastAndFunky/gaspricescraper
scrapebensinstation.py
.py
c0e623053854d122
7
0
import contextlib from collections import namedtuple from collections.abc import Callable from typing import Any, Dict import torch import triton import triton.language as tl __all__ = ["set_batch_invariant_mode", "is_batch_invariant_mode_enabled", "disable_batch_invariant_mode", "enable_batch_invariant_mode"] def ...
Karmabhumi1/batch_invariant_ops
batch_invariant_ops/batch_invariant_ops.py
.py
b104eee8f514aed8
7.15
1
# cronscheduler.py """ Main module for CronScheduler application. """ import argparse import logging import sys from typing import Optional class CronScheduler: """Main class for CronScheduler functionality.""" def __init__(self, verbose: bool = False): """Initialize with verbosity setting.""" ...
DILLIGADF/CronScheduler
cronscheduler.py
.py
ff20632a767963af
7
0
# test_cronscheduler.py """ Tests for CronScheduler module. """ import unittest from cronscheduler import CronScheduler class TestCronScheduler(unittest.TestCase): """Test cases for CronScheduler class.""" def test_initialization(self): """Test class initialization.""" instance = CronSche...
DILLIGADF/CronScheduler
test_cronscheduler.py
.py
8a5b49e2f8767882
7.5
0
# File: config/development.py # Development environment configuration import os from datetime import timedelta class DevelopmentConfig: """Development configuration settings""" # Environment ENV = 'development' DEBUG = True TESTING = False # Database DATABASE_URL = os.environ.get...
Dhayalsanthosh/Python-Mastery-Hub
config/development.py
.py
2a271f51d69526e6
7
0
# File: config/production.py # Production environment configuration import os from datetime import timedelta class ProductionConfig: """Production configuration settings""" # Environment ENV = 'production' DEBUG = False TESTING = False # Database DATABASE_URL = os.environ.get('DA...
Dhayalsanthosh/Python-Mastery-Hub
config/production.py
.py
a27936f80417031d
7
0
# File: config/testing.py # Testing environment configuration import os from datetime import timedelta class TestingConfig: """Testing configuration settings""" # Environment ENV = 'testing' DEBUG = True TESTING = True # Database (using in-memory SQLite for fast tests) SQLALCHEMY...
Dhayalsanthosh/Python-Mastery-Hub
config/testing.py
.py
dba5acb1cf4870c4
7.5
0
# File: migrations/versions/001_initial_schema.py """Initial schema Revision ID: 001 Revises: Create Date: 2024-01-01 10:00:00.000000 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '001' down_revision = None branch_l...
Dhayalsanthosh/Python-Mastery-Hub
migrations/versions/001_initial_schema.py
.py
926c2b19dea40433
7
0
# File: migrations/versions/002_add_user_tables.py """Add user tables Revision ID: 002 Revises: 001 Create Date: 2024-01-01 11:00:00.000000 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '002' down_revision = '001' br...
Dhayalsanthosh/Python-Mastery-Hub
migrations/versions/002_add_user_tables.py
.py
f0e13e779ebeb5ff
7
0
# File: migrations/versions/003_add_progress_tracking.py """Add progress tracking tables Revision ID: 003 Revises: 002 Create Date: 2024-01-01 12:00:00.000000 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '003' down_...
Dhayalsanthosh/Python-Mastery-Hub
migrations/versions/003_add_progress_tracking.py
.py
bf29ad8985d55944
7
0
# File: migrations/versions/004_add_exercise_submissions.py """Add exercise submissions tables Revision ID: 004 Revises: 003 Create Date: 2024-01-01 13:00:00.000000 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '004'...
Dhayalsanthosh/Python-Mastery-Hub
migrations/versions/004_add_exercise_submissions.py
.py
e4f7b4cf578dbd91
7
0
# File: migrations/versions/005_add_achievements.py """Add achievements and gamification tables Revision ID: 005 Revises: 004 Create Date: 2024-01-01 14:00:00.000000 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '005...
Dhayalsanthosh/Python-Mastery-Hub
migrations/versions/005_add_achievements.py
.py
1704bb0713d8d4de
7
0
# File: scripts/migrate_db.py # Database migration management script import os import sys import argparse import subprocess import logging from datetime import datetime from pathlib import Path # Add project root to Python path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) try: fro...
Dhayalsanthosh/Python-Mastery-Hub
scripts/migrate_db.py
.py
b1a3ce1c2d764992
7
0
# File: scripts/seed_data.py # Sample data generation script for development and testing import os import sys import argparse import random import logging from datetime import datetime, timedelta from faker import Faker # Add project root to Python path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(...
Dhayalsanthosh/Python-Mastery-Hub
scripts/seed_data.py
.py
93b0daf1c177a751
7
0
# File: security/policies/password_policy.py """ Password Policy Implementation Enforces secure password requirements and validation rules """ import re import hashlib import secrets import string from datetime import datetime, timedelta from typing import Dict, List, Optional, Tuple from dataclasses import dataclass ...
Dhayalsanthosh/Python-Mastery-Hub
security/policies/password_policy.py
.py
184ca67ba241e529
7
0
""" CLI Commands Package Contains all command implementations for the Python Mastery Hub CLI. Each command module provides specific functionality with argument parsing and execution. """ from . import learn from . import progress from . import test from . import demo # Export command modules __all__ = [ "learn",...
Dhayalsanthosh/Python-Mastery-Hub
src/python_mastery_hub/cli/commands/__init__.py
.py
8ed26564c6b940dc
7
0
""" Learn Command - Interactive Learning Module Access Provides command-line access to all learning modules with interactive features. """ import argparse import asyncio from typing import List, Dict, Any from pathlib import Path from python_mastery_hub.core.basics import base as basics_base from python_mastery_hub....
Dhayalsanthosh/Python-Mastery-Hub
src/python_mastery_hub/cli/commands/learn.py
.py
110f101ed4a93139
7
0
""" CLI Interactive Package Interactive components for the Python Mastery Hub CLI including REPL, exercise runners, and interactive quizzes. """ from . import repl from . import exercises from . import quiz # Export interactive modules __all__ = [ "repl", "exercises", "quiz", ] # Interactive mode regi...
Dhayalsanthosh/Python-Mastery-Hub
src/python_mastery_hub/cli/interactive/__init__.py
.py
fa3c775001a8a503
7
0
""" Interactive CLI for Python Mastery Hub. Provides a comprehensive command-line interface for exploring Python concepts, running examples, and practicing with interactive exercises. """ import typer from typing import Optional, List from rich.console import Console from rich.table import Table from rich.panel impor...
Dhayalsanthosh/Python-Mastery-Hub
src/python_mastery_hub/cli/main.py
.py
1ef32105fc744357
7
0